diff --git a/examples/build_agents_by_code.ipynb b/examples/build_agents_by_code.ipynb new file mode 100644 index 00000000..e7fbabae --- /dev/null +++ b/examples/build_agents_by_code.ipynb @@ -0,0 +1,362 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Code to create agents and teams\n", + "\n", + "This notebook shows the code flow to create agents and teams using flo-ai" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 1, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "from flo_ai import FloSupervisor, FloAgent, FloSession, FloTeam, FloLinear\n", + "from langchain_openai import ChatOpenAI\n", + "# TODO router config needs fixing\n", + "from flo_ai.yaml.flo_team_builder import RouterConfig\n", + "from langchain_community.tools.tavily_search.tool import TavilySearchResults\n", + "from dotenv import load_dotenv\n", + "\n", + "load_dotenv()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Code to create a simple tea, with 2 agents, each agent having one tool of itself" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [], + "source": [ + "llm = ChatOpenAI(temperature=0, model_name='gpt-4o')\n", + "session = FloSession(llm).register_tool(\n", + " name=\"TavilySearchResults\",\n", + " tool=TavilySearchResults()\n", + ")\n", + "\n", + "researcher = FloAgent.Builder(session, \"Researcher\", \n", + " \"Do a research on the internet and find articles of relevent to the topic asked by the user\", [TavilySearchResults()]).build()\n", + "blogger = FloAgent.Builder(session, \"BlogWriter\", \n", + " \"Able to write a blog using information provided\", [TavilySearchResults()]).build()\n", + "\n", + "marketing_team = FloTeam.Builder(session, \"Marketing\", [researcher, blogger]).build()\n", + "r1 = FloSupervisor.Builder(session, \"Head-of-Marketing\", marketing_team).build()\n", + "flo_team_1 = r1.build_routed_team()\n" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "def draw_to_file(graph, filename: str, xray=False):\n", + " from PIL import Image as PILImage\n", + " import io\n", + " byte_image = graph.draw(xray)\n", + " with io.BytesIO(byte_image) as image_io:\n", + " image = PILImage.open(image_io)\n", + " image.save(filename)" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [], + "source": [ + "draw_to_file(flo_team_1, \"dk.png\", True)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "A second team created for doing editorial suggestions" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [], + "source": [ + "chief_editorial = FloAgent.Builder(session, \"Senior-Editor\", \n", + " \"Have a look at the article created and give editorial suggestions\", [TavilySearchResults()]).build()\n", + "\n", + "edit_team = FloTeam.Builder(session, \"Editorial-Team\", [chief_editorial]).build()\n", + "r2 = FloSupervisor.Builder(session, \"Editor-Team-Routing\", edit_team).build()\n", + "\n", + "editorial_team = r2.build_routed_team()\n", + "draw_to_file(editorial_team, \"editorial.png\", True)" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [], + "source": [ + "journal_company = FloTeam.Builder(session, \"Newspaper\", [flo_team_1, editorial_team])\n", + "\n", + "# TODO fix router config\n", + "r3 = FloLinear.Builder(session,\n", + " journal_company, \n", + " RouterConfig(**{\"name\" :\"Serial\", \"kind\": \"linear\"})).build()\n", + "\n", + "master_team = r3.build_routed_team()" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [], + "source": [ + "draw_to_file(master_team, \"master.png\")" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "\n", + "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n", + "\u001b[32;1m\u001b[1;3m\n", + "Invoking: `tavily_search_results_json` with `{'query': 'Cristiano Ronaldo biography'}`\n", + "\n", + "\n", + "\u001b[0m\u001b[36;1m\u001b[1;3m[{'url': 'https://www.liveabout.com/cristiano-ronaldo-3557502', 'content': 'Learn about the life and career of Cristiano Ronaldo, the Portuguese footballer who plays for Real Madrid and is one of the best players in the world. Find out his achievements, awards, records, and controversies in this comprehensive biography.'}, {'url': 'https://www.biographyonline.net/sport/football/cristiano-ronaldo.html', 'content': \"Learn about the life and career of Cristiano Ronaldo, one of the world's best footballers. From his early days in Portugal to his success at Manchester United, Real Madrid and Juventus, and his international achievements with Portugal.\"}, {'url': 'https://eurofootballer.com/who-is-cristiano-ronaldo-complete-biography-and-life-history/', 'content': \"Learn about the life and achievements of Cristiano Ronaldo, one of the world's best footballers. From his early days in Portugal to his record-breaking stints in England, Spain and Italy, and his current contract with Al-Nassr in Saudi Arabia.\"}, {'url': 'https://en.wikipedia.org/wiki/Career_of_Cristiano_Ronaldo', 'content': 'Learn about the life and achievements of Cristiano Ronaldo, one of the greatest footballers of all time. From his early days at Sporting CP to his record-breaking moves and awards, this article covers his career in detail.'}, {'url': 'https://www.britannica.com/biography/Cristiano-Ronaldo', 'content': 'He scored a total of 66 goals in 56 appearances with Madrid and the Portuguese national team in 2013 to earn his second world player of the year award (the FIFA World Player of the Year was renamed the FIFA Ballon d’Or in 2010). Endorsements and legal issues\\nRonaldo was one of the most well-known sports stars off the field, and numerous studies of athletes’ popularity showed that he was the most-beloved athlete in the world during his playing peak. In 2016 he helped Portugal win the European Championship, the country’s first major international tournament title, although he only played sparingly in the final because of a knee injury that he had sustained early in the match. Ronaldo came into the 2014 World Cup hot off of his second world player of the year win, but his play at the tournament was spotty, and the entire Portugal team struggled during a group-stage elimination. His extreme popularity made Ronaldo one of the highest-paid endorsers in sports history, and in November 2016 he became the third person (after basketball superstars Michael Jordan and LeBron James) to earn a “lifetime” contract from the sportswear company Nike.'}]\u001b[0m\u001b[32;1m\u001b[1;3m\n", + "Invoking: `tavily_search_results_json` with `{'query': 'Cristiano Ronaldo career achievements'}`\n", + "\n", + "\n", + "\u001b[0m\u001b[36;1m\u001b[1;3m[{'url': 'https://en.wikipedia.org/wiki/List_of_career_achievements_by_Cristiano_Ronaldo', 'content': \"Inclusions in theoretical teams\\nSelections for international sportsperson of the year\\nInternational man of the match awards\\nOrders\\nMiscellaneous\\nRecords\\nGoalscoring statistics\\nClub\\n[494][495][496]\\nCountry\\nSource: Rec.Sport. Widely regarded as one of the greatest players of all time, Ronaldo holds the record for most goals and assists in the UEFA Champions League (140 and 42 respectively), and the record for most goals in the UEFA European Championship (14), its qualification stage (40), and the FIFA Club World Cup (7), as well as most goals scored in a UEFA Champions League season (17 in\\n2013-14), most international goals (128), and most appearances in a national team (204). Ronaldo with then President of the Community of Madrid, Cristina Cifuentes, during Champions League title celebrations in Madrid in 2016\\nRonaldo (second from the right) raising his hand in the air as Real Madrid celebrate winning the UEFA Champions League, on 26 May 2018\\nSee also\\nFootnotes\\nReferences\\nWorks cited\\nBiographies Contents\\nList of career achievements by Cristiano Ronaldo\\nPortuguese professional footballer\\nEponyms and public art\\nFilms\\nOver the course of his career, Portuguese footballer Cristiano Ronaldo has received five Ballon d'Or/FIFA Ballon d'Or awards,[a] the most for a European player. All in all he had won over 300 trophies and medals by January 2021, with some of them dating back to his childhood.[1]\\nCollective awards\\nFriendly competitions\\nIndividual honours\\nRonaldo has obtained many other minor achievements, awards and recognitions, by the major sport magazines and newspapers, which are not reported.\\n\"}, {'url': 'https://www.sportingnews.com/us/soccer/news/cristiano-ronaldo-career-trophies-how-many-has-cr7-won/sgkll9jwwmnkarutohgptsvj', 'content': \"In 2021, Ronaldo received The Best FIFA Special Award for Outstanding Career Achievement as he broke the record for most international goals scored by a male footballer. Ronaldo's time at ...\"}, {'url': 'https://www.transfermarkt.com/cristiano-ronaldo/erfolge/spieler/8198', 'content': 'This statistic shows the achievements of Al-Nasr Riad player Cristiano Ronaldo. ... #7 Cristiano Ronaldo. 3 5 1 5 4. Al-Nassr Saudi ... Career . Contact . About Us . TM-Team FAQ . Social media . Transfermarkt Company Projects ...'}, {'url': 'https://www.britannica.com/biography/Cristiano-Ronaldo', 'content': 'He scored a total of 66 goals in 56 appearances with Madrid and the Portuguese national team in 2013 to earn his second world player of the year award (the FIFA World Player of the Year was renamed the FIFA Ballon d’Or in 2010). Endorsements and legal issues\\nRonaldo was one of the most well-known sports stars off the field, and numerous studies of athletes’ popularity showed that he was the most-beloved athlete in the world during his playing peak. In 2016 he helped Portugal win the European Championship, the country’s first major international tournament title, although he only played sparingly in the final because of a knee injury that he had sustained early in the match. Ronaldo came into the 2014 World Cup hot off of his second world player of the year win, but his play at the tournament was spotty, and the entire Portugal team struggled during a group-stage elimination. His extreme popularity made Ronaldo one of the highest-paid endorsers in sports history, and in November 2016 he became the third person (after basketball superstars Michael Jordan and LeBron James) to earn a “lifetime” contract from the sportswear company Nike.'}, {'url': 'https://www.biographyonline.net/sport/football/cristiano-ronaldo.html', 'content': \"Cristiano Ronaldo is a Portuguese professional footballer who has played for Manchester United, Real Madrid, Juventus and Portugal. Along with Lionel Messi, he is regularly considered to be one of the top two players in the world. He became the world's most expensive player when Real Madrid signed him for 94 million Euros in 2009 from ...\"}]\u001b[0m\u001b[32;1m\u001b[1;3m\n", + "Invoking: `tavily_search_results_json` with `{'query': 'Cristiano Ronaldo personal life'}`\n", + "\n", + "\n", + "\u001b[0m\u001b[36;1m\u001b[1;3m[{'url': 'https://talksport.com/football/1752006/cristiano-ronaldo-georgina-rodriguez-family-children/', 'content': \"Ronaldo has been with Rodriguez since 2016 Credit: @cristiano Instagram Of course, there are also plenty of eyes on the superstar's personal life and his partner Georgina Rodriguez has become a ...\"}, {'url': 'https://www.sportskeeda.com/football/ronaldo-family', 'content': \"Learn about the Portuguese football legend's family, including his girlfriend Georgina Rodriguez, his twins Eva Maria and Mateo, and his son Cristiano Jr. Find out how he lost his father at a young age and who is the mother of his twins.\"}, {'url': 'https://people.com/parents/everything-to-know-about-cristiano-ronaldo-family-kids/', 'content': '\"\\nNow nearly 12 years old, Cristiano Jr. is taking after his father in more than just looks — he plays soccer just like Dad!\\nEva Maria and Mateo Ronaldo, 6\\nIn June 2017, Ronaldo welcomed twins Eva and Mateo via surrogate, sharing the happy news of their arrival in a Facebook post captioned, \"So happy to be able to hold the two new loves of my life 🙏❤. Everything to Know About Cristiano Ronaldo\\'s Family\\nCristiano Ronaldo shares his children with girlfriend Georgina Rodriguez\\nCristiano Ronaldo and Georgina Rodriguez are finding \"hope and happiness\" after the birth of their daughter and amid mourning the loss of their newborn son.\\n This year, I had the best and the worst moment of my life in an instant,\" she said, adding that Ronaldo \"encouraged\" her to start enjoying life again after the heavy loss. \"\\nMonths before the twins\\' arrival, Ronaldo began dating model Georgina Rodriguez, with the pair making their first public appearance at the Best FIFA Football Awards in January 2017.\\n \"After one week I say, \\'Let\\'s be upfront, and let\\'s be honest with the kids, let\\'s say that, Ángel, which is his name, he go to the Heaven.\\''}, {'url': 'https://www.thisisamericansoccer.com/cristiano-ronaldos-family/', 'content': 'Learn about the Ronaldo family tree, from his humble origins in Madeira to his global fame as a football legend. Discover how his parents, siblings, partner, and children shaped his character and supported his dreams.'}, {'url': 'https://en.wikipedia.org/wiki/Cristiano_Ronaldo', 'content': 'After scoring in the following matches against Chelsea and Brentford, he was named the Premier League Player of the Month for April.[313]\\nHe finished the season with 24 goals in all competitions, 18 of those goals being in the Premier League, making him the third-highest goalscorer in the league behind Golden Boot winners Mohamed Salah and Son Heung-min, being named in the Premier League Team of the Year and the winner of United\\'s Sir Matt Busby Player of the Year award, given to the club\\'s best player from the previous season;[314][315] however, with United finishing in a disappointing sixth place and qualifying for the UEFA Europa League, Ronaldo went trophyless for the first time since 2010.[316]\\nAfter growing dissatisfaction with the direction of United on and off the field, Ronaldo missed the club\\'s pre-season tour of Thailand and Australia due to family reasons, amid reports of his desire to leave to join a club competing in the Champions League, despite incoming manager Erik ten Hag insisting that he was not for sale and was part of the club\\'s plans.[317] Ronaldo was awarded the Player of the Month award for February after scoring eight goals and assisting twice.[346] Ronaldo spent another season without winning a league title, as Al Nassr finished second in the league in the 2022–23 season.[347]\\nRonaldo\\'s signing for Al-Nassr resulted in increased popularity both domestically and internationally of the Saudi Pro League, with various European players such as Karim Benzema, Sadio Mané, N\\'Golo Kanté, Rúben Neves, Riyad Mahrez, Roberto Firmino and Neymar moving to the Saudi Pro League during the summer transfer window, crediting Ronaldo as one of the main factors for moving to the league.[348]\\nHe scored his first goal of the 2023–24 season in a 4–1 win over Union Monastirienne in the Arab Club Champions Cup on 31 July.[349] This unique role has been described by pundits as that of a \"false\", \"attacking\", or \"goalscoring winger\", as Ronaldo effectively almost functioned as a striker at times with his central runs into the penalty area, despite actually playing on the left flank.[488][493] From 2013 onwards, under manager Carlo Ancelotti, he effectively adapted his style to the physical effects of ageing with increasingly reduced off-the-ball movement and general involvement, completing fewer dribbles and passes per game, and instead focusing on short-distance creating and goalscoring.[487][494][495] Since 2017, Ronaldo adapted his style of play yet again to become more of a free-roaming centre forward under manager Zinedine Zidane, a role in which he continued to excel and maintain a prolific goalscoring record; in this position, he earned praise in the media for his intelligent movement both on and off the ball, positional sense, link-up play and finishing, as well as his ability to lose or anticipate his markers, find space in the box and score from few touches or opportunities.[496][497][498]\\n Ronaldo then missed United\\'s following matches before the World Cup break, with Ten Hag saying that Ronaldo was ill.[329]\\nOn 14 November, an interview with Piers Morgan was published, where Ronaldo said that he felt \"betrayed\" by Ten Hag and senior executives who wanted Ronaldo to leave the club, and accused the club of doubting him regarding the illness of his daughter that led him to miss pre-season, adding that he did not respect ten Hag \"because he doesn\\'t show respect for me\", leading him to be disappointed with the communication of the club.[330] Ronaldo claimed that ten Hag deliberately provoked him by first leaving him on the bench against City, and then wanting to bring him on in the final moments against Tottenham, but added that he regretted his decision to leave early.[330] Ronaldo ended his first season in English football by scoring the opening goal in United\\'s 3–0 win over Millwall in the 2004 FA Cup Final, earning his first trophy.[52] BBC pundit Alan Hansen described him as the star of the final.[53] The British press had been critical of Ronaldo during the season for his \"elaborate\" step-overs in trying to beat opponents,[54] but teammate Gary Neville said he was \"not a show pony, but the real thing\", and predicted he would become a world-class player.[55]\\n\"He has got the tricks and party pieces, we know that, but they\\'re not much good unless there is something at the end of it all.'}]\u001b[0m\u001b[32;1m\u001b[1;3m### Cristiano Ronaldo: A Football Legend\n", + "\n", + "#### Early Life and Career Beginnings\n", + "\n", + "Cristiano Ronaldo dos Santos Aveiro, commonly known as Cristiano Ronaldo or CR7, was born on February 5, 1985, in Funchal, Madeira, Portugal. From a young age, Ronaldo displayed an extraordinary talent for football, which led him to join the youth academy of Sporting CP in Lisbon. His exceptional skills quickly caught the attention of scouts from top European clubs.\n", + "\n", + "#### Rise to Stardom\n", + "\n", + "Ronaldo's professional career began at Sporting CP, where he made his debut in the Primeira Liga at just 17 years old. His performance against Manchester United in a friendly match in 2003 was so impressive that it led to his transfer to the English club. At Manchester United, Ronaldo's career skyrocketed. Under the guidance of Sir Alex Ferguson, he developed into one of the best players in the world, winning three Premier League titles, a UEFA Champions League title, and his first Ballon d'Or in 2008.\n", + "\n", + "#### Real Madrid Era\n", + "\n", + "In 2009, Ronaldo made a record-breaking transfer to Real Madrid for €94 million. His time at Real Madrid was marked by unprecedented success. He became the club's all-time top scorer, won four Champions League titles, and added four more Ballon d'Or awards to his collection. Ronaldo's rivalry with Lionel Messi during this period became one of the most talked-about aspects of modern football.\n", + "\n", + "#### Juventus and Beyond\n", + "\n", + "In 2018, Ronaldo transferred to Juventus for €100 million. He continued to break records and win titles, including two Serie A championships. In 2021, he returned to Manchester United, where he continued to perform at a high level. As of 2023, Ronaldo plays for Al-Nassr in Saudi Arabia, further expanding his global influence.\n", + "\n", + "#### International Career\n", + "\n", + "Ronaldo's international career with Portugal has been equally illustrious. He has scored the most goals in international football history and has made the most appearances for the Portuguese national team. His crowning achievement came in 2016 when he led Portugal to victory in the UEFA European Championship, the country's first major international tournament win.\n", + "\n", + "#### Personal Life\n", + "\n", + "Off the field, Ronaldo is known for his philanthropic efforts and business ventures. He has a long-term relationship with Georgina Rodriguez, and together they have a large family, including his son Cristiano Jr. and twins Eva Maria and Mateo. Ronaldo's personal life has been a subject of media attention, but he has managed to maintain a positive public image.\n", + "\n", + "#### Achievements and Records\n", + "\n", + "Ronaldo's list of achievements is extensive. He holds the record for the most goals and assists in the UEFA Champions League, the most goals in the UEFA European Championship, and the most international goals. He has won over 300 trophies and medals, including five Ballon d'Or awards, making him one of the most decorated players in football history.\n", + "\n", + "#### Legacy\n", + "\n", + "Cristiano Ronaldo's impact on football is immeasurable. He has set new standards for excellence and professionalism, inspiring countless young athletes around the world. His dedication, work ethic, and relentless pursuit of greatness have cemented his place as one of the greatest footballers of all time.\n", + "\n", + "#### Conclusion\n", + "\n", + "Cristiano Ronaldo's journey from a young boy in Madeira to a global football icon is a testament to his talent, hard work, and determination. His legacy will continue to influence the world of football for generations to come. Whether on the field or off it, Ronaldo's name will always be synonymous with greatness.\u001b[0m\n", + "\n", + "\u001b[1m> Finished chain.\u001b[0m\n", + "\n", + "\n", + "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n", + "\u001b[32;1m\u001b[1;3m\n", + "Invoking: `tavily_search_results_json` with `{'query': 'Cristiano Ronaldo latest news 2023'}`\n", + "\n", + "\n", + "\u001b[0m\u001b[36;1m\u001b[1;3m[{'url': 'https://abcnews.go.com/Sports/cristiano-ronaldo-end-2023-worlds-top-goalscorer/story?id=106012559', 'content': \"Cristiano Ronaldo to end 2023 as world's top goalscorer - ABC News ABC News Cristiano Ronaldo is set to end the year as the world's top goalscorer after scoring his 54th goal of 2023 in Al Nassr's 4-1 victory at Al Taawoun in the Saudi Pro League on Saturday. Ronaldo's latest goal on Saturday came on the one-year anniversary of him signing for Saudi club Al Nassr, following his controversial exit from Manchester United. Al Nassr were leading 3-1 through goals from Marcelo Brozovic, Aymeric Laporte and Otavio\\xa0on Saturday when Ronaldo headed in from six yards out in the second minute of stoppage time. How to watch the Harris-Trump ABC News debate --------------------------------------------- * Sep 9, 9:01 AM ABC News Live ABC News Network © 2024 ABC News\"}, {'url': 'https://www.newsnow.co.uk/h/Sport/Football/International+Stars/Cristiano+Ronaldo', 'content': 'Latest headlines on Cristiano Ronaldo, one of the greatest ever footballers, goal scorers, and most successful players ever to kick a ball. ... About our Cristiano Ronaldo News Born in 1985, Cristiano Ronaldo is one of the greatest footballers of all-time. ... he missed the match against Al-Tai on 5 January 2023. Ronaldo played his first game ...'}, {'url': 'https://www.cnn.com/2023/12/12/sport/cristiano-ronaldo-50-goals-2023-spt-intl/index.html', 'content': 'CNN values your feedback\\nCristiano Ronaldo scores 50th goal of 2023 as potential Lionel Messi clash is announced\\nCristiano Ronaldo scored his 50th goal of the calendar year on Monday as Al Nassr advanced to the semifinals of the Saudi King Cup with a 5-2 victory against rival Al Shabab.\\n Lionel Messi says he is focused on playing at next year’s Copa América but doesn’t rule out appearing at 2026 World Cup\\nLast week, the 38-year-old forward played the 1,200th game of his professional career, scoring a league-leading 16th goal in the Saudi Pro League this season.\\n Cristiano Ronaldo says his long-standing ‘rivalry’ with Lionel Messi is over\\n“Great victory and I’m thrilled to announce my 50th goal in 2023, all thanks to the unwavering support of my teammates, fans, and my family!” Ronaldo netted his team’s fourth goal with a powerful strike in the 74th minute, continuing his impressive scoring rate since playing his first game in Saudi Arabia in January.\\n “We are excited to connect with new supporters in Saudi Arabia, and also hope people all over the world will be tuning in to see a pair of dream matches like these.”\\n'}, {'url': 'https://www.bbc.co.uk/sport/football/67688432', 'content': 'Cristiano Ronaldo scored his 50th goal in 2023 as Al-Nassr beat rivals Al-Shabab 5-2 to reach the semi-finals of the Saudi King Cup. The former Real Madrid and Manchester United forward got his ...'}, {'url': 'https://www.cnn.com/2023/05/28/football/lionel-messi-record-psg-ligue-1-title-spt-intl/index.html', 'content': 'There was another landmark in the long rivalry between Lionel Messi and Cristiano Ronaldo on Saturday. ... Published 9:01 AM EDT, Sun May 28, 2023 ... But this latest triumph masks an increasingly ...'}]\u001b[0m\u001b[32;1m\u001b[1;3m### Cristiano Ronaldo: A Football Legend\n", + "\n", + "#### Early Life and Career Beginnings\n", + "\n", + "Cristiano Ronaldo dos Santos Aveiro, commonly known as Cristiano Ronaldo or CR7, was born on February 5, 1985, in Funchal, Madeira, Portugal. From a young age, Ronaldo displayed an extraordinary talent for football, which led him to join the youth academy of Sporting CP in Lisbon. His exceptional skills quickly caught the attention of scouts from top European clubs.\n", + "\n", + "#### Rise to Stardom\n", + "\n", + "Ronaldo's professional career began at Sporting CP, where he made his debut in the Primeira Liga at just 17 years old. His performance against Manchester United in a friendly match in 2003 was so impressive that it led to his transfer to the English club. At Manchester United, Ronaldo's career skyrocketed. Under the guidance of Sir Alex Ferguson, he developed into one of the best players in the world, winning three Premier League titles, a UEFA Champions League title, and his first Ballon d'Or in 2008.\n", + "\n", + "#### Real Madrid Era\n", + "\n", + "In 2009, Ronaldo made a record-breaking transfer to Real Madrid for €94 million. His time at Real Madrid was marked by unprecedented success. He became the club's all-time top scorer, won four Champions League titles, and added four more Ballon d'Or awards to his collection. Ronaldo's rivalry with Lionel Messi during this period became one of the most talked-about aspects of modern football.\n", + "\n", + "#### Juventus and Beyond\n", + "\n", + "In 2018, Ronaldo transferred to Juventus for €100 million. He continued to break records and win titles, including two Serie A championships. In 2021, he returned to Manchester United, where he continued to perform at a high level. As of 2023, Ronaldo plays for Al-Nassr in Saudi Arabia, further expanding his global influence.\n", + "\n", + "#### International Career\n", + "\n", + "Ronaldo's international career with Portugal has been equally illustrious. He has scored the most goals in international football history and has made the most appearances for the Portuguese national team. His crowning achievement came in 2016 when he led Portugal to victory in the UEFA European Championship, the country's first major international tournament win.\n", + "\n", + "#### Personal Life\n", + "\n", + "Off the field, Ronaldo is known for his philanthropic efforts and business ventures. He has a long-term relationship with Georgina Rodriguez, and together they have a large family, including his son Cristiano Jr. and twins Eva Maria and Mateo. Ronaldo's personal life has been a subject of media attention, but he has managed to maintain a positive public image.\n", + "\n", + "#### Achievements and Records\n", + "\n", + "Ronaldo's list of achievements is extensive. He holds the record for the most goals and assists in the UEFA Champions League, the most goals in the UEFA European Championship, and the most international goals. He has won over 300 trophies and medals, including five Ballon d'Or awards, making him one of the most decorated players in football history.\n", + "\n", + "#### Latest Milestones in 2023\n", + "\n", + "As of 2023, Cristiano Ronaldo continues to break records and achieve new milestones. He is set to end the year as the world's top goalscorer, having scored his 54th goal of 2023 in Al Nassr's 4-1 victory at Al Taawoun in the Saudi Pro League. This goal came on the one-year anniversary of his signing with Al Nassr, following his controversial exit from Manchester United. Ronaldo also scored his 50th goal of the calendar year in a match against Al Shabab, leading Al Nassr to the semifinals of the Saudi King Cup. This year, he also played his 1,200th professional game, continuing to demonstrate his remarkable longevity and consistency.\n", + "\n", + "#### Legacy\n", + "\n", + "Cristiano Ronaldo's impact on football is immeasurable. He has set new standards for excellence and professionalism, inspiring countless young athletes around the world. His dedication, work ethic, and relentless pursuit of greatness have cemented his place as one of the greatest footballers of all time.\n", + "\n", + "#### Conclusion\n", + "\n", + "Cristiano Ronaldo's journey from a young boy in Madeira to a global football icon is a testament to his talent, hard work, and determination. His legacy will continue to influence the world of football for generations to come. Whether on the field or off it, Ronaldo's name will always be synonymous with greatness.\u001b[0m\n", + "\n", + "\u001b[1m> Finished chain.\u001b[0m\n", + "\n", + "\n", + "\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n", + "\u001b[32;1m\u001b[1;3m### Cristiano Ronaldo: A Football Legend\n", + "\n", + "#### Early Life and Career Beginnings\n", + "\n", + "Cristiano Ronaldo dos Santos Aveiro, commonly known as Cristiano Ronaldo or CR7, was born on February 5, 1985, in Funchal, Madeira, Portugal. From a young age, Ronaldo displayed an extraordinary talent for football, which led him to join the youth academy of Sporting CP in Lisbon. His exceptional skills quickly caught the attention of scouts from top European clubs.\n", + "\n", + "#### Rise to Stardom\n", + "\n", + "Ronaldo's professional career began at Sporting CP, where he made his debut in the Primeira Liga at just 17 years old. His performance against Manchester United in a friendly match in 2003 was so impressive that it led to his transfer to the English club. At Manchester United, Ronaldo's career skyrocketed. Under the guidance of Sir Alex Ferguson, he developed into one of the best players in the world, winning three Premier League titles, a UEFA Champions League title, and his first Ballon d'Or in 2008.\n", + "\n", + "#### Real Madrid Era\n", + "\n", + "In 2009, Ronaldo made a record-breaking transfer to Real Madrid for €94 million. His time at Real Madrid was marked by unprecedented success. He became the club's all-time top scorer, won four Champions League titles, and added four more Ballon d'Or awards to his collection. Ronaldo's rivalry with Lionel Messi during this period became one of the most talked-about aspects of modern football.\n", + "\n", + "#### Juventus and Beyond\n", + "\n", + "In 2018, Ronaldo transferred to Juventus for €100 million. He continued to break records and win titles, including two Serie A championships. In 2021, he returned to Manchester United, where he continued to perform at a high level. As of 2023, Ronaldo plays for Al-Nassr in Saudi Arabia, further expanding his global influence.\n", + "\n", + "#### International Career\n", + "\n", + "Ronaldo's international career with Portugal has been equally illustrious. He has scored the most goals in international football history and has made the most appearances for the Portuguese national team. His crowning achievement came in 2016 when he led Portugal to victory in the UEFA European Championship, the country's first major international tournament win.\n", + "\n", + "#### Personal Life\n", + "\n", + "Off the field, Ronaldo is known for his philanthropic efforts and business ventures. He has a long-term relationship with Georgina Rodriguez, and together they have a large family, including his son Cristiano Jr. and twins Eva Maria and Mateo. Ronaldo's personal life has been a subject of media attention, but he has managed to maintain a positive public image.\n", + "\n", + "#### Achievements and Records\n", + "\n", + "Ronaldo's list of achievements is extensive. He holds the record for the most goals and assists in the UEFA Champions League, the most goals in the UEFA European Championship, and the most international goals. He has won over 300 trophies and medals, including five Ballon d'Or awards, making him one of the most decorated players in football history.\n", + "\n", + "#### Latest Milestones in 2023\n", + "\n", + "As of 2023, Cristiano Ronaldo continues to break records and achieve new milestones. He is set to end the year as the world's top goalscorer, having scored his 54th goal of 2023 in Al Nassr's 4-1 victory at Al Taawoun in the Saudi Pro League. This goal came on the one-year anniversary of his signing with Al Nassr, following his controversial exit from Manchester United. Ronaldo also scored his 50th goal of the calendar year in a match against Al Shabab, leading Al Nassr to the semifinals of the Saudi King Cup. This year, he also played his 1,200th professional game, continuing to demonstrate his remarkable longevity and consistency.\n", + "\n", + "#### Legacy\n", + "\n", + "Cristiano Ronaldo's impact on football is immeasurable. He has set new standards for excellence and professionalism, inspiring countless young athletes around the world. His dedication, work ethic, and relentless pursuit of greatness have cemented his place as one of the greatest footballers of all time.\n", + "\n", + "#### Conclusion\n", + "\n", + "Cristiano Ronaldo's journey from a young boy in Madeira to a global football icon is a testament to his talent, hard work, and determination. His legacy will continue to influence the world of football for generations to come. Whether on the field or off it, Ronaldo's name will always be synonymous with greatness.\n", + "\n", + "---\n", + "\n", + "### Editorial Suggestions:\n", + "\n", + "1. **Introduction**: Consider adding a brief introductory paragraph that encapsulates Ronaldo's significance in football. This will set the stage for the detailed sections that follow.\n", + "\n", + "2. **Subheadings**: Ensure consistency in the formatting of subheadings. For example, \"Real Madrid Era\" could be \"The Real Madrid Era\" to match the style of \"Juventus and Beyond.\"\n", + "\n", + "3. **Transitions**: Add transitional sentences between sections to improve the flow of the article. For instance, a sentence at the end of the \"Rise to Stardom\" section could hint at his upcoming move to Real Madrid.\n", + "\n", + "4. **Details and Anecdotes**: Incorporate more personal anecdotes or lesser-known facts to make the article more engaging. For example, mention specific memorable matches or goals.\n", + "\n", + "5. **Quotes**: Including quotes from Ronaldo, his coaches, or teammates can add depth and authenticity to the article.\n", + "\n", + "6. **Visuals**: If this article is intended for a digital platform, consider adding images, infographics, or videos to complement the text and provide a richer experience for the reader.\n", + "\n", + "7. **Sources and References**: If possible, cite sources or references for key statistics and claims, especially in the \"Achievements and Records\" and \"Latest Milestones in 2023\" sections.\n", + "\n", + "8. **Conclusion**: The conclusion could be more impactful by summarizing his influence on both football and popular culture, and perhaps speculating on his future contributions to the sport.\n", + "\n", + "By incorporating these suggestions, the article can become more comprehensive, engaging, and polished.\u001b[0m\n", + "\n", + "\u001b[1m> Finished chain.\u001b[0m\n" + ] + }, + { + "data": { + "text/plain": [ + "{'messages': [HumanMessage(content='Write an article about CR7'),\n", + " HumanMessage(content=\"### Cristiano Ronaldo: A Football Legend\\n\\n#### Early Life and Career Beginnings\\n\\nCristiano Ronaldo dos Santos Aveiro, commonly known as Cristiano Ronaldo or CR7, was born on February 5, 1985, in Funchal, Madeira, Portugal. From a young age, Ronaldo displayed an extraordinary talent for football, which led him to join the youth academy of Sporting CP in Lisbon. His exceptional skills quickly caught the attention of scouts from top European clubs.\\n\\n#### Rise to Stardom\\n\\nRonaldo's professional career began at Sporting CP, where he made his debut in the Primeira Liga at just 17 years old. His performance against Manchester United in a friendly match in 2003 was so impressive that it led to his transfer to the English club. At Manchester United, Ronaldo's career skyrocketed. Under the guidance of Sir Alex Ferguson, he developed into one of the best players in the world, winning three Premier League titles, a UEFA Champions League title, and his first Ballon d'Or in 2008.\\n\\n#### Real Madrid Era\\n\\nIn 2009, Ronaldo made a record-breaking transfer to Real Madrid for €94 million. His time at Real Madrid was marked by unprecedented success. He became the club's all-time top scorer, won four Champions League titles, and added four more Ballon d'Or awards to his collection. Ronaldo's rivalry with Lionel Messi during this period became one of the most talked-about aspects of modern football.\\n\\n#### Juventus and Beyond\\n\\nIn 2018, Ronaldo transferred to Juventus for €100 million. He continued to break records and win titles, including two Serie A championships. In 2021, he returned to Manchester United, where he continued to perform at a high level. As of 2023, Ronaldo plays for Al-Nassr in Saudi Arabia, further expanding his global influence.\\n\\n#### International Career\\n\\nRonaldo's international career with Portugal has been equally illustrious. He has scored the most goals in international football history and has made the most appearances for the Portuguese national team. His crowning achievement came in 2016 when he led Portugal to victory in the UEFA European Championship, the country's first major international tournament win.\\n\\n#### Personal Life\\n\\nOff the field, Ronaldo is known for his philanthropic efforts and business ventures. He has a long-term relationship with Georgina Rodriguez, and together they have a large family, including his son Cristiano Jr. and twins Eva Maria and Mateo. Ronaldo's personal life has been a subject of media attention, but he has managed to maintain a positive public image.\\n\\n#### Achievements and Records\\n\\nRonaldo's list of achievements is extensive. He holds the record for the most goals and assists in the UEFA Champions League, the most goals in the UEFA European Championship, and the most international goals. He has won over 300 trophies and medals, including five Ballon d'Or awards, making him one of the most decorated players in football history.\\n\\n#### Latest Milestones in 2023\\n\\nAs of 2023, Cristiano Ronaldo continues to break records and achieve new milestones. He is set to end the year as the world's top goalscorer, having scored his 54th goal of 2023 in Al Nassr's 4-1 victory at Al Taawoun in the Saudi Pro League. This goal came on the one-year anniversary of his signing with Al Nassr, following his controversial exit from Manchester United. Ronaldo also scored his 50th goal of the calendar year in a match against Al Shabab, leading Al Nassr to the semifinals of the Saudi King Cup. This year, he also played his 1,200th professional game, continuing to demonstrate his remarkable longevity and consistency.\\n\\n#### Legacy\\n\\nCristiano Ronaldo's impact on football is immeasurable. He has set new standards for excellence and professionalism, inspiring countless young athletes around the world. His dedication, work ethic, and relentless pursuit of greatness have cemented his place as one of the greatest footballers of all time.\\n\\n#### Conclusion\\n\\nCristiano Ronaldo's journey from a young boy in Madeira to a global football icon is a testament to his talent, hard work, and determination. His legacy will continue to influence the world of football for generations to come. Whether on the field or off it, Ronaldo's name will always be synonymous with greatness.\", name='BlogWriter-BEsx9'),\n", + " HumanMessage(content='### Cristiano Ronaldo: A Football Legend\\n\\n#### Early Life and Career Beginnings\\n\\nCristiano Ronaldo dos Santos Aveiro, commonly known as Cristiano Ronaldo or CR7, was born on February 5, 1985, in Funchal, Madeira, Portugal. From a young age, Ronaldo displayed an extraordinary talent for football, which led him to join the youth academy of Sporting CP in Lisbon. His exceptional skills quickly caught the attention of scouts from top European clubs.\\n\\n#### Rise to Stardom\\n\\nRonaldo\\'s professional career began at Sporting CP, where he made his debut in the Primeira Liga at just 17 years old. His performance against Manchester United in a friendly match in 2003 was so impressive that it led to his transfer to the English club. At Manchester United, Ronaldo\\'s career skyrocketed. Under the guidance of Sir Alex Ferguson, he developed into one of the best players in the world, winning three Premier League titles, a UEFA Champions League title, and his first Ballon d\\'Or in 2008.\\n\\n#### Real Madrid Era\\n\\nIn 2009, Ronaldo made a record-breaking transfer to Real Madrid for €94 million. His time at Real Madrid was marked by unprecedented success. He became the club\\'s all-time top scorer, won four Champions League titles, and added four more Ballon d\\'Or awards to his collection. Ronaldo\\'s rivalry with Lionel Messi during this period became one of the most talked-about aspects of modern football.\\n\\n#### Juventus and Beyond\\n\\nIn 2018, Ronaldo transferred to Juventus for €100 million. He continued to break records and win titles, including two Serie A championships. In 2021, he returned to Manchester United, where he continued to perform at a high level. As of 2023, Ronaldo plays for Al-Nassr in Saudi Arabia, further expanding his global influence.\\n\\n#### International Career\\n\\nRonaldo\\'s international career with Portugal has been equally illustrious. He has scored the most goals in international football history and has made the most appearances for the Portuguese national team. His crowning achievement came in 2016 when he led Portugal to victory in the UEFA European Championship, the country\\'s first major international tournament win.\\n\\n#### Personal Life\\n\\nOff the field, Ronaldo is known for his philanthropic efforts and business ventures. He has a long-term relationship with Georgina Rodriguez, and together they have a large family, including his son Cristiano Jr. and twins Eva Maria and Mateo. Ronaldo\\'s personal life has been a subject of media attention, but he has managed to maintain a positive public image.\\n\\n#### Achievements and Records\\n\\nRonaldo\\'s list of achievements is extensive. He holds the record for the most goals and assists in the UEFA Champions League, the most goals in the UEFA European Championship, and the most international goals. He has won over 300 trophies and medals, including five Ballon d\\'Or awards, making him one of the most decorated players in football history.\\n\\n#### Latest Milestones in 2023\\n\\nAs of 2023, Cristiano Ronaldo continues to break records and achieve new milestones. He is set to end the year as the world\\'s top goalscorer, having scored his 54th goal of 2023 in Al Nassr\\'s 4-1 victory at Al Taawoun in the Saudi Pro League. This goal came on the one-year anniversary of his signing with Al Nassr, following his controversial exit from Manchester United. Ronaldo also scored his 50th goal of the calendar year in a match against Al Shabab, leading Al Nassr to the semifinals of the Saudi King Cup. This year, he also played his 1,200th professional game, continuing to demonstrate his remarkable longevity and consistency.\\n\\n#### Legacy\\n\\nCristiano Ronaldo\\'s impact on football is immeasurable. He has set new standards for excellence and professionalism, inspiring countless young athletes around the world. His dedication, work ethic, and relentless pursuit of greatness have cemented his place as one of the greatest footballers of all time.\\n\\n#### Conclusion\\n\\nCristiano Ronaldo\\'s journey from a young boy in Madeira to a global football icon is a testament to his talent, hard work, and determination. His legacy will continue to influence the world of football for generations to come. Whether on the field or off it, Ronaldo\\'s name will always be synonymous with greatness.\\n\\n---\\n\\n### Editorial Suggestions:\\n\\n1. **Introduction**: Consider adding a brief introductory paragraph that encapsulates Ronaldo\\'s significance in football. This will set the stage for the detailed sections that follow.\\n\\n2. **Subheadings**: Ensure consistency in the formatting of subheadings. For example, \"Real Madrid Era\" could be \"The Real Madrid Era\" to match the style of \"Juventus and Beyond.\"\\n\\n3. **Transitions**: Add transitional sentences between sections to improve the flow of the article. For instance, a sentence at the end of the \"Rise to Stardom\" section could hint at his upcoming move to Real Madrid.\\n\\n4. **Details and Anecdotes**: Incorporate more personal anecdotes or lesser-known facts to make the article more engaging. For example, mention specific memorable matches or goals.\\n\\n5. **Quotes**: Including quotes from Ronaldo, his coaches, or teammates can add depth and authenticity to the article.\\n\\n6. **Visuals**: If this article is intended for a digital platform, consider adding images, infographics, or videos to complement the text and provide a richer experience for the reader.\\n\\n7. **Sources and References**: If possible, cite sources or references for key statistics and claims, especially in the \"Achievements and Records\" and \"Latest Milestones in 2023\" sections.\\n\\n8. **Conclusion**: The conclusion could be more impactful by summarizing his influence on both football and popular culture, and perhaps speculating on his future contributions to the sport.\\n\\nBy incorporating these suggestions, the article can become more comprehensive, engaging, and polished.', name='Senior-Editor-hoWOe')]}" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "master_team.invoke(\"Write an article about CR7\")" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": ".venv", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.11.6" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/examples/linear_router_team.py b/examples/linear_router_team.py index ff82750e..27d0af67 100644 --- a/examples/linear_router_team.py +++ b/examples/linear_router_team.py @@ -45,10 +45,10 @@ async def _arun( - name: Reasercher job: Do a research on the internet and find articles of relevent to the topic asked by the user, always try to find the latest information on the same tools: - - name: TavilySearchResults + - name: TavilySearchResults - name: Blogger - job: From the documents provider by the researcher write a blog of 300 words with can be readily published, make in engaging and add reference links to original blogs - tools: + job: From the documents provider by the researcher write a blog of 300 words with can be readily published, make in engaging and add reference links to original blogs + tools: - name: TavilySearchResults """ diff --git a/examples/llm_router_example.ipynb b/examples/llm_router_example.ipynb new file mode 100644 index 00000000..b53c5509 --- /dev/null +++ b/examples/llm_router_example.ipynb @@ -0,0 +1,114 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 1, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "from flo_ai import Flo\n", + "from flo_ai import FloSession\n", + "from langchain_openai import ChatOpenAI, OpenAIEmbeddings\n", + "\n", + "from dotenv import load_dotenv\n", + "load_dotenv()" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [], + "source": [ + "from langchain_community.tools.tavily_search.tool import TavilySearchResults\n", + "\n", + "llm = ChatOpenAI(temperature=0, model_name='gpt-4o-mini')\n", + "session = FloSession(llm)\n" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "agent_yaml = \"\"\"\n", + "apiVersion: flo/alpha-v1\n", + "kind: FloRoutedTeam\n", + "name: adding-team\n", + "team:\n", + " name: AddingTeam1\n", + " router:\n", + " name: router\n", + " kind: llm\n", + " job: Sent to the next member which was not called\n", + " agents:\n", + " - name: Agent1\n", + " kind: llm\n", + " role: Expert mathematician\n", + " job: You are an expert in mathematics. Add one to the number given to you. And pass the result to the next agent\n", + " - name: Agent2\n", + " kind: llm\n", + " role: Expert mathematician\n", + " job: You are an expert in mathematics. Add one to the number given to you. And pass the result to the next agent\n", + " - name: Agent3\n", + " kind: llm\n", + " role: Expert mathematician\n", + " job: You are an expert in mathematics. Add one to the number given to you. And pass the result to the next agent\n", + "\"\"\"" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "{'messages': [HumanMessage(content='Start with number 7'), HumanMessage(content='The result is 8.', name='Agent1-rzQ1B'), HumanMessage(content='The result is 9.', name='Agent2-izmIo'), HumanMessage(content='The result is 10.', name='Agent3-WgTbh')], 'next': 'FINISH'}\n" + ] + } + ], + "source": [ + "flo = Flo.build(session, agent_yaml)\n", + "flo.draw_to_file(\"aasd.png\")\n", + "\n", + "print(flo.invoke(\"Start with number 7\"))" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": ".venv", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.11.6" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/examples/planned_blogging_team.py b/examples/planned_blogging_team.py index 6f14419b..e7011c51 100644 --- a/examples/planned_blogging_team.py +++ b/examples/planned_blogging_team.py @@ -1,6 +1,5 @@ from flo_ai.core import Flo from langchain_openai import ChatOpenAI -from xamples.enviroment import load_env from flo_ai import FloSession from langchain_community.tools.tavily_search.tool import TavilySearchResults diff --git a/flo_ai/__init__.py b/flo_ai/__init__.py index 3532140d..08594a25 100644 --- a/flo_ai/__init__.py +++ b/flo_ai/__init__.py @@ -1,6 +1,8 @@ from flo_ai.core import Flo from flo_ai.models.flo_agent import FloAgent -from flo_ai.router.flo_supervisor import FloSupervisorBuilder -from flo_ai.models.flo_team import FloTeamBuilder +from flo_ai.router.flo_supervisor import FloSupervisor +from flo_ai.models.flo_team import FloTeam +from flo_ai.router.flo_linear import FloLinear from flo_ai.state.flo_session import FloSession from flo_ai.retrievers.flo_retriever import FloRagBuilder + diff --git a/flo_ai/builders/yaml_builder.py b/flo_ai/builders/yaml_builder.py index e8ae0345..2772de37 100644 --- a/flo_ai/builders/yaml_builder.py +++ b/flo_ai/builders/yaml_builder.py @@ -1,4 +1,4 @@ -from flo_ai.models.flo_team import FloTeamBuilder +from flo_ai.models.flo_team import FloTeam from flo_ai.models.flo_agent import FloAgent from flo_ai.yaml.flo_team_builder import (FloRoutedTeamConfig, TeamConfig, AgentConfig, FloAgentConfig) @@ -31,21 +31,19 @@ def parse_and_build_subteams( for agent in team_config.agents: flo_agent: FloAgent = AgentFactory.create(session, agent, tool_map) agents.append(flo_agent) - flo_team = FloTeamBuilder( + flo_team = FloTeam.Builder( session=session, name=team_config.name, members=agents ).build() router = FloRouterFactory.create(session, team_config, flo_team) flo_routed_team = router.build_routed_team() - if team_config.planner is not None: - return FloPlannerBuilder(session, team_config.planner.name, flo_routed_team).build() else: flo_teams = [] for subteam in team_config.subteams: flo_subteam = parse_and_build_subteams(session, subteam, tool_map) flo_teams.append(flo_subteam) - flo_team = FloTeamBuilder( + flo_team = FloTeam.Builder( session=session, name=team_config.name, members=flo_teams diff --git a/flo_ai/models/flo_node.py b/flo_ai/models/flo_node.py index 692059ae..8c9f752e 100644 --- a/flo_ai/models/flo_node.py +++ b/flo_ai/models/flo_node.py @@ -18,7 +18,9 @@ class Builder(): @staticmethod def teamflo_agent_node(state: TeamFloAgentState, agent: AgentExecutor, name: str): result = agent.invoke(state) - return { "messages": [HumanMessage(content=result["output"], name=name)] } + # TODO see how to fix this + output = result if isinstance(result, str) else result["output"] + return { "messages": [HumanMessage(content=output, name=name)] } @staticmethod def get_last_message(state: TeamFloAgentState) -> str: @@ -29,7 +31,7 @@ def join_graph(response: dict): return { "messages": [ response["messages"][-1] ] } @staticmethod - def teamflo_team_node( message: str, members: list[str]): + def teamflo_team_node(message: str, members: list[str]): results = { "messages": [HumanMessage(content=message)], "team_members": ", ".join(members), @@ -41,7 +43,7 @@ def build_from_agent(self, flo_agent: FloAgent): return FloNode(agent_func, flo_agent.name) def build_from_team(self, flo_team: FloRoutedTeam): + team_chain = (functools.partial(FloNode.Builder.teamflo_team_node, members=flo_team.runnable.nodes) | flo_team.runnable) return FloNode(( - FloNode.Builder.get_last_message | functools.partial(FloNode.Builder.teamflo_team_node, members=flo_team.graph.nodes) - | flo_team.graph | FloNode.Builder.join_graph + FloNode.Builder.get_last_message | team_chain | FloNode.Builder.join_graph ), flo_team.name) \ No newline at end of file diff --git a/flo_ai/models/flo_team.py b/flo_ai/models/flo_team.py index 4b8aaf16..db21a709 100644 --- a/flo_ai/models/flo_team.py +++ b/flo_ai/models/flo_team.py @@ -12,19 +12,19 @@ def __init__(self, self.session = session self.members = members -class FloTeamBuilder: - def __init__(self, - session: FloSession, - name: str, - members: list[FloMember]) -> None: - self.name = randomize_name(name) - self.session = session - self.members = members - self.member_names= list(map(lambda x: x.name, self.members)) - - def build(self): - return FloTeam( - name = self.name, - session=self.session, - members=self.members - ) \ No newline at end of file + class Builder: + def __init__(self, + session: FloSession, + name: str, + members: list[FloMember]) -> None: + self.name = randomize_name(name) + self.session = session + self.members = members + self.member_names= list(map(lambda x: x.name, self.members)) + + def build(self): + return FloTeam( + name = self.name, + session=self.session, + members=self.members + ) \ No newline at end of file diff --git a/flo_ai/router/flo_linear.py b/flo_ai/router/flo_linear.py index 86ed5e16..1a165e0d 100644 --- a/flo_ai/router/flo_linear.py +++ b/flo_ai/router/flo_linear.py @@ -67,4 +67,14 @@ def build_team_graph(self): super_graph = super_graph.compile() return FloRoutedTeam(self.flo_team.name, super_graph) + + class Builder(): + + def __init__(self, session: FloSession, flo_team: FloTeam, config: RouterConfig) -> None: + self.config = config + self.session = session + self.team = flo_team + + def build(self): + return FloLinear(self.session, self.team, self.config) diff --git a/flo_ai/router/flo_llm_router.py b/flo_ai/router/flo_llm_router.py new file mode 100644 index 00000000..388dd6dc --- /dev/null +++ b/flo_ai/router/flo_llm_router.py @@ -0,0 +1,134 @@ +from langchain_core.output_parsers.openai_functions import JsonOutputFunctionsParser +from langchain_core.language_models import BaseLanguageModel +from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder +from typing import Union +from langchain_core.runnables import Runnable +from flo_ai.state.flo_session import FloSession +from flo_ai.constants.prompt_constants import FLO_FINISH +from flo_ai.helpers.utils import randomize_name +from flo_ai.router.flo_router import FloRouter +from flo_ai.models.flo_team import FloTeam +from flo_ai.models.flo_routed_team import FloRoutedTeam +from langgraph.graph import StateGraph +from flo_ai.state.flo_state import TeamFloAgentState + +class StateUpdateComponent: + def __init__(self, name: str, session: FloSession) -> None: + self.name = name + self.inner_session = session + + def __call__(self, input): + self.inner_session.append(self.name) + return input + +class FloLLMRouter(FloRouter): + + def __init__(self, + session: FloSession, + executor: Runnable, + flo_team: FloTeam, + name: str) -> None: + super().__init__( + session = session, + name = name, + flo_team = flo_team, + executor = executor + ) + + def build_agent_graph(self): + flo_agent_nodes = [self.build_node(flo_agent) for flo_agent in self.members] + workflow = StateGraph(TeamFloAgentState) + for flo_agent_node in flo_agent_nodes: + workflow.add_node(flo_agent_node.name, flo_agent_node.func) + workflow.add_node(self.router_name, self.executor) + for member in self.member_names: + workflow.add_edge(member, self.router_name) + workflow.add_conditional_edges(self.router_name, self.router_fn) + workflow.set_entry_point(self.router_name) + workflow_graph = workflow.compile() + return FloRoutedTeam(self.flo_team.name, workflow_graph) + + def build_team_graph(self): + flo_team_entry_chains = [self.build_node_for_teams(flo_agent) for flo_agent in self.members] + # Define the graph. + super_graph = StateGraph(TeamFloAgentState) + # First add the nodes, which will do the work + for flo_team_chain in flo_team_entry_chains: + super_graph.add_node(flo_team_chain.name, flo_team_chain.func) + super_graph.add_node(self.router_name, self.executor) + + for member in self.member_names: + super_graph.add_edge(member, self.router_name) + + super_graph.add_conditional_edges(self.router_name, self.router_fn) + + super_graph.set_entry_point(self.router_name) + super_graph = super_graph.compile() + return FloRoutedTeam(self.flo_team.name, super_graph) + + class Builder: + def __init__(self, + session: FloSession, + name: str, + flo_team: FloTeam, + router_prompt: ChatPromptTemplate = None, + llm: Union[BaseLanguageModel, None] = None) -> None: + + self.name = randomize_name(name) + self.session = session + self.llm = llm if llm is not None else session.llm + self.flo_team = flo_team + self.agents = flo_team.members + self.members = [agent.name for agent in flo_team.members] + self.options = self.members + [FLO_FINISH] + member_type = "workers" if flo_team.members[0].type == "agent" else "team members" + + router_base_system_message = ( + "You are a supervisor tasked with managing a conversation between the" + " following {member_type}: {members}. Given the following rules," + " respond with the worker to act next " + ) + + self.llm_router_prompt = ChatPromptTemplate.from_messages( + [ + ("system", router_base_system_message), + MessagesPlaceholder(variable_name="messages"), + ("system", "Rules: {router_prompt}"), + ( + "system", + "Given the conversation above, who should act next?" + " Or should we FINISH if the task is already answered ? Select one of: {options}", + ), + ] + ).partial(options=str(self.options), members=", ".join(self.members), member_type=member_type, router_prompt=router_prompt) + + def build(self): + function_def = { + "name": "route", + "description": "Select the next role.", + "parameters": { + "title": "routeSchema", + "type": "object", + "properties": { + "next": { + "title": "Next", + "anyOf": [ + {"enum": self.options}, + ], + } + }, + "required": ["next"], + } + } + + chain = ( + self.llm_router_prompt + | self.llm.bind_functions(functions=[function_def], function_call="route") + | JsonOutputFunctionsParser() + | StateUpdateComponent(self.name, self.session) + ) + + return FloLLMRouter(executor = chain, + flo_team=self.flo_team, + name=self.name, + session=self.session) \ No newline at end of file diff --git a/flo_ai/router/flo_router_factory.py b/flo_ai/router/flo_router_factory.py index 9fd1b125..f66613cf 100644 --- a/flo_ai/router/flo_router_factory.py +++ b/flo_ai/router/flo_router_factory.py @@ -1,5 +1,6 @@ from flo_ai.state.flo_session import FloSession -from flo_ai.router.flo_supervisor import FloSupervisorBuilder +from flo_ai.router.flo_supervisor import FloSupervisor +from flo_ai.router.flo_llm_router import FloLLMRouter from flo_ai.router.flo_linear import FloLinear from flo_ai.yaml.flo_team_builder import TeamConfig from flo_ai.models.flo_team import FloTeam @@ -10,8 +11,10 @@ class FloRouterFactory: @staticmethod def create(session: FloSession, team_config: TeamConfig, flo_team: FloTeam) -> FloRouter: if team_config.router.kind == 'supervisor': - return FloSupervisorBuilder(session, team_config.router.name, flo_team).build() + return FloSupervisor.Builder(session, team_config.router.name, flo_team).build() elif team_config.router.kind == 'linear': - return FloLinear(session, flo_team, team_config.router) + return FloLinear.Builder(session, flo_team, team_config.router).build() + elif team_config.router.kind == 'llm': + return FloLLMRouter.Builder(session, team_config.router.name, flo_team).build() else: raise Exception("Unknown router type") diff --git a/flo_ai/router/flo_supervisor.py b/flo_ai/router/flo_supervisor.py index 98438909..6fb73dff 100644 --- a/flo_ai/router/flo_supervisor.py +++ b/flo_ai/router/flo_supervisor.py @@ -19,7 +19,7 @@ " following {member_type}: {members}. Given the following user request," " respond with the worker to act next. Each worker will perform a" " task and respond with their results and status. When the users question is answered or the assigned task is finished," - " respond with FINISH. If both your workers has responded atleast once, then strictly return FINISH " + " respond with FINISH. " ) class StateUpdateComponent: @@ -76,61 +76,61 @@ def build_team_graph(self): super_graph = super_graph.compile() return FloRoutedTeam(self.flo_team.name, super_graph) -class FloSupervisorBuilder: - def __init__(self, - session: FloSession, - name: str, - flo_team: FloTeam, - supervisor_prompt: Union[ChatPromptTemplate, None] = None, - llm: Union[BaseLanguageModel, None] = None) -> None: - # TODO add validation for reporteess - self.name = randomize_name(name) - self.session = session - self.llm = llm if llm is not None else session.llm - self.flo_team = flo_team - self.agents = flo_team.members - self.members = [agent.name for agent in flo_team.members] - self.options = self.members + [FLO_FINISH] - member_type = "workers" if flo_team.members[0].type == "agent" else "team members" - self.supervisor_prompt = ChatPromptTemplate.from_messages( - [ - ("system", supervisor_system_message), - MessagesPlaceholder(variable_name="messages"), - ( - "system", - "Given the conversation above, who should act next?" - " Or should we FINISH if the task is already answered, (do not wait for the entire question to be answered) or there isn't enough information to answer the question, even then return FINISH? Select one of: {options}", - ), - ] - ).partial(options=str(self.options), members=", ".join(self.members), member_type=member_type) if supervisor_prompt is None else supervisor_prompt - - def build(self): - function_def = { - "name": "route", - "description": "Select the next role.", - "parameters": { - "title": "routeSchema", - "type": "object", - "properties": { - "next": { - "title": "Next", - "anyOf": [ - {"enum": self.options}, - ], - } - }, - "required": ["next"], + class Builder: + def __init__(self, + session: FloSession, + name: str, + flo_team: FloTeam, + supervisor_prompt: Union[ChatPromptTemplate, None] = None, + llm: Union[BaseLanguageModel, None] = None) -> None: + # TODO add validation for reporteess + self.name = randomize_name(name) + self.session = session + self.llm = llm if llm is not None else session.llm + self.flo_team = flo_team + self.agents = flo_team.members + self.members = [agent.name for agent in flo_team.members] + self.options = self.members + [FLO_FINISH] + member_type = "workers" if flo_team.members[0].type == "agent" else "team members" + self.supervisor_prompt = ChatPromptTemplate.from_messages( + [ + ("system", supervisor_system_message), + MessagesPlaceholder(variable_name="messages"), + ( + "system", + "Given the conversation above, who should act next?" + " Or should we FINISH if the task is already answered, Select one of: {options}", + ), + ] + ).partial(options=str(self.options), members=", ".join(self.members), member_type=member_type) if supervisor_prompt is None else supervisor_prompt + + def build(self): + function_def = { + "name": "route", + "description": "Select the next role.", + "parameters": { + "title": "routeSchema", + "type": "object", + "properties": { + "next": { + "title": "Next", + "anyOf": [ + {"enum": self.options}, + ], + } + }, + "required": ["next"], + } } - } - - chain = ( - self.supervisor_prompt - | self.llm.bind_functions(functions=[function_def], function_call="route") - | JsonOutputFunctionsParser() - | StateUpdateComponent(self.name, self.session) - ) + + chain = ( + self.supervisor_prompt + | self.llm.bind_functions(functions=[function_def], function_call="route") + | JsonOutputFunctionsParser() + | StateUpdateComponent(self.name, self.session) + ) - return FloSupervisor(executor = chain, - flo_team=self.flo_team, - name=self.name, - session=self.session) \ No newline at end of file + return FloSupervisor(executor = chain, + flo_team=self.flo_team, + name=self.name, + session=self.session) \ No newline at end of file diff --git a/flo_ai/yaml/flo_team_builder.py b/flo_ai/yaml/flo_team_builder.py index 479b103d..66a75b2e 100644 --- a/flo_ai/yaml/flo_team_builder.py +++ b/flo_ai/yaml/flo_team_builder.py @@ -39,6 +39,7 @@ class AgentConfig(BaseModel): class RouterConfig(BaseModel): name: str kind: str + job: Optional[str] = None start_node: Optional[str] = None end_node: Optional[str] = None edges: Optional[List[List[str]]] = None