diff --git a/libs/partners/cohere/docs/multi_hop_agent.ipynb b/libs/partners/cohere/docs/multi_hop_agent.ipynb new file mode 100644 index 0000000000000..1ee6806496821 --- /dev/null +++ b/libs/partners/cohere/docs/multi_hop_agent.ipynb @@ -0,0 +1,318 @@ +{ + "cells": [ + { + "cell_type": "raw", + "metadata": {}, + "source": [ + "---\n", + "sidebar_position: 0\n", + "---" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Cohere Tools\n", + "\n", + "The following notebook goes over how to use the Cohere tools agent:" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Prerequisites for this notebook:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# install package\n", + "!pip install -U langchain-cohere\n", + "%pip install wikipedia" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [], + "source": [ + "from langchain.agents import AgentExecutor\n", + "from langchain_cohere.chat_models import ChatCohere\n", + "from langchain_cohere.react_multi_hop.agent import create_cohere_react_agent\n", + "from langchain.retrievers import WikipediaRetriever\n", + "from langchain.tools.retriever import create_retriever_tool\n", + "from langchain_core.prompts import ChatPromptTemplate" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Next we create the prompt template and cohere model" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [], + "source": [ + "# Create the prompt\n", + "prompt = ChatPromptTemplate.from_template(\n", + " \"Write all output in capital letters. {input}\"\n", + ")\n", + "\n", + "# Create the Cohere chat model\n", + "chat = ChatCohere(cohere_api_key=\"API_KEY\", model=\"command-r\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In this example we use a Wikipedia retrieval tool " + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [], + "source": [ + "retriever = WikipediaRetriever()\n", + "retriever_tool = create_retriever_tool(\n", + " retriever,\n", + " \"wikipedia\",\n", + " \"Search for information on Wikipedia\",\n", + ")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Next, create the cohere tool agent and call with the input" + ] + }, + { + "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;3mPlan: First I will search for who the second person to walk on the moon was. Then I will search for that person's mother's hometown and write the answer in capital letters.\n", + "Action: ```json\n", + "[\n", + " {\n", + " \"tool_name\": \"wikipedia\",\n", + " \"parameters\": {\n", + " \"query\": \"second man to walk on the moon\"\n", + " }\n", + " }\n", + "]\n", + "```\u001b[0m\u001b[36;1m\u001b[1;3mWalk the Moon (stylized as WALK THE MOON) is an American pop rock band based in Cincinnati, Ohio. Lead singer Nicholas Petricca started the band in 2006, while a student at Kenyon College, deriving the band's name from the song \"Walking on the Moon\" by The Police. Although the band is best known for their most successful hit single to date \"Shut Up and Dance\", other notable songs include \"Anna Sun\" and \"One Foot\".\n", + "Walk the Moon has cited Talking Heads as influences. The band's use of 1980s musical mainstays, such as keyboard and synthesizer, is also notable.\n", + "\n", + "\n", + "== History ==\n", + "\n", + "\n", + "=== 2010–2011: Beginning, Anna Sun and i Want! i Want! ===\n", + "\n", + "The group independently released their debut studio album, I Want! I Want!, in November 2010, receiving airplay for the track \"Anna Sun\" on multiple alternative radio stations. Along with the success of \"Anna Sun\", Alt Nation named them a band you need to know for the summer of 2012. Influential music blog Neon Gold helped to break the band in January 2011, calling \"Anna Sun\", \"the kind of stuff British A&R dreams, and major label bidding wars, are made of.\" In February 2011, Walk the Moon signed to RCA Records.\n", + "In 2011, the band members began to paint their faces for live performances and they would bring enough paint to share with audience members. They have claimed it has become a “live tradition”. Bonnaroo’s camera crew documented the painting process in a short video from the 2011 festival. The band played at the Sasquatch Music Festival and Firefly Music Festival. In these years, they were known for their energetic performances and tireless touring schedule.\n", + "Before the release of their self-titled album, Walk the Moon joined many other performers at the Music Midtown festival and performed on the Great Southeast Music Hall Stage in Atlanta, Georgia in September 2011. In spring 2011, the band went on a short tour with the west coast band, Grouplove, as well as supporting Panic! at the Disco and Weezer on select dates. The band played on the main stage at the 20th Anniversary of Lollapalooza and also supported Local Natives in an Official Lollaplooza Aftershow at Lincoln Hall.\n", + "The band recorded i Want! i Want! with Chris Schmidt and Ben Cochran at Soap Floats Recording Studio in their hometown of Cincinnati, Ohio and then self-released it. The lead single from the album, \"Anna Sun\", became a surprise hit in the summer of 2011 following an endorsement by the Esquire article \"30 Summer Songs Every Man Should Listen To\". The song was written by Petricca and New York songwriter Nick Lerangis as their time at Kenyon College came to an end. \"It's about college, about maintaining that little bit of being a kid,\" Petricca said. \"Don't be afraid to play.\" The song was named after one of their favorite teachers. It was named song of the summer by MTV and Seventeen Mag, and one of the top songs of the year by Amazon. It has been officially remixed by Fool's Gold and received a Trouble Productions remix by Albert Hammond Jr. Anna Sun rose to the number one spot on Alt. Nation on Sirius XM Radio. \"Anna Sun\" was added to the video rotation of American Eagle Outfitters stores in May 2011. It was featured on the hit TV show Vampire Diaries in the first episode of season three. It was also the free single of the week on iTunes for the week of May 15.\n", + "Filmed in 2011 in Cincinnati's Over-the-Rhine neighborhood, the \"Anna Sun\" music video was released to coincide with the album. The video was shot on-location at the Cincinnati Mockbee building, as well as at a city park. It was directed and produced by Patrick Meier of the Cincinnati company, Contrast Productions, and features original choreography from Kim Popa of PONES Inc., as well as a cast full of the band's friends and locals from Cincinnati. MTV Hive calls the video a \"hilariously choreographed, neon-colored and awesomely shot in one take\" production.\n", + "\n", + "\n", + "=== 2012–2013: Walk the Moon and Tightrope EP ===\n", + "\n", + "The band's self-titled major label debut Walk t\n", + "\n", + "As part of the Apollo program by NASA, 24 astronauts flew nine missions to the Moon between December 1968 and December 1972. During six successful two-man landing missions, twelve men walked on the lunar surface, six of whom drove Lunar Roving Vehicles as part of the last three missions. Three men have been to the Moon twice, one orbited once and took a circumlunar trajectory the second time, while the other two landed once apiece. Apart from these 24 men, no human being has gone beyond low Earth orbit. No woman has been to the Moon, but a number of non-human animals have circled or orbited it, including two tortoises, several turtles, and five mice.\n", + "Apollo missions 8 and 10–17 were the nine crewed missions to the Moon. Apollo 4–6 and AS-201 and AS-202 were uncrewed, while AS-203 is considered a test flight. The Apollo program included three other crewed missions: Apollo 1 (AS-204) did not launch and its crew died in a ground-based capsule fire, while Apollo 7 and Apollo 9 were low Earth orbit missions that only tested spacecraft components and docking maneuvers. Apollo missions 18, 19, and 20 were canceled. Twelve astronauts later flew unused Apollo command modules in the Apollo Applications Program's Skylab and Apollo–Soyuz Test Project. Of the 24 astronauts who flew to the Moon, two went on to command a Skylab mission, one commanded Apollo–Soyuz, one flew as commander for Approach and Landing Tests of the Space Shuttle, and two commanded orbital Space Shuttle missions.\n", + "\n", + "\n", + "== Prime crew members ==\n", + "NASA's Director of Flight Crew Operations during the Gemini and Apollo programs was Donald K. \"Deke\" Slayton, one of the original Mercury Seven astronauts, who was medically grounded in September 1962 due to a minor cardiac arrhythmia – paroxysmal atrial fibrillation. Slayton was responsible for making all Gemini and Apollo crew assignments. In March 1972, Slayton was restored to flight status, and flew on the 1975 Apollo–Soyuz Test Project mission.\n", + "The prime crew members selected for actual missions are here grouped by their NASA astronaut selection groups, and within each group in the order selected for flight. Two versions of the Apollo Command/Service Module (CSM) spacecraft were developed: Block I, intended for preliminary low Earth orbit testing; and Block II, redesigned for the lunar landing. The Block I crew position titles were Command Pilot, Senior Pilot (second seat), and Pilot (third seat). The corresponding Block II titles were: Commander, Command Module Pilot, and Lunar Module Pilot. The second seat pilot was given secondary responsibility for celestial navigation to keep the CSM's guidance computer accurately calibrated with the spacecraft's true position, and the third seat pilot served as a flight engineer, monitoring the health of the spacecraft systems.\n", + "\n", + "\n", + "== Apollo astronauts by their dates of selection by NASA ==\n", + "\n", + "\n", + "=== 1959 ===\n", + "Virgil I. \"Gus\" Grissom began his career at NASA in 1959. In 1966, he was selected as Command Pilot for the first crewed Apollo mission, a low Earth orbit test. This mission ended a month before its scheduled launch, when a cabin fire on the launch pad killed Grissom, Ed White and Roger Chaffee on January 27, 1967.\n", + "Walter M. Schirra Jr. also began his NASA career in 1959. He was selected in October 1968 as Command Pilot for Apollo 7, an 11-day, low Earth orbit shakedown test of the three-man Apollo Command/Service Module and the first crewed launch for the Apollo project.\n", + "Alan B. Shepard Jr. – America's first man in space on Freedom 7 was originally selected to command Gemini 3, but was medically grounded for the duration of Gemini due to Ménière's disease and assisted Slayton in Flight Operations. After corrective surgery, Shepard was restored to flight status and commanded Apollo 14, the third successful Moon landing mission.\n", + "\n", + "\n", + "=== 1962 ===\n", + "\n", + "All of these astronauts flew on Gemini, and except for White, each commanded one Gemini and one Apollo mission:\n", + "\n", + "Edward H. White II – Second-seat \n", + "\n", + "\"Man on the Moon\" is a song by American alternative rock band R.E.M., released in November 1992 as the second single from their eighth album, Automatic for the People (1992). The lyrics were written by lead singer Michael Stipe, and the music by drummer Bill Berry and guitarist Peter Buck. The song was well received by critics and reached number 30 on the US Billboard Hot 100, number 17 on the US Cash Box Top 100, number 18 on the UK Singles Chart, and number one in Iceland. It remains one of R.E.M.'s most popular songs and was included on the compilations In Time: The Best of R.E.M. 1988–2003 and Part Lies, Part Heart, Part Truth, Part Garbage 1982–2011.\n", + "\"Man on the Moon\" is a tribute to comedian Andy Kaufman, with numerous references to his career including his Elvis impersonation, wrestling, and the film My Breakfast with Blassie. The song's title and chorus refer to Moon landing conspiracy theories, as an oblique allusion to rumors that Kaufman's death in 1984 was faked. The song gave its name to Miloš Forman's Kaufman biopic Man on the Moon (1999), and features prominently in the film's soundtrack.\n", + "\n", + "\n", + "== Composition ==\n", + "\"Man on the Moon\" is a mid-tempo country-rock song following a verse-chorus structure with an added pre-chorus and an instrumental bridge following the second and third choruses. The song has six lines in the first verse but only four in the second and third verses.An early instrumental demo of the song was known to the band as \"C to D Slide\". Guitarist Peter Buck has explained how the music came together: \"'Man on the Moon' was something that Bill [Berry] had, this one chord change that he came in with, which was C to D like the verse of the song, and he said: 'I don't know what to do with that.' I used to finish some of Bill's things ... he would come up with the riffs, but I would be the finish guy for that. I sat down and came up with the chorus, the bridges, and so forth. I remember we showed it to Mike and Michael when they came in later; definitely we had the song finished. I think Bill played bass and I played guitar; we kept going around with it. I think we might have played some mandolin on it in the rehearsal studio.\"Michael Stipe explained in an interview with Charlie Rose how the lyric was written independently of the music, which had no prior association with the song's eventual lyrical content regarding Kaufman. Stipe recounted the other R.E.M. members had written and performed the music of the song and recorded it along with the rest of the Automatic for the People album during studio sessions in Seattle. As of the final week of the recording sessions, Stipe was still struggling to write the lyric, and the others continued to plead with him to finish it. Stipe attempted to argue the track should be an instrumental, but his bandmates were insistent. Stipe listened to the track on a walk around Seattle on his Walkman cassette player and was inspired to write about Andy Kaufman. After Stipe went back to the studio to complete the vocal track, the track was mixed that night and sent out the following day to be mastered.\n", + "\n", + "\n", + "== Lyric ==\n", + "The song's lyric does not tell a conventional story and instead forms a collection of cultural references, images and ideas. There are repeated mentions of Andy Kaufman, including references to his Elvis impersonation and work with wrestlers Fred Blassie and Jerry Lawler. The song also invokes the conspiracy theories surrounding the Moon landing and Elvis Presley's death as an indirect nod to the persistent rumors that Kaufman faked his own death. Speaking in 2017 to the NME, Mike Mills explained that the perceived ambiguity of Kaufman's legacy, including questions of whether he was a comedian or a performance artist, and whether his work was funny or irritating, was a way to frame other questions about life within the song:\n", + "\n", + "He's the perfect ghost to lead you through this tour of questioning things. Did the moon landing really happen? Is Elvis really dead? He was ki\u001b[0m\u001b[32;1m\u001b[1;3mReflection: I have found that the second person to walk on the moon was Buzz Aldrin. Now I will search for the hometown of his mother and write the answer in capital letters.\n", + "Action: ```json\n", + "[\n", + " {\n", + " \"tool_name\": \"wikipedia\",\n", + " \"parameters\": {\n", + " \"query\": \"Buzz Aldrin mother's hometown\"\n", + " }\n", + " }\n", + "]\n", + "```\u001b[0m\u001b[36;1m\u001b[1;3mBuzz Aldrin (; born Edwin Eugene Aldrin Jr.; January 20, 1930) is an American former astronaut, engineer and fighter pilot. He made three spacewalks as pilot of the 1966 Gemini 12 mission, and was the Lunar Module Eagle pilot on the 1969 Apollo 11 mission. He was the second person to walk on the Moon after mission commander Neil Armstrong.\n", + "Born in Glen Ridge, New Jersey, Aldrin graduated third in the class of 1951 from the United States Military Academy at West Point with a degree in mechanical engineering. He was commissioned into the United States Air Force and served as a jet fighter pilot during the Korean War. He flew 66 combat missions and shot down two MiG-15 aircraft.\n", + "After earning a Doctor of Science degree in astronautics from the Massachusetts Institute of Technology (MIT), Aldrin was selected as a member of NASA's Astronaut Group 3, making him the first astronaut with a doctoral degree. His doctoral thesis, Line-of-Sight Guidance Techniques for Manned Orbital Rendezvous, earned him the nickname \"Dr. Rendezvous\" from fellow astronauts. His first space flight was in 1966 on Gemini 12, during which he spent over five hours on extravehicular activity. Three years later, Aldrin set foot on the Moon at 03:15:16 on July 21, 1969 (UTC), nineteen minutes after Armstrong first touched the surface, while command module pilot Michael Collins remained in lunar orbit. A Presbyterian elder, Aldrin became the first person to hold a religious ceremony on the Moon when he privately took communion.\n", + "After leaving NASA in 1971, Aldrin became Commandant of the U.S. Air Force Test Pilot School. He retired from the Air Force in 1972 after 21 years of service. His autobiographies Return to Earth (1973) and Magnificent Desolation (2009) recount his struggles with clinical depression and alcoholism in the years after leaving NASA. Aldrin continues to advocate for space exploration, particularly a human mission to Mars. He developed the Aldrin cycler, a special spacecraft trajectory that makes travel to Mars more efficient in terms of time and propellant. He has been accorded numerous honors, including the Presidential Medal of Freedom in 1969.\n", + "\n", + "\n", + "== Early life and education ==\n", + "Aldrin was born Edwin Eugene Aldrin Jr. on January 20, 1930, at Mountainside Hospital in Glen Ridge, New Jersey. His parents, Edwin Eugene Aldrin Sr. and Marion Aldrin (née Moon), lived in neighboring Montclair. His father was an Army aviator during World War I and the assistant commandant of the Army's test pilot school at McCook Field, Ohio, from 1919 to 1922, but left the Army in 1928 and became an executive at Standard Oil. Aldrin had two sisters: Madeleine, who was four years older, and Fay Ann, who was a year and a half older. His nickname, which became his legal first name in 1988, arose as a result of Fay's mispronouncing \"brother\" as \"buzzer\", which was then shortened to \"Buzz\". He was a Boy Scout, achieving the rank of Tenderfoot Scout.Aldrin did well in school, maintaining an A average. He played football and was the starting center for Montclair High School's undefeated 1946 state champion team. His father wanted him to go to the United States Naval Academy in Annapolis, Maryland, and enrolled him at nearby Severn School, a preparatory school for Annapolis, and even secured him a Naval Academy appointment from Albert W. Hawkes, one of the United States senators from New Jersey. Aldrin attended Severn School in 1946, but had other ideas about his future career. He suffered from seasickness and considered ships a distraction from flying airplanes. He faced down his father and told him to ask Hawkes to change the nomination to the United States Military Academy at West Point, New York.Aldrin entered West Point in 1947. He did well academically, finishing first in his class his plebe (first) year. Aldrin was also an excellent athlete, competing in pole vault for the academy track and field team. In 1950, he traveled with a group of West Point cadets to Japan and\n", + "\n", + "Neil Alden Armstrong (August 5, 1930 – August 25, 2012) was an American astronaut and aeronautical engineer who in 1969 became the first person to walk on the Moon. He was also a naval aviator, test pilot, and university professor.\n", + "Armstrong was born and raised in Wapakoneta, Ohio. He entered Purdue University, studying aeronautical engineering, with the U.S. Navy paying his tuition under the Holloway Plan. He became a midshipman in 1949 and a naval aviator the following year. He saw action in the Korean War, flying the Grumman F9F Panther from the aircraft carrier USS Essex. After the war, he completed his bachelor's degree at Purdue and became a test pilot at the National Advisory Committee for Aeronautics (NACA) High-Speed Flight Station at Edwards Air Force Base in California. He was the project pilot on Century Series fighters and flew the North American X-15 seven times. He was also a participant in the U.S. Air Force's Man in Space Soonest and X-20 Dyna-Soar human spaceflight programs.\n", + "Armstrong joined the NASA Astronaut Corps in the second group, which was selected in 1962. He made his first spaceflight as command pilot of Gemini 8 in March 1966, becoming NASA's first civilian astronaut to fly in space. During this mission with pilot David Scott, he performed the first docking of two spacecraft; the mission was aborted after Armstrong used some of his re-entry control fuel to stabilize a dangerous roll caused by a stuck thruster. During training for Armstrong's second and last spaceflight as commander of Apollo 11, he had to eject from the Lunar Landing Research Vehicle moments before a crash.\n", + "On July 20, 1969, Armstrong and Apollo 11 Lunar Module (LM) pilot Buzz Aldrin became the first people to land on the Moon, and the next day they spent two and a half hours outside the Lunar Module Eagle spacecraft while Michael Collins remained in lunar orbit in the Apollo Command Module Columbia. When Armstrong first stepped onto the lunar surface, he famously said: \"That's one small step for [a] man, one giant leap for mankind.\" It was broadcast live to an estimated 530 million viewers worldwide. Apollo 11 was a major U.S. victory in the Space Race, by fulfilling a national goal proposed in 1961 by President John F. Kennedy \"of landing a man on the Moon and returning him safely to the Earth\" before the end of the decade. Along with Collins and Aldrin, Armstrong was awarded the Presidential Medal of Freedom by President Richard Nixon and received the 1969 Collier Trophy. President Jimmy Carter presented him with the Congressional Space Medal of Honor in 1978, he was inducted into the National Aviation Hall of Fame in 1979, and with his former crewmates received the Congressional Gold Medal in 2009.\n", + "After he resigned from NASA in 1971, Armstrong taught in the Department of Aerospace Engineering at the University of Cincinnati until 1979. He served on the Apollo 13 accident investigation and on the Rogers Commission, which investigated the Space Shuttle Challenger disaster. In 2012, Armstrong died due to complications resulting from coronary bypass surgery, at the age of 82.\n", + "\n", + "\n", + "== Early life ==\n", + "Armstrong was born near Wapakoneta, Ohio, on August 5, 1930, the son of Viola Louise (née Engel) and Stephen Koenig Armstrong. He was of German, English, Scots-Irish, and Scottish descent. He is a descendant of Clan Armstrong. He had a younger sister, June, and a younger brother, Dean. His father was an auditor for the Ohio state government, and the family moved around the state repeatedly, living in 16 towns over the next 14 years. Armstrong's love for flying grew during this time, having started at the age of two when his father took him to the Cleveland Air Races. When he was five or six, he experienced his first airplane flight in Warren, Ohio, when he and his father took a ride in a Ford Trimotor (also known as the \"Tin Goose\").The family's last move was in 1944 and took them back to Wapakoneta, where Armstrong attended Blume High Scho\n", + "\n", + "David Kaufman (born July 23, 1961) is an American actor. He is best known for his voice roles of Dexter Douglas in Freakazoid!, Jimmy Olsen in various DC projects beginning with Superman: The Animated Series, the titular protagonist in Danny Phantom, Aldrin in The Buzz on Maggie, Marty McFly in Back to the Future, and Stuart Little in the animated series of the same name. He often is a voice double for Michael J. Fox.\n", + "\n", + "\n", + "== Early life ==\n", + "Kaufman was born and raised in St. Louis, Missouri. His father is Jewish, while his mother is Catholic. Kaufman began acting at a young age in his hometown when his kindergarten teacher handed him the plum lead role of Santa Claus in the class Christmas play.\n", + "At the age of 18, Kaufman moved from St. Louis to attend UCLA; he was a student in the Department of Theater Arts.\n", + "\n", + "\n", + "== Career ==\n", + "Since his college years, Kaufman has studied and worked extensively as a professional actor in films and television.\n", + "He has worked with the Daly family of actors on several projects: He worked with Tim Daly on Superman: The Animated Series and its subsequent spin-offs, playing Jimmy Olsen. He also appeared with Daly in the series Wings in 1995 with his wife Lisa; the two portrayed a couple whose wedding Daly's character Joe and his fiancée Helen crash. He worked with Tim's sister, Tyne Daly on Kids Like These and joined Tim again in Justice League: Doom, reprising his role of Jimmy Olsen.\n", + "Kaufman has also worked as a commercial actor. One of his most prominent roles was as a dancing stockboy in a 1989 commercial for Hi-C Ecto Cooler.\n", + "\n", + "\n", + "== Personal life ==\n", + "On June 30, 1990, Kaufman married actress Lisa Picotte; together, they have two children who are also actors, including Grace Kaufman and Henry Kaufman. He came out as bisexual on Celebrate Bisexuality Day in 2021.\n", + "\n", + "\n", + "== Filmography ==\n", + "\n", + "\n", + "=== Television series ===\n", + "\n", + "\n", + "=== Films ===\n", + "\n", + "\n", + "=== Video games ===\n", + "\n", + "\n", + "=== Commercials ===\n", + "AT&T (starring with Ray Walston)\n", + "Pepsi (starring with Cindy Crawford)\n", + "Blockbuster (starring with Magic Johnson)\n", + "Kid Cuisine (voice of K. C. Penguin)as well as spots for Honda, Hi-C Ecto-Cooler, Maxwell House, Dentyne, Chili's, Midas, Wendy's, Twiglets and British Petroleum, among others.\n", + "\n", + "\n", + "=== Stage work ===\n", + "Kaufman has earned several Los Angeles area critics' awards and nominations.\n", + "He has been a member of the West Coast Ensemble in Los Angeles for over ten years, performing such varied roles as:\n", + "\n", + "Skeets Miller in Floyd Collins\n", + "Prosecutor Gilmer in To Kill a Mockingbird\n", + "George Lewis in Kaufman and Hart's Once in a Lifetime\n", + "Orestes in Electra\n", + "Tyler in Sondheim and Furth's Merrily We Roll Along\n", + "Ronnie Shaughnessy in The House of Blue Leaves\n", + "Callimaco in Machiavelli's The Mandrake\n", + "Eugene Jerome in Neil Simon's Biloxi Blues\n", + "Paul Palmer in James Duff's A Quarrel of Sparrows at The Court Theatre in Los Angeles\n", + "Stewie in the premiere of Richard Greenberg's Night and Her Stars at South Coast Repertory.\n", + "\n", + "\n", + "== References ==\n", + "\n", + "\n", + "== External links ==\n", + "David Kaufman at IMDb\u001b[0m\u001b[32;1m\u001b[1;3mRelevant Documents: 1\n", + "Cited Documents: 1\n", + "Answer: MONTclair, NEW JERSEY.\n", + "Grounded answer: Montclair, New Jersey.\u001b[0m\n", + "\n", + "\u001b[1m> Finished chain.\u001b[0m\n" + ] + }, + { + "data": { + "text/plain": [ + "{'input': 'What was the hometown of the mother of the second person to walk on the moon?',\n", + " 'output': 'MONTclair, NEW JERSEY.'}" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "agent = create_cohere_react_agent(\n", + " llm=chat,\n", + " tools=[retriever_tool],\n", + " prompt=prompt,\n", + ")\n", + "agent_executor = AgentExecutor(agent=agent, tools=[retriever_tool], verbose=True)\n", + "agent_executor.invoke({\"input\": \"What was the hometown of the mother of the second person to walk on the moon?\"})" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "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.7" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/libs/partners/cohere/langchain_cohere/__init__.py b/libs/partners/cohere/langchain_cohere/__init__.py index 52d53361931f4..17dc3c35defa0 100644 --- a/libs/partners/cohere/langchain_cohere/__init__.py +++ b/libs/partners/cohere/langchain_cohere/__init__.py @@ -2,6 +2,7 @@ from langchain_cohere.cohere_agent import create_cohere_tools_agent from langchain_cohere.embeddings import CohereEmbeddings from langchain_cohere.rag_retrievers import CohereRagRetriever +from langchain_cohere.react_multi_hop.agent import create_cohere_react_agent from langchain_cohere.rerank import CohereRerank __all__ = [ @@ -11,4 +12,5 @@ "CohereRagRetriever", "CohereRerank", "create_cohere_tools_agent", + "create_cohere_react_agent", ] diff --git a/libs/partners/cohere/langchain_cohere/chat_models.py b/libs/partners/cohere/langchain_cohere/chat_models.py index 8babfc3e16bc9..19cc20dd1e1ee 100644 --- a/libs/partners/cohere/langchain_cohere/chat_models.py +++ b/libs/partners/cohere/langchain_cohere/chat_models.py @@ -66,6 +66,7 @@ def get_cohere_chat_request( *, documents: Optional[List[Dict[str, str]]] = None, connectors: Optional[List[Dict[str, str]]] = None, + stop_sequences: Optional[List[str]] = None, **kwargs: Any, ) -> Dict[str, Any]: """Get the request for the Cohere chat API. @@ -115,6 +116,7 @@ def get_cohere_chat_request( "documents": formatted_docs, "connectors": connectors, "prompt_truncation": prompt_truncation, + "stop_sequences": stop_sequences, **kwargs, } @@ -180,7 +182,9 @@ def _stream( run_manager: Optional[CallbackManagerForLLMRun] = None, **kwargs: Any, ) -> Iterator[ChatGenerationChunk]: - request = get_cohere_chat_request(messages, **self._default_params, **kwargs) + request = get_cohere_chat_request( + messages, stop_sequences=stop, **self._default_params, **kwargs + ) if hasattr(self.client, "chat_stream"): # detect and support sdk v5 stream = self.client.chat_stream(**request) @@ -210,7 +214,9 @@ async def _astream( run_manager: Optional[AsyncCallbackManagerForLLMRun] = None, **kwargs: Any, ) -> AsyncIterator[ChatGenerationChunk]: - request = get_cohere_chat_request(messages, **self._default_params, **kwargs) + request = get_cohere_chat_request( + messages, stop_sequences=stop, **self._default_params, **kwargs + ) if hasattr(self.async_client, "chat_stream"): # detect and support sdk v5 stream = self.async_client.chat_stream(**request) @@ -266,7 +272,9 @@ def _generate( ) return generate_from_stream(stream_iter) - request = get_cohere_chat_request(messages, **self._default_params, **kwargs) + request = get_cohere_chat_request( + messages, stop_sequences=stop, **self._default_params, **kwargs + ) response = self.client.chat(**request) generation_info = self._get_generation_info(response) @@ -290,7 +298,9 @@ async def _agenerate( ) return await agenerate_from_stream(stream_iter) - request = get_cohere_chat_request(messages, **self._default_params, **kwargs) + request = get_cohere_chat_request( + messages, stop_sequences=stop, **self._default_params, **kwargs + ) response = self.client.chat(**request) generation_info = self._get_generation_info(response) diff --git a/libs/partners/cohere/langchain_cohere/cohere_agent.py b/libs/partners/cohere/langchain_cohere/cohere_agent.py index 5bf8328e8c6f2..8481c0768e8ab 100644 --- a/libs/partners/cohere/langchain_cohere/cohere_agent.py +++ b/libs/partners/cohere/langchain_cohere/cohere_agent.py @@ -11,7 +11,12 @@ from langchain_core.runnables import Runnable, RunnablePassthrough from langchain_core.runnables.base import RunnableLambda from langchain_core.tools import BaseTool -from langchain_core.utils.function_calling import convert_to_openai_function +from langchain_core.utils.function_calling import ( + PYTHON_TO_JSON_TYPES, + convert_to_openai_function, +) + +JSON_TO_PYTHON_TYPES = {v: k for k, v in PYTHON_TO_JSON_TYPES.items()} def create_cohere_tools_agent( @@ -83,8 +88,12 @@ def _convert_to_cohere_tool( description=tool.description, parameter_definitions={ param_name: ToolParameterDefinitionsValue( - description=param_definition.get("description"), - type=param_definition.get("type"), + description=param_definition.get("description") + if "description" in param_definition + else "", + type=JSON_TO_PYTHON_TYPES.get( + param_definition.get("type"), param_definition.get("type") + ), required="default" not in param_definition, ) for param_name, param_definition in tool.args.items() @@ -101,7 +110,9 @@ def _convert_to_cohere_tool( parameter_definitions={ param_name: ToolParameterDefinitionsValue( description=param_definition.get("description"), - type=param_definition.get("type"), + type=JSON_TO_PYTHON_TYPES.get( + param_definition.get("type"), param_definition.get("type") + ), required="default" not in param_definition, ) for param_name, param_definition in tool.get("properties", {}).items() @@ -121,7 +132,9 @@ def _convert_to_cohere_tool( parameter_definitions={ param_name: ToolParameterDefinitionsValue( description=param_definition.get("description"), - type=param_definition.get("type"), + type=JSON_TO_PYTHON_TYPES.get( + param_definition.get("type"), param_definition.get("type") + ), required=param_name in parameters.get("required", []), ) for param_name, param_definition in properties.items() diff --git a/libs/partners/cohere/langchain_cohere/llms.py b/libs/partners/cohere/langchain_cohere/llms.py index 4cf30e42a3b01..2f8463464a629 100644 --- a/libs/partners/cohere/langchain_cohere/llms.py +++ b/libs/partners/cohere/langchain_cohere/llms.py @@ -69,6 +69,8 @@ class BaseCohere(Serializable): user_agent: str = "langchain" """Identifier for the application making the request.""" + timeout_seconds: Optional[float] = 300 + @root_validator() def validate_environment(cls, values: Dict) -> Dict: """Validate that api key and python package exists in environment.""" @@ -76,12 +78,15 @@ def validate_environment(cls, values: Dict) -> Dict: get_from_dict_or_env(values, "cohere_api_key", "COHERE_API_KEY") ) client_name = values["user_agent"] + timeout_seconds = values.get("timeout_seconds") values["client"] = cohere.Client( api_key=values["cohere_api_key"].get_secret_value(), + timeout=timeout_seconds, client_name=client_name, ) values["async_client"] = cohere.AsyncClient( api_key=values["cohere_api_key"].get_secret_value(), + timeout=timeout_seconds, client_name=client_name, ) return values diff --git a/libs/partners/cohere/langchain_cohere/react_multi_hop/__init__.py b/libs/partners/cohere/langchain_cohere/react_multi_hop/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/libs/partners/cohere/langchain_cohere/react_multi_hop/agent.py b/libs/partners/cohere/langchain_cohere/react_multi_hop/agent.py new file mode 100644 index 0000000000000..66a6d2982b263 --- /dev/null +++ b/libs/partners/cohere/langchain_cohere/react_multi_hop/agent.py @@ -0,0 +1,317 @@ +import json +import logging +import re +from typing import Callable, Dict, List, Sequence, Tuple, Union + +from langchain_core.agents import AgentAction, AgentFinish +from langchain_core.language_models import BaseLanguageModel +from langchain_core.messages.ai import AIMessage +from langchain_core.messages.base import BaseMessage +from langchain_core.messages.system import SystemMessage +from langchain_core.output_parsers import BaseOutputParser +from langchain_core.prompts.base import BasePromptTemplate +from langchain_core.prompts.chat import ChatPromptTemplate +from langchain_core.runnables import Runnable, RunnablePassthrough +from langchain_core.tools import BaseTool + +from langchain_cohere.cohere_agent import JSON_TO_PYTHON_TYPES +from langchain_cohere.react_multi_hop.prompt import ( + multi_hop_prompt_template, + render_structured_preamble, +) + +""" + Cohere multi-hop tool allows you to use multiple tools in parallel or + sequentially to complete your task. The agent uses a multi hop prompt by Cohere. + This prompt is experimental and subject to change. +""" + + +def create_cohere_react_agent( + llm: BaseLanguageModel, + tools: Sequence[BaseTool], + prompt: ChatPromptTemplate, +) -> Runnable: + agent = ( + RunnablePassthrough.assign( + # Handled in the multi_hop_prompt + agent_scratchpad=lambda _: [], + ) + | _multi_hop_prompt(tools=tools, prompt=prompt) + | llm.bind(stop=["\nObservation:"], raw_prompting=True) + | CohereToolsReactAgentOutputParser() + ) + return agent + + +class CohereToolsReactAgentOutputParser( + BaseOutputParser[Union[List[AgentAction], AgentFinish]] +): + """Parses a message into agent actions/finish.""" + + def parse_jsonified_tool_use_generation( + self, tool_use_generation: str, tool_use_prefix: str + ) -> List[Dict]: + """Parses model-generated jsonified actions. + + Expects input of the form + "{tool_use_prefix}: ```json\n[{list of jsonified objects}]```" + + outputs parsed list of jsonified objects. + """ + + def _extract_codeblocks_from_md(text: str) -> List[str]: + return re.findall(r"`{3}([^`]*)`{0,3}", text) + + raw_generation = re.sub(f"^{tool_use_prefix} ", "", tool_use_generation) + code_block_sections = _extract_codeblocks_from_md(raw_generation) + + if len(code_block_sections) != 1: # should have exactly 1 code block + raise ValueError(f"Action Parsing Failed: {tool_use_generation}") + # only json allowed: + assert code_block_sections[0].startswith( + "json\n" + ), f"Action Parsing Failed: {tool_use_generation}" + + actions = json.loads(re.sub("^json\n", "", code_block_sections[0])) + + if not isinstance(actions, list): + raise ValueError(f"Action Parsing Failed: {tool_use_generation}") + + if len(actions): + if any( + not isinstance(action, Dict) or "tool_name" not in action + for action in actions + ): + raise ValueError(f"Action Parsing Failed: {tool_use_generation}") + return actions + + def parse_answer_with_prefixes( + self, completion: str, prefixes: Dict[str, str] + ) -> Dict[str, str]: + """parses string into key-value pairs, + according to patterns supplied in prefixes. Also strips. + + if inputs are: + completion = "\nhello: sam\ngoodbye then: paul.", + prefixes = {"greeting": "hello:", "farewell": "goodbye then:"} + + the expected returned result is: + {"greeting": "sam", "farewell": "paul."} + + Args: + completion (str): text to split + prefixes (Dict[str, str]): a key-value dict of keys and patterns. + See example above + + Returns: + Dict[str, str]: parsed result + """ + # sort out prefixes + re_pat = "(" + "|".join([re.escape(p) for p in prefixes.values()]) + ")" + reverse_prefix_map = {v: k for k, v in prefixes.items()} + split = re.split(re_pat, completion) + split = split[1:] + parsed = {} + for prefix, value in zip(split[::2], split[1::2]): + if prefix in reverse_prefix_map: # if the prefix is a match + if ( + reverse_prefix_map[prefix] not in parsed + ): # first occurrence of a prefix is kept, others discarded + parsed[reverse_prefix_map[prefix]] = value.strip() + return parsed + + def parse_actions(self, generation: str) -> Tuple[str, str, List[Dict]]: + """Parse action selections from model output.""" + plan = "" + actions = generation + try: + if "Plan: " in generation or "Reflection: " in generation: + # Model is trained to output a Plan or Reflection followed by an action. + # Use regex to extract the plan and action. + regex = ( + r"^(Plan|Reflection)\s*\d*\s*:(.*?)" + + r"(Action\s*\d*\s*:\s*\d*\s*```json\n.*?```)" + ) + action_match = re.search(regex, generation, re.DOTALL) + if not action_match: + raise ValueError( + f"Failed to parse multihop completion for input: {generation}" + ) + plan = action_match.group(2).strip() + actions = action_match.group(3).strip() + else: + # Catch the case where model outputs only an action. + regex = r"^(Action\s*\d*\s*:\s*\d*\s*```json\n.*?```)" + action_match = re.search(regex, generation, re.DOTALL) + if not action_match: + raise ValueError( + f"Failed to parse multihop completion for input: {generation}" + ) + actions = action_match.group(1).strip() + except Exception as e: + logging.error( + f"Failed to parse multihop completion for input: {generation}" + ) + logging.error(f"Error: {e}") + + parsed_actions = self.parse_jsonified_tool_use_generation(actions, "Action:") + return generation, plan, parsed_actions + + def parse(self, text: str) -> Union[List[AgentAction], AgentFinish]: + # Parse the structured output of the final answer. + if "Answer: " in text: + prefix_map = { + "answer": "Answer:", + "grounded_answer": "Grounded answer:", + "relevant_docs": "Relevant Documents:", + "cited_docs": "Cited Documents:", + } + parsed_answer = self.parse_answer_with_prefixes(text, prefix_map) + return AgentFinish({"output": parsed_answer["answer"]}, text) + elif any([x in text for x in ["Plan: ", "Reflection: ", "Action: "]]): + completion, plan, actions = self.parse_actions(text) + return [ + AgentAction( + action["tool_name"], + action["parameters"], + f"\n{action}\n" if i > 0 else f"\n{plan}\n{action}\n", + ) + for i, action in enumerate(actions) + ] + else: + raise ValueError( + "\nCould not parse generation as it did not contain Plan, Reflection," + + f"Action, or Answer. Input: {text}\n\n" + ) + + +def get_type(type_: str, is_optional: bool) -> str: + python_type = JSON_TO_PYTHON_TYPES.get(type_, type_) + if is_optional: + return f"Optional[{python_type}]" + else: + return python_type + + +def get_tool_signature(tool: BaseTool) -> str: + """Get the tool signature.""" + args = [] + for parameter_name, parameter_definition in tool.args.items(): + type_ = get_type( + parameter_definition.get("type"), "default" in parameter_definition + ) + args.append(f"{parameter_name}: {type_}") + signature = ", ".join(args) + return f"def {tool.name}({signature}) -> List[Dict]:" + + +def get_tool_args(tool: BaseTool) -> str: + """Get the tool args.""" + if not tool.args: + return "" + rendered_args = [] + for parameter_name, parameter_definition in tool.args.items(): + type_ = get_type( + parameter_definition.get("type"), "default" in parameter_definition + ) + description = parameter_definition.get("description") + rendered_args.append(f"{parameter_name} ({type_}): {description}") + indent = " " * 12 + return "\n\n" + f"\n{indent}".join(rendered_args) + + +def render_chat_history(chat_history: List[BaseMessage]) -> str: + """Render chat history.""" + return "".join( + [ + f"<|START_OF_TURN_TOKEN|>{get_role(message)}{message.content}<|END_OF_TURN_TOKEN|>" + for message in chat_history + ] + ) + + +def get_role(message: BaseMessage) -> str: + if isinstance(message, AIMessage): + return "<|CHATBOT_TOKEN|>" + elif isinstance(message, SystemMessage): + return "<|SYSTEM_TOKEN|>" + else: + return "<|USER_TOKEN|>" + + +def render_tool_description(tool: BaseTool) -> str: + """Render the tool name and description. + + For example: + ```python + def calculator_calc(expression: str) -> List[Dict]: + \"\"\"This is a powerful multi-purpose calculator. + It is capable of a wide array of math calculation and a range of features. + + Args: + expression (str): The expression for the calculator to evaluate. + + \"\"\" + pass + ``` + """ + + template = """ +```python +{tool_signature} + \"\"\"{tool_description} + Args: + {tool_args} + \"\"\" + pass +```""" + return template.format( + tool_signature=get_tool_signature(tool), + tool_description=tool.description, + tool_args=get_tool_args(tool), + ) + + +def format_cohere_log_to_str( + intermediate_steps: List[Tuple[AgentAction, str]], + observation_prefix: str = "<|END_OF_TURN_TOKEN|>\n<|START_OF_TURN_TOKEN|>" + + "<|SYSTEM_TOKEN|>\n", + llm_prefix: str = "<|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|>" + + "<|CHATBOT_TOKEN|>", +) -> str: + """Construct the scratchpad that lets the agent continue its thought process.""" + thoughts = "" + last_log = "" + # Global result idx to be used for grounded answer citation from any prior action. + + result_idx = 0 + for step_i, (action, observation) in enumerate(intermediate_steps): + # For parallel tool calls, dont add the action call twice, add all the results. + if action.log != last_log: + thoughts += action.log + last_log = action.log + if step_i > 0: + thoughts += "\n" + observation_str = f"Document: {result_idx}\n{observation}" + result_idx += 1 + thoughts += f"{observation_prefix}{observation_str}{llm_prefix}" + + return thoughts + + +def _multi_hop_prompt( + tools: Sequence[BaseTool], prompt: ChatPromptTemplate +) -> Callable: + def inner(x: Dict) -> BasePromptTemplate: + return multi_hop_prompt_template.partial( + structured_preamble=render_structured_preamble( + user_preamble=x.get("preamble", None) + ), + tools="\n".join([render_tool_description(t) for t in tools]), + user_prompt=prompt.invoke(x).to_string(), + steps=format_cohere_log_to_str(x["intermediate_steps"]), + history=render_chat_history(x.get("chat_history", [])), + ) + + return inner diff --git a/libs/partners/cohere/langchain_cohere/react_multi_hop/prompt.py b/libs/partners/cohere/langchain_cohere/react_multi_hop/prompt.py new file mode 100644 index 0000000000000..cdec9533f8a9b --- /dev/null +++ b/libs/partners/cohere/langchain_cohere/react_multi_hop/prompt.py @@ -0,0 +1,77 @@ +# flake8: noqa +from datetime import datetime +from typing import Optional + +from langchain_core.prompts import PromptTemplate + +default_basic_rules = "You are a powerful language agent trained by Cohere to help people. You are capable of complex reasoning and augmented with a number of tools. Your job is to plan and reason about how you will use and consume the output of these tools to best help the user. You will see a conversation history between yourself and a user, ending with an utterance from the user. You will then see an instruction informing you what kind of response to generate. You will construct a plan and then perform a number of reasoning and action steps to solve the problem. When you have determined the answer to the user's request, you will cite your sources in your answers, according the instructions." + +now = datetime.now().strftime("%A, %B %d, %Y %H:%M:%S") +default_task_context = f"""You use your advanced complex reasoning capabilities to help people by answering their questions and other requests interactively. You will be asked a very wide array of requests on all kinds of topics. You will be equipped with a wide range of search engines or similar tools to help you, which you use to research your answer. You may need to use multiple tools in parallel or sequentially to complete your task. You should focus on serving the user's needs as best you can, which will be wide-ranging. The current date is {now}.""" + +default_style_guide = """Unless the user asks for a different style of answer, you should answer in full sentences, using proper grammar and spelling.""" + +default_safety_rules = """The instructions in this section override those in the task description and style guide sections. Don't answer questions that are harmful or immoral.""" + +default_system_prefix = """<|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|>""" + +overridable_preamble = """## Task And Context +{TASK_CONTEXT} + +## Style Guide +{STYLE_GUIDE}""" + +structured_preamble_template = """{SYSTEM_PREFIX}# Safety Preamble +{SAFETY_PREAMBLE} + +# System Preamble +## Basic Rules +{BASIC_RULES} + +# User Preamble +{USER_PREAMBLE}""" + + +def render_structured_preamble( + user_preamble: Optional[str] = None, + system_prefix: Optional[str] = default_system_prefix, + basic_rules: Optional[str] = default_basic_rules, + task_context: Optional[str] = default_task_context, + safety_rules: Optional[str] = default_safety_rules, +) -> str: + if user_preamble is None: + user_preamble = overridable_preamble.format( + STYLE_GUIDE=default_style_guide, + TASK_CONTEXT=task_context, + ) + return structured_preamble_template.format( + SYSTEM_PREFIX=system_prefix, + BASIC_RULES=basic_rules, + USER_PREAMBLE=user_preamble, + SAFETY_PREAMBLE=safety_rules, + ) + + +multi_hop_instruction = """Carefully perform the following instructions, in order, starting each with a new line. +Firstly, You may need to use complex and advanced reasoning to complete your task and answer the question. Think about how you can use the provided tools to answer the question and come up with a high level plan you will execute. +Write 'Plan:' followed by an initial high level plan of how you will solve the problem including the tools and steps required. +Secondly, Carry out your plan by repeatedly using actions, reasoning over the results, and re-evaluating your plan. Perform Action, Observation, Reflection steps with the following format. Write 'Action:' followed by a json formatted action containing the "tool_name" and "parameters" + Next you will analyze the 'Observation:', this is the result of the action. +After that you should always think about what to do next. Write 'Reflection:' followed by what you've figured out so far, any changes you need to make to your plan, and what you will do next including if you know the answer to the question. +... (this Action/Observation/Reflection can repeat N times) +Thirdly, Decide which of the retrieved documents are relevant to the user's last input by writing 'Relevant Documents:' followed by comma-separated list of document numbers. If none are relevant, you should instead write 'None'. +Fourthly, Decide which of the retrieved documents contain facts that should be cited in a good answer to the user's last input by writing 'Cited Documents:' followed a comma-separated list of document numbers. If you don't want to cite any of them, you should instead write 'None'. +Fifthly, Write 'Answer:' followed by a response to the user's last input in high quality natural english. Use the retrieved documents to help you. Do not insert any citations or grounding markup. +Finally, Write 'Grounded answer:' followed by a response to the user's last input in high quality natural english. Use the symbols and to indicate when a fact comes from a document in the search result, e.g my fact for a fact from document 4.""" + + +multi_hop_prompt_template = PromptTemplate.from_template( + """{structured_preamble} + +## Available Tools +Here is a list of tools that you have available to you: + +{tools}<|END_OF_TURN_TOKEN|>{history}<|START_OF_TURN_TOKEN|><|USER_TOKEN|>{user_prompt}<|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|SYSTEM_TOKEN|>{multi_hop_instruction}<|END_OF_TURN_TOKEN|><|START_OF_TURN_TOKEN|><|CHATBOT_TOKEN|>{steps}""" +).partial( + multi_hop_instruction=multi_hop_instruction, +) diff --git a/libs/partners/cohere/tests/unit_tests/test_cohere_agent.py b/libs/partners/cohere/tests/unit_tests/test_cohere_agent.py index 9dc082a55e671..e3bc37a8dae82 100644 --- a/libs/partners/cohere/tests/unit_tests/test_cohere_agent.py +++ b/libs/partners/cohere/tests/unit_tests/test_cohere_agent.py @@ -12,17 +12,17 @@ "arg_1": { "description": "Arg1 description", "required": True, - "type": "string", + "type": "str", }, "optional_arg_2": { "description": "Arg2 description", "required": False, - "type": "string", + "type": "str", }, "arg_3": { "description": "Arg3 description", "required": True, - "type": "integer", + "type": "int", }, }, } diff --git a/libs/partners/cohere/tests/unit_tests/test_imports.py b/libs/partners/cohere/tests/unit_tests/test_imports.py index 0159c19e94ea9..b34708aa5d863 100644 --- a/libs/partners/cohere/tests/unit_tests/test_imports.py +++ b/libs/partners/cohere/tests/unit_tests/test_imports.py @@ -7,6 +7,7 @@ "CohereRagRetriever", "CohereRerank", "create_cohere_tools_agent", + "create_cohere_react_agent", ]