update oai tool agent doc (#13147)

pull/13148/head
Bagatur 11 months ago committed by GitHub
parent b298f550fe
commit eb51150557
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -7,7 +7,7 @@
"source": [
"# OpenAI tools\n",
"\n",
"With LCEL we can easily construc"
"With LCEL we can easily construct agents that take advantage of [OpenAI parallel function calling](https://platform.openai.com/docs/guides/function-calling/parallel-function-calling) (a.k.a. tool calling)."
]
},
{
@ -17,17 +17,7 @@
"metadata": {},
"outputs": [],
"source": [
"# ! pip install -U openai duckduckgo-search"
]
},
{
"cell_type": "markdown",
"id": "82787d8d",
"metadata": {},
"source": [
"## Initialize tools\n",
"\n",
"We will first create some tools we can use"
"# !pip install -U openai duckduckgo-search"
]
},
{
@ -37,41 +27,51 @@
"metadata": {},
"outputs": [],
"source": [
"from langchain.agents import initialize_agent, AgentType, Tool\n",
"from langchain.agents import initialize_agent, AgentExecutor, AgentType, Tool\n",
"from langchain.agents.format_scratchpad.openai_tools import (\n",
" format_to_openai_tool_messages,\n",
")\n",
"from langchain.agents.output_parsers.openai_tools import OpenAIToolsAgentOutputParser\n",
"from langchain.chat_models import ChatOpenAI\n",
"from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder\n",
"from langchain.tools import DuckDuckGoSearchRun\n",
"from langchain.tools import DuckDuckGoSearchRun, BearlyInterpreterTool\n",
"from langchain.tools.render import format_tool_to_openai_tool"
]
},
{
"cell_type": "markdown",
"id": "6ef71dfc-074b-409a-8451-863feef937ae",
"metadata": {},
"source": [
"## Tools\n",
"\n",
"For this agent let's give it the ability to search [DuckDuckGo](/docs/integrations/tools/ddg) and use [Bearly's code interpreter](/docs/integrations/tools/bearly). You'll need a Bearly API key, which you can [get here](https://bearly.ai/dashboard)."
]
},
{
"cell_type": "code",
"execution_count": 3,
"execution_count": 24,
"id": "23fc0aa6",
"metadata": {},
"outputs": [],
"source": [
"llm = ChatOpenAI(temperature=0, model=\"gpt-3.5-turbo-1106\")\n",
"tools = [DuckDuckGoSearchRun()]"
"lc_tools = [DuckDuckGoSearchRun(), BearlyInterpreterTool(api_key=\"...\").as_tool()]\n",
"oai_tools = [format_tool_to_openai_tool(tool) for tool in lc_tools]"
]
},
{
"cell_type": "markdown",
"id": "39c3ba21",
"id": "90c293df-ce11-4600-b912-e937215ec644",
"metadata": {},
"source": [
"## Using LCEL\n",
"## Prompt template\n",
"\n",
"We will first use LangChain Expression Language to create this agent"
"We need to make sure we have a user input message and an \"agent_scratchpad\" messages placeholder, which is where the AgentExecutor will track AI messages invoking tools and Tool messages returning the tool output."
]
},
{
"cell_type": "code",
"execution_count": 4,
"execution_count": 18,
"id": "55292bed",
"metadata": {},
"outputs": [],
@ -85,19 +85,39 @@
")"
]
},
{
"cell_type": "markdown",
"id": "32904250-c53e-415e-abdf-7ce8b1357fb7",
"metadata": {},
"source": [
"## Model\n",
"\n",
"Only certain models support parallel function calling, so make sure you're using a compatible model."
]
},
{
"cell_type": "code",
"execution_count": 6,
"execution_count": 19,
"id": "552421b3",
"metadata": {},
"outputs": [],
"source": [
"llm_with_tools = llm.bind(tools=[format_tool_to_openai_tool(t) for t in tools])"
"llm = ChatOpenAI(temperature=0, model=\"gpt-3.5-turbo-1106\")"
]
},
{
"cell_type": "markdown",
"id": "6fc73aa5-e185-4c6a-8770-1279c3ae5530",
"metadata": {},
"source": [
"## Agent\n",
"\n",
"We use the `OpenAIToolsAgentOutputParser` to convert the tool calls returned by the model into `AgentAction`s objects that our `AgentExecutor` can then route to the appropriate tool."
]
},
{
"cell_type": "code",
"execution_count": 7,
"execution_count": 20,
"id": "bf514eb4",
"metadata": {},
"outputs": [],
@ -110,34 +130,40 @@
" ),\n",
" }\n",
" | prompt\n",
" | llm_with_tools\n",
" | llm.bind(tools=oai_tools)\n",
" | OpenAIToolsAgentOutputParser()\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "5125573e",
"cell_type": "markdown",
"id": "ea032e1c-523d-4509-a008-e693529324be",
"metadata": {},
"outputs": [],
"source": [
"from langchain.agents import AgentExecutor"
"## Agent executor"
]
},
{
"cell_type": "code",
"execution_count": 9,
"execution_count": 21,
"id": "bdc7e506",
"metadata": {},
"outputs": [],
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['memory', 'callbacks', 'callback_manager', 'verbose', 'tags', 'metadata', 'agent', 'tools', 'return_intermediate_steps', 'max_iterations', 'max_execution_time', 'early_stopping_method', 'handle_parsing_errors', 'trim_intermediate_steps']\n"
]
}
],
"source": [
"agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)"
"agent_executor = AgentExecutor(agent=agent, tools=lc_tools, verbose=True)"
]
},
{
"cell_type": "code",
"execution_count": 10,
"execution_count": 22,
"id": "2cd65218",
"metadata": {},
"outputs": [
@ -149,24 +175,34 @@
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3m\n",
"Invoking: `duckduckgo_search` with `weather in Los Angeles today`\n",
"Invoking: `duckduckgo_search` with `average temperature in Los Angeles today`\n",
"\n",
"\n",
"\u001b[0m\u001b[36;1m\u001b[1;3mNext week, there is a growing potential for 1 to 2 storms Tuesday through Friday bringing a 90% chance of rain to the area. There is a 50% chance of a moderate storm with 1 to 3 inches of total rainfall, and a 10% chance of a major storm of 3 to 6+ inches. Quick Facts Today's weather: Sunny, windy Beaches: 70s-80s Mountains: 60s-70s/63-81 Inland: 70s Warnings and advisories: Red Flag Warning, Wind Advisory Todays highs along the coast will be in... yesterday temp 66.6 °F Surf Forecast in Los Angeles for today Another important indicators for a comfortable holiday on the beach are the presence and height of the waves, as well as the speed and direction of the wind. Please find below data on the swell size for Los Angeles. Daily max (°C) 19 JAN 18 FEB 19 MAR 20 APR 21 MAY 22 JUN 24 JUL 24 AUG 24 SEP 23 OCT 21 NOV 19 DEC Rainfall (mm) 61 JAN 78° | 53° 60 °F like 60° Clear N 0 Today's temperature is forecast to be NEARLY THE SAME as yesterday. Radar Satellite WunderMap |Nexrad Today Wed 11/08 High 78 °F 0% Precip. / 0.00 in Sunny....\u001b[0m\u001b[32;1m\u001b[1;3m\n",
"Invoking: `duckduckgo_search` with `average temperature in New York City today`\n",
"\n",
"\n",
"\u001b[0m\u001b[36;1m\u001b[1;3mWeather Underground provides local & long-range weather forecasts, weatherreports, maps & tropical weather conditions for the New York City area. ... Today Tue 11/07 High 68 ... Climate Central's prediction for an even more distant date — 2100 — is that the average temperature in 247 cities across the country will be 8 degrees higher than it is now. New York will ... Extended Forecast for New York NY Similar City Names Overnight Mostly Cloudy Low: 48 °F Saturday Partly Sunny High: 58 °F Saturday Night Mostly Cloudy Low: 48 °F Sunday Mostly Sunny High: 64 °F Sunday Night Mostly Clear Low: 45 °F Monday Weather report for New York City. Night and day a few clouds are expected. It is a sunny day. Temperatures peaking at 62 °F. During the night and in the first hours of the day blows a light breeze (4 to 8 mph). For the afternoon a gentle breeze is expected (8 to 12 mph). Graphical Climatology of New York Central Park - Daily Temperatures, Precipitation, and Snowfall (1869 - Present) The following is a graphical climatology of New York Central Park daily temperatures, precipitation, and snowfall, from January 1869 into 2023. The graphics consist of summary overview charts (in some cases including data back into the late 1860's) followed […]\u001b[0m\u001b[32;1m\u001b[1;3m\n",
"Invoking: `duckduckgo_search` with `average temperature in San Francisco today`\n",
"\n",
"\u001b[0m\u001b[36;1m\u001b[1;3m60 °F like 60° Clear N 0 Today's temperature is forecast to be NEARLY THE SAME as yesterday. Radar Satellite WunderMap |Nexrad Today Wed 11/08 High 78 °F 0% Precip. / 0.00 in Sunny. High 78F.... Current Conditions Radar Forecasts Rivers and Lakes Climate and Past Weather Local Programs Fire Weather Show Caption Click a location below for detailed forecast. Last Map Update: Tue, Nov. 7, 2023 at 5:03:23 pm PST Watches, Warnings & Advisories Zoom Out Gale Warning Small Craft Advisory Wind Advisory Fire Weather Watch LOS ANGELES (KABC) -- Southern California will see mostly clear skies and mild temperatures on Monday. Los Angeles and Orange counties will see a few clouds in the morning, but they'll clear up... Storm No. 1: The first storm on Saturday will move quickly through Southern California, with most of the rain falling Saturday night. Light rain is possible late Friday for the Ventura County... Weather in Los Angeles today, California. Friday, 13 October 2023 . Day 1:00 PM +77°F . Broken cloud sky\u001b[0m\u001b[32;1m\u001b[1;3m\n",
"Invoking: `duckduckgo_search` with `weather in New York City today`\n",
"\n",
"\u001b[0m\u001b[36;1m\u001b[1;3mToday Hourly 10-Day Calendar History Wundermap access_time 10:24 PM PST on November 4, 2023 (GMT -8) | Updated 1 day ago 63° | 48° 59 °F like 59° Partly Cloudy N 0 Today's temperature is... The National Weather Service forecast for the greater San Francisco Bay Area on Thursday calls for clouds increasing over the region during the day. Daytime highs are expected to be in the 60s on ... San Francisco (United States of America) weather - Met Office Today 17° 9° Sunny. Sunrise: 06:41 Sunset: 17:05 M UV Wed 8 Nov 19° 8° Thu 9 Nov 16° 9° Fri 10 Nov 16° 10° Sat 11 Nov 18° 9° Sun 12... Today's weather in San Francisco Bay. The sun rose at 6:42am and the sunset will be at 5:04pm. There will be 10 hours and 22 minutes of sun and the average temperature is 54°F. At the moment water temperature is 58°F and the average water temperature is 58°F. Wintry Impacts in Alaska and New England; Critical Fire Conditions in Southern California. A winter storm continues to bring hazardous travel conditions to south-central Alaska with heavy snow, a wintry mix, ice accumulation, and rough seas. A wintry mix including freezing rain is expected in Upstate New York and interior New England.\u001b[0m\u001b[32;1m\u001b[1;3m\n",
"Invoking: `duckduckgo_search` with `current temperature in Los Angeles`\n",
"responded: It seems that the search results did not provide the specific average temperatures for today in Los Angeles, New York City, and San Francisco. Let me try another approach to gather this information for you.\n",
"\n",
"\u001b[0m\u001b[36;1m\u001b[1;3mToday Hourly 10-Day Calendar History Wundermap access_time 11:38 PM EDT on October 31, 2023 (GMT -4) | Updated 22 hours ago --° | 49° 56 °F like 56° Rain Shower N 5 Gusts 7mph Radar Satellite... 49°F 9°C More Information: Local Forecast Office More Local Wx 3 Day History Mobile Weather Hourly Weather Forecast Extended Forecast for New York NY Similar City Names Overnight Mostly Cloudy Low: 48 °F Saturday Partly Sunny High: 58 °F Saturday Night Mostly Cloudy Low: 48 °F Sunday Mostly Sunny High: 64 °F Sunday Night Mostly Clear Low: 45 °F 13°C Get Detailed info Tonight Partly Cloudy Low: 47°F Sunday Mostly Sunny High: 62°F change location New York, NY Weather Forecast Office NWS Forecast Office New York, NY Weather.gov > New York, NY Current Hazards Current Conditions Radar Forecasts Rivers and Lakes Climate and Past Weather Local Programs The weather today in New York City will be comfortable with temperatures around 68°F. During the evening and night time the temperatures will drop to 48 ° F. For deep dive information check out our hourly weather forecast for today down the page. Temperature. 68 ° / 48 °. Chance of rain. 0. %. Today's Weather - New York, NY Nov 02, 2023 3:32 AM Churchill School -- Feels like -- Hi -- Lo -- -- Live Radar Weather Radar Map WEATHER DETAILS New York, NY Windchill -- Daily Rain -- Dew Point -- Monthly Rain -- Humidity -- Avg. Wind -- Pressure -- Wind Gust -- Sunrise -- Moon -- Sunset -- UV Index Low WEATHER FORECAST New York, NY\u001b[0m\u001b[32;1m\u001b[1;3m\n",
"Invoking: `duckduckgo_search` with `weather in San Francisco today`\n",
"\u001b[0m\u001b[36;1m\u001b[1;3mFire Weather Show Caption Click a location below for detailed forecast. Last Map Update: Tue, Nov. 7, 2023 at 5:03:23 pm PST Watches, Warnings & Advisories Zoom Out Gale Warning Small Craft Advisory Wind Advisory Fire Weather Watch Text Product Selector (Selected product opens in current window) Hazards Observations Marine Weather Fire Weather 78° | 53° 60 °F like 60° Clear N 0 Today's temperature is forecast to be NEARLY THE SAME as yesterday. Radar Satellite WunderMap |Nexrad Today Wed 11/08 High 78 °F 0% Precip. / 0.00 in Sunny.... Los Angeles and Orange counties will see a few clouds in the morning, but they'll clear up in the afternoon to bring a high of 76 degrees. Daytime temperatures should stay in the 70s most of... Weather Forecast Office NWS Forecast Office Los Angeles, CA Weather.gov > Los Angeles, CA Current Hazards Current Conditions Radar Forecasts Rivers and Lakes Climate and Past Weather Local Programs Click a location below for detailed forecast. Last Map Update: Fri, Oct. 13, 2023 at 12:44:23 am PDT Watches, Warnings & Advisories Zoom Out Want a minute-by-minute forecast for Los-Angeles, CA? MSN Weather tracks it all, from precipitation predictions to severe weather warnings, air quality updates, and even wildfire alerts.\u001b[0m\u001b[32;1m\u001b[1;3m\n",
"Invoking: `duckduckgo_search` with `current temperature in New York City`\n",
"responded: It seems that the search results did not provide the specific average temperatures for today in Los Angeles, New York City, and San Francisco. Let me try another approach to gather this information for you.\n",
"\n",
"\u001b[0m\u001b[36;1m\u001b[1;3mCurrent Weather for Popular Cities . San Francisco, CA 55 ... New York City, NY Weather Conditions star_ratehome. 55 ... Low: 47°F Sunday Mostly Sunny High: 62°F change location New York, NY Weather Forecast Office NWS Forecast Office New York, NY Weather.gov > New York, NY Current Hazards Current Conditions Radar Forecasts Rivers and Lakes Climate and Past Weather Local Programs Click a location below for detailed forecast. Today Increasing Clouds High: 50 °F Tonight Mostly Cloudy Low: 47 °F Thursday Slight Chance Rain High: 67 °F Thursday Night Mostly Cloudy Low: 48 °F Friday Mostly Cloudy then Slight Chance Rain High: 54 °F Friday Weather report for New York City Night and day a few clouds are expected. It is a sunny day. Temperatures peaking at 62 °F. During the night and in the first hours of the day blows a light breeze (4 to 8 mph). For the afternoon a gentle breeze is expected (8 to 12 mph). Today 13 October, weather in New York City +61°F. Clear sky, Light Breeze, Northwest 5.1 mph. Atmosphere pressure 29.9 inHg. Relative humidity 45%. Tomorrow's night air temperature will drop to +54°F, wind will change to North 2.7 mph. Pressure will remain unchanged 29.9 inHg. Day temperature will remain unchanged +54°F, and night 15 October ...\u001b[0m\u001b[32;1m\u001b[1;3m\n",
"Invoking: `duckduckgo_search` with `current temperature in San Francisco`\n",
"responded: It seems that the search results did not provide the specific average temperatures for today in Los Angeles, New York City, and San Francisco. Let me try another approach to gather this information for you.\n",
"\n",
"\u001b[0m\u001b[36;1m\u001b[1;3mWeather Underground provides local & long-range weather forecasts, weatherreports, maps & tropical weather conditions for the San Francisco area. ... Today Wed 11/08 High 67 ... Radar Forecasts Rivers and Lakes Climate and Past Weather Local Programs Click a location below for detailed forecast. Last Map Update: Wed, Nov. 8, 2023 at 5:03:31 am PST Watches, Warnings & Advisories Zoom Out Small Craft Advisory Frost Advisory Text Product Selector (Selected product opens in current window) Radar Forecasts Rivers and Lakes Climate and Past Weather Local Programs Rain Continues Monday Show Caption Click a location below for detailed forecast. Last Map Update: Tue, Nov. 7, 2023 at 1:05:27 am PST Watches, Warnings & Advisories Zoom Out Winter Weather Advisory Small Craft Advisory Gale Watch Today's and tonight's San Francisco, CA weather forecast, weather conditions and Doppler radar from The Weather Channel and Weather.com Nov 8, 2023. The National Weather Service forecast for the greater San Francisco Bay Area on Wednesday calls for sunny skies, with clouds expected to increase over some areas around the bay during ...\u001b[0m\u001b[32;1m\u001b[1;3mHere's the weather for today in Los Angeles, New York City, and San Francisco:\n",
"\u001b[0m\u001b[36;1m\u001b[1;3m59 °F like 59° Partly Cloudy N 0 Today's temperature is forecast to be COOLER than yesterday. Radar Satellite WunderMap |Nexrad Today Thu 11/09 High 63 °F 3% Precip. / 0.00 in A mix of clouds and... Weather Forecast Office NWS Forecast Office San Francisco, CA Weather.gov > San Francisco Bay Area, CA Current Hazards Current Conditions Radar Forecasts Rivers and Lakes Climate and Past Weather Local Programs Click a location below for detailed forecast. Last Map Update: Wed, Nov. 8, 2023 at 5:03:31 am PST Watches, Warnings & Advisories Zoom Out The weather right now in San Francisco, CA is Cloudy. The current temperature is 62°F, and the expected high and low for today, Sunday, November 5, 2023, are 67° high temperature and 57°F low temperature. The wind is currently blowing at 5 miles per hour, and coming from the South Southwest. The wind is gusting to 5 mph. With the wind and ... San Francisco 7 day weather forecast including weather warnings, temperature, rain, wind, visibility, humidity and UV National - Current Temperatures National - First Alert Doppler Latest Stories More ... San Francisco's 'Rev. G' honored with national Jefferson Award for service, seeking peace\u001b[0m\u001b[32;1m\u001b[1;3m\n",
"Invoking: `bearly_interpreter` with `{'python_code': '(78 + 53 + 55) / 3'}`\n",
"\n",
"- Los Angeles: The temperature is around 60°F with clear skies and mild temperatures. There are no precipitation forecasts for today.\n",
"- New York City: The temperature is around 68°F during the day and will drop to 48°F in the evening and night. There is no chance of rain forecasted for today.\n",
"- San Francisco: The temperature is expected to reach a high of 67°F with sunny skies. Clouds are expected to increase over some areas around the bay during the day.\n",
"\n",
"If you need more detailed information, feel free to ask!\u001b[0m\n",
"\u001b[0m\u001b[33;1m\u001b[1;3m{'stdout': '', 'stderr': '', 'fileLinks': [], 'exitCode': 0}\u001b[0m\u001b[32;1m\u001b[1;3mThe average of the temperatures in Los Angeles, New York City, and San Francisco today is approximately 62 degrees Fahrenheit.\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n"
]
@ -174,26 +210,20 @@
{
"data": {
"text/plain": [
"{'input': \"What's the weather in LA, NYC, and SF today\",\n",
" 'output': \"Here's the weather for today in Los Angeles, New York City, and San Francisco:\\n\\n- Los Angeles: The temperature is around 60°F with clear skies and mild temperatures. There are no precipitation forecasts for today.\\n- New York City: The temperature is around 68°F during the day and will drop to 48°F in the evening and night. There is no chance of rain forecasted for today.\\n- San Francisco: The temperature is expected to reach a high of 67°F with sunny skies. Clouds are expected to increase over some areas around the bay during the day.\\n\\nIf you need more detailed information, feel free to ask!\"}"
"{'input': \"What's the average of the temperatures in LA, NYC, and SF today?\",\n",
" 'output': 'The average of the temperatures in Los Angeles, New York City, and San Francisco today is approximately 62 degrees Fahrenheit.'}"
]
},
"execution_count": 10,
"execution_count": 22,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"agent_executor.invoke({\"input\": \"What's the weather in LA, NYC, and SF today\"})"
"agent_executor.invoke(\n",
" {\"input\": \"What's the average of the temperatures in LA, NYC, and SF today?\"}\n",
")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "c750177f-af6c-4617-b2aa-69e3f1153a3e",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {

Loading…
Cancel
Save