from langchain_community.tools.tavily_search import TavilySearchResults
from langchain_openai import ChatOpenAI
= ChatOpenAI(model="gpt-4o") model
15 Building Agent
https://python.langchain.com/v0.2/docs/tutorials/agents/
15.1 Search with Tavily
= TavilySearchResults(max_results=2)
search = search.invoke("what is the weather in SF")
search_results print(search_results)
[{'url': 'https://www.weatherapi.com/', 'content': "{'location': {'name': 'San Francisco', 'region': 'California', 'country': 'United States of America', 'lat': 37.78, 'lon': -122.42, 'tz_id': 'America/Los_Angeles', 'localtime_epoch': 1722692537, 'localtime': '2024-08-03 6:42'}, 'current': {'last_updated_epoch': 1722691800, 'last_updated': '2024-08-03 06:30', 'temp_c': 14.3, 'temp_f': 57.7, 'is_day': 1, 'condition': {'text': 'Patchy rain nearby', 'icon': '//cdn.weatherapi.com/weather/64x64/day/176.png', 'code': 1063}, 'wind_mph': 4.0, 'wind_kph': 6.5, 'wind_degree': 244, 'wind_dir': 'WSW', 'pressure_mb': 1015.0, 'pressure_in': 29.98, 'precip_mm': 0.01, 'precip_in': 0.0, 'humidity': 90, 'cloud': 77, 'feelslike_c': 14.2, 'feelslike_f': 57.6, 'windchill_c': 14.2, 'windchill_f': 57.6, 'heatindex_c': 14.3, 'heatindex_f': 57.7, 'dewpoint_c': 12.6, 'dewpoint_f': 54.6, 'vis_km': 10.0, 'vis_miles': 6.0, 'uv': 1.0, 'gust_mph': 7.1, 'gust_kph': 11.4}}"}, {'url': 'https://world-weather.info/forecast/usa/san_francisco/08-march/', 'content': 'Detailed ⚡ Weather Forecast for March 8 in San Francisco, California, United States - 🌡️ temperature, wind, atmospheric pressure, humidity and precipitations - World-Weather.info. Add the current city. Search. Weather; Archive ... March 06 March 07 Select date: March 09 March 10. March 08, 2024 : Atmospheric conditions and temperature ...'}]
search_results
[{'url': 'https://www.weatherapi.com/',
'content': "{'location': {'name': 'San Francisco', 'region': 'California', 'country': 'United States of America', 'lat': 37.78, 'lon': -122.42, 'tz_id': 'America/Los_Angeles', 'localtime_epoch': 1722692537, 'localtime': '2024-08-03 6:42'}, 'current': {'last_updated_epoch': 1722691800, 'last_updated': '2024-08-03 06:30', 'temp_c': 14.3, 'temp_f': 57.7, 'is_day': 1, 'condition': {'text': 'Patchy rain nearby', 'icon': '//cdn.weatherapi.com/weather/64x64/day/176.png', 'code': 1063}, 'wind_mph': 4.0, 'wind_kph': 6.5, 'wind_degree': 244, 'wind_dir': 'WSW', 'pressure_mb': 1015.0, 'pressure_in': 29.98, 'precip_mm': 0.01, 'precip_in': 0.0, 'humidity': 90, 'cloud': 77, 'feelslike_c': 14.2, 'feelslike_f': 57.6, 'windchill_c': 14.2, 'windchill_f': 57.6, 'heatindex_c': 14.3, 'heatindex_f': 57.7, 'dewpoint_c': 12.6, 'dewpoint_f': 54.6, 'vis_km': 10.0, 'vis_miles': 6.0, 'uv': 1.0, 'gust_mph': 7.1, 'gust_kph': 11.4}}"},
{'url': 'https://world-weather.info/forecast/usa/san_francisco/08-march/',
'content': 'Detailed ⚡ Weather Forecast for March 8 in San Francisco, California, United States - 🌡️ temperature, wind, atmospheric pressure, humidity and precipitations - World-Weather.info. Add the current city. Search. Weather; Archive ... March 06 March 07 Select date: March 09 March 10. March 08, 2024 : Atmospheric conditions and temperature ...'}]
0] search_results[
{'url': 'https://www.weatherapi.com/',
'content': "{'location': {'name': 'San Francisco', 'region': 'California', 'country': 'United States of America', 'lat': 37.78, 'lon': -122.42, 'tz_id': 'America/Los_Angeles', 'localtime_epoch': 1722692537, 'localtime': '2024-08-03 6:42'}, 'current': {'last_updated_epoch': 1722691800, 'last_updated': '2024-08-03 06:30', 'temp_c': 14.3, 'temp_f': 57.7, 'is_day': 1, 'condition': {'text': 'Patchy rain nearby', 'icon': '//cdn.weatherapi.com/weather/64x64/day/176.png', 'code': 1063}, 'wind_mph': 4.0, 'wind_kph': 6.5, 'wind_degree': 244, 'wind_dir': 'WSW', 'pressure_mb': 1015.0, 'pressure_in': 29.98, 'precip_mm': 0.01, 'precip_in': 0.0, 'humidity': 90, 'cloud': 77, 'feelslike_c': 14.2, 'feelslike_f': 57.6, 'windchill_c': 14.2, 'windchill_f': 57.6, 'heatindex_c': 14.3, 'heatindex_f': 57.7, 'dewpoint_c': 12.6, 'dewpoint_f': 54.6, 'vis_km': 10.0, 'vis_miles': 6.0, 'uv': 1.0, 'gust_mph': 7.1, 'gust_kph': 11.4}}"}
# If we want, we can create other tools.
# Once we have all the tools we want, we can put them in a list that we will reference later.
= [search]
tools tools
[TavilySearchResults(max_results=2)]
15.2 Tool Calling
from langchain_core.messages import HumanMessage
= model.invoke([HumanMessage(content="hi!")])
response response.content
'Hello! How can I assist you today?'
= model.bind_tools(tools)
model_with_tools
= model_with_tools.invoke([HumanMessage(content="Hi!")])
response
print(f"ContentString: {response.content}")
print(f"ToolCalls: {response.tool_calls}")
ContentString: Hello! How can I assist you today?
ToolCalls: []
= model_with_tools.invoke([HumanMessage(content="What's the weather in SF?")])
response
print(f"ContentString: {response.content}")
print(f"ToolCalls: {response.tool_calls}")
ContentString:
ToolCalls: [{'name': 'tavily_search_results_json', 'args': {'query': 'current weather in San Francisco'}, 'id': 'call_6RnFKXmPyWKAr12g71QLwrA8', 'type': 'tool_call'}]
This isn’t calling that tool yet - it’s just telling us to. In order to actually call it, we’ll want to create our agent.
15.3 Agent
from langgraph.prebuilt import create_react_agent
= create_react_agent(model, tools) agent_executor
= agent_executor.invoke({"messages": [HumanMessage(content="hi!")]})
response
"messages"] response[
[HumanMessage(content='hi!', id='a785d076-d96f-43e8-94cf-1394d7d217db'),
AIMessage(content='Hello! How can I assist you today?', response_metadata={'token_usage': {'completion_tokens': 10, 'prompt_tokens': 81, 'total_tokens': 91}, 'model_name': 'gpt-4o', 'system_fingerprint': 'fp_c832e4513b', 'finish_reason': 'stop', 'logprobs': None}, id='run-5dc75417-6ae0-4b1b-ad84-b6a02cfc94f6-0')]
= agent_executor.invoke(
response "messages": [HumanMessage(content="whats the weather in sf?")]}
{
)"messages"] response[
[HumanMessage(content='whats the weather in sf?', id='72b3b2ff-c21d-494f-bf3f-c6326ebd62cf'),
AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_W3LFWA6ODXpNNAKVlepGGvxg', 'function': {'arguments': '{"query":"current weather in San Francisco"}', 'name': 'tavily_search_results_json'}, 'type': 'function'}]}, response_metadata={'token_usage': {'completion_tokens': 22, 'prompt_tokens': 86, 'total_tokens': 108}, 'model_name': 'gpt-4o', 'system_fingerprint': 'fp_4e2b2da518', 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-6757ff34-bc39-4084-b984-e3f62d9aa6a2-0', tool_calls=[{'name': 'tavily_search_results_json', 'args': {'query': 'current weather in San Francisco'}, 'id': 'call_W3LFWA6ODXpNNAKVlepGGvxg', 'type': 'tool_call'}]),
ToolMessage(content='[{"url": "https://www.weatherapi.com/", "content": "{\'location\': {\'name\': \'San Francisco\', \'region\': \'California\', \'country\': \'United States of America\', \'lat\': 37.78, \'lon\': -122.42, \'tz_id\': \'America/Los_Angeles\', \'localtime_epoch\': 1722693244, \'localtime\': \'2024-08-03 6:54\'}, \'current\': {\'last_updated_epoch\': 1722692700, \'last_updated\': \'2024-08-03 06:45\', \'temp_c\': 14.3, \'temp_f\': 57.7, \'is_day\': 1, \'condition\': {\'text\': \'Patchy rain nearby\', \'icon\': \'//cdn.weatherapi.com/weather/64x64/day/176.png\', \'code\': 1063}, \'wind_mph\': 4.0, \'wind_kph\': 6.5, \'wind_degree\': 244, \'wind_dir\': \'WSW\', \'pressure_mb\': 1015.0, \'pressure_in\': 29.98, \'precip_mm\': 0.01, \'precip_in\': 0.0, \'humidity\': 90, \'cloud\': 77, \'feelslike_c\': 14.2, \'feelslike_f\': 57.6, \'windchill_c\': 14.2, \'windchill_f\': 57.6, \'heatindex_c\': 14.3, \'heatindex_f\': 57.7, \'dewpoint_c\': 12.6, \'dewpoint_f\': 54.6, \'vis_km\': 10.0, \'vis_miles\': 6.0, \'uv\': 1.0, \'gust_mph\': 7.1, \'gust_kph\': 11.4}}"}, {"url": "https://www.timeanddate.com/weather/usa/san-francisco/hourly", "content": "Hour-by-Hour Forecast for San Francisco, California, USA. Weather Today Weather Hourly 14 Day Forecast Yesterday/Past Weather Climate (Averages) Currently: 59 \\u00b0F. Passing clouds. (Weather station: San Francisco International Airport, USA). See more current weather."}]', name='tavily_search_results_json', id='846fc9a2-5e89-49be-8804-2aab2da9ce71', tool_call_id='call_W3LFWA6ODXpNNAKVlepGGvxg'),
AIMessage(content='The current weather in San Francisco is as follows:\n\n- **Temperature**: 14.3°C (57.7°F)\n- **Condition**: Patchy rain nearby\n- **Wind**: 4.0 mph (6.5 kph) from the WSW\n- **Humidity**: 90%\n- **Cloud Cover**: 77%\n- **Visibility**: 10 km (6 miles)\n- **Pressure**: 1015.0 mb\n- **UV Index**: 1 (low)\n\n![Weather Icon](//cdn.weatherapi.com/weather/64x64/day/176.png)\n\nFor more details, you can check the [WeatherAPI](https://www.weatherapi.com/) or [Time and Date](https://www.timeanddate.com/weather/usa/san-francisco/hourly).', response_metadata={'token_usage': {'completion_tokens': 173, 'prompt_tokens': 614, 'total_tokens': 787}, 'model_name': 'gpt-4o', 'system_fingerprint': 'fp_4e2b2da518', 'finish_reason': 'stop', 'logprobs': None}, id='run-7cac30fc-a299-41e2-958e-7531937a4acb-0')]
print(response["messages"][-1].content)
The current weather in San Francisco is as follows:
- **Temperature**: 14.3°C (57.7°F)
- **Condition**: Patchy rain nearby
- **Wind**: 4.0 mph (6.5 kph) from the WSW
- **Humidity**: 90%
- **Cloud Cover**: 77%
- **Visibility**: 10 km (6 miles)
- **Pressure**: 1015.0 mb
- **UV Index**: 1 (low)
![Weather Icon](//cdn.weatherapi.com/weather/64x64/day/176.png)
For more details, you can check the [WeatherAPI](https://www.weatherapi.com/) or [Time and Date](https://www.timeanddate.com/weather/usa/san-francisco/hourly).