Creating an Agent with LangGraph and Search Tools

In this tutorial, we will learn how to build an intelligent dialogue agent with memory capabilities using LangGraph and LangChain. This agent can use search tools to answer questions and maintain the continuity of conversations.

1. Obtain API Key for Search Tool

Log in to the search tool website: <span>https://tavily.com/</span>, generate an API key as prompted, which comes with 1000 free calls. Then, we need to set the environment variable <span>TAVILY_API_KEY</span> in the Python code to the obtained API key.

os.environ["TAVILY_API_KEY"] = "tvly-*****"

2. Install Dependencies

pip install tavily-python langchain_community 

3. Import Dependencies

First, we need to import the necessary components:

from langchain_openai import ChatOpenAI
from langchain_community.tools.tavily_search import TavilySearchResults
from langchain_core.messages import HumanMessage
from langgraph.checkpoint.memory import MemorySaver
from langgraph.prebuilt import create_react_agent

These imports include:

  • ChatOpenAI: Interface for OpenAI’s chat model
  • TavilySearchResults: Web search tool
  • HumanMessage: Class for constructing human messages
  • MemorySaver: Memory component for saving conversation history
  • create_react_agent: Function for creating a ReAct paradigm agent

4. Component Configuration

4.1 Set Up Language Model

model = ChatOpenAI(model="gpt-4o-mini")

We use OpenAI’s GPT-4 model as the brain of the agent. This model will be responsible for understanding user input and deciding how to use the tools.

4.2 Configure Memory System

memory = MemorySaver()

The MemorySaver component allows the agent to remember previous conversation content, which is crucial for maintaining coherent dialogue.

4.3 Set Up Search Tool

search = TavilySearchResults(max_results=2)
tools = [search]

We use the Tavily search tool, which can:

  • • Perform web searches
  • • Return the top two most relevant results
  • • Help the agent obtain the latest information

5. Create Intelligent Agent

agent_executor = create_react_agent(model, tools, checkpointer=memory)

The create_react_agent function combines all components into a complete agent system:

  1. 1. Use the specified language model as the decision core
  2. 2. Integrate search tools for the agent to use
  3. 3. Add a memory system to save conversation history

6. Interactive Dialogue Implementation

config = {"configurable": {"thread_id": "abc123"}}

while True:
    query = input("Please enter your question:")
    for chunk in agent_executor.stream(
        {"messages": [HumanMessage(content=query)]}, config
    ):
        print(chunk)
        print("----")
    print('\n')

This code implements:

  1. 1. Creating a continuous dialogue loop
  2. 2. Receiving user input questions
  3. 3. Displaying the agent’s thought and response process through streaming output
  4. 4. Tracking conversation context through thread_id

7. Usage Instructions

When using this intelligent agent system:

  1. 1. The agent will display its thought process in real-time
  2. 2. You can ask any question, and the agent will use the search tool as needed
  3. 3. The agent will remember previous conversation content, allowing for continuous dialogue
  4. 4. To exit the conversation, you can use Ctrl+C to terminate the program

8. Example

Please enter your question: How is the weather in Shanghai tomorrow?
{'agent': {'messages': [AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'call_Wq2uNmcLynn6MSURC8yXJuiY', 'function': {'arguments': '{"query":"How is the weather in Shanghai tomorrow?"}', 'name': 'tavily_search_results_json'}, 'type': 'function'}], 'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 23, 'prompt_tokens': 86, 'total_tokens': 109, 'completion_tokens_details': None, 'prompt_tokens_details': None}, 'model_name': 'gpt-4o-mini', 'system_fingerprint': 'fp_04751d0b65', 'finish_reason': 'tool_calls', 'logprobs': None}, id='run-65d3026c-7047-4679-b868-89a9f6dde55a-0', tool_calls=[{'name': 'tavily_search_results_json', 'args': {'query': 'How is the weather in Shanghai tomorrow?'}, 'id': 'call_Wq2uNmcLynn6MSURC8yXJuiY', 'type': 'tool_call'}], usage_metadata={'input_tokens': 86, 'output_tokens': 23, 'total_tokens': 109, 'input_token_details': {}, 'output_token_details': {}})]}}
----
{'tools': {'messages': [ToolMessage(content='[{"url": "https://www.weather-atlas.com/zh/china/shanghai-weather-tomorrow", "content": " Tomorrow's weather - Shanghai, China Weather Atlas Search country or city Country (multiple) Units °C °F Language English Español 中文 Contact About Us Glossary Terms of Use Privacy Policy Cookie Policy Disclaimer Country (multiple) China Shanghai Tomorrow Tomorrow's weather forecast Shanghai, China Today Tomorrow Long-term History January February March April May June July August September October November December °C °F Share more Email Viber WhatsApp Expand Directory Tomorrow's weather forecast Hourly weather forecast Weather forecast for your location Tomorrow's weather forecast and temperature - Wednesday, November 20 CST Mostly cloudy 16°C / 9°C Wind: 14 km/h 352° Humidity: 59% Precipitation probability: 4% Precipitation: 0 mm UV index: 3 Hourly weather forecast - Shanghai, China 0 hours 12°C Feels like: 11°C Partly cloudy Wind: 10 km/h 347° Pressure: 1027 hPa Humidity: 73% Precipitation probability: 4% 12°C 11°C 11°C 10°C 11°C 10°C 13°C 12°C 15°C 14°C 16°C 15°C 15°C 15°C 15°C 15°C 14°C 14°C 13°C 13°C 12°C 13°C 12°C Published by: Weather Atlas | About Us Data source | weather.com | Weather Shanghai, China Tomorrow's weather forecast © 2002-2024|Contact|About Us  "}, {"url": "https://www.weather.com.cn/shanghai/weather.shtml", "content": "Shanghai weather forecast, Shanghai weather forecast also provides living index, health index, traffic index, tourism index for each district and county in Shanghai, timely release of weather warning signals and various weather information. ... Today's maximum temperature is 20 degrees, and tomorrow's minimum temperature is 15 degrees. Fire risk level meteorological index: level 4, flammable. Office hours (6-9): Sunny to cloudy, 11-15 degrees; Off work (16'}]', name='tavily_search_results_json', id='494dc3bb-0fd0-4367-8e81-034e87848c45', tool_call_id='call_Wq2uNmcLynn6MSURC8yXJuiY', artifact={'query': 'How is the weather in Shanghai tomorrow?', 'follow_up_questions': None, 'answer': None, 'images': [], 'results': [{'title': 'Tomorrow's Weather - Shanghai, China - Weather Atlas', 'url': 'https://www.weather-atlas.com/zh/china/shanghai-weather-tomorrow', 'content': 'Tomorrow's weather - Shanghai, China Weather Atlas Search country or city Country (multiple) Units °C °F Language English Español 中文 Contact About Us Glossary Terms of Use Privacy Policy Cookie Policy Disclaimer Country (multiple) China Shanghai Tomorrow Tomorrow's weather forecast Shanghai, China Today Tomorrow Long-term History January February March April May June July August September October November December °C °F Share more Email Viber WhatsApp Expand Directory Tomorrow's weather forecast Hourly weather forecast Weather forecast for your location Tomorrow's weather forecast and temperature - Wednesday, November 20 CST Mostly cloudy 16°C / 9°C Wind: 14 km/h 352° Humidity: 59% Precipitation probability: 4% Precipitation: 0 mm UV index: 3 Hourly weather forecast - Shanghai, China 0 hours 12°C Feels like: 11°C Partly cloudy Wind: 10 km/h 347° Pressure: 1027 hPa Humidity: 73% Precipitation probability: 4% 12°C 11°C 11°C 10°C 11°C 10°C 13°C 12°C 15°C 14°C 16°C 15°C 15°C 15°C 15°C 15°C 14°C 14°C 13°C 13°C 12°C 13°C 12°C Published by: Weather Atlas | About Us Data source | weather.com | Weather Shanghai, China Tomorrow's weather forecast © 2002-2024|Contact|About Us', 'score': 0.9973888, 'raw_content': None}, {'title': 'Shanghai Homepage - Shanghai - China Weather Network', 'url': 'https://www.weather.com.cn/shanghai/weather.shtml', 'content': 'Shanghai weather forecast, Shanghai weather forecast also provides living index, health index, traffic index, tourism index for each district and county in Shanghai, timely release of weather warning signals and various weather information. ... Today's maximum temperature is 20 degrees, and tomorrow's minimum temperature is 15 degrees. Fire risk level meteorological index: level 4, flammable. Office hours (6-9): Sunny to cloudy, 11-15 degrees; Off work (16', 'score': 0.99589807, 'raw_content': None}], 'response_time': 2.85})]}}
----
{'agent': {'messages': [AIMessage(content=' Tomorrow (November 20) Shanghai's weather forecast shows:

- **Weather Condition**: Mostly cloudy
- **Temperature**: High of 16°C, low of 9°C
- **Wind Speed**: 14 km/h
- **Humidity**: 59%
- **Precipitation Probability**: 4%
- **Precipitation**: 0 mm

Overall, tomorrow's weather is suitable for travel, and you can check more detailed information [here](https://www.weather-atlas.com/zh/china/shanghai-weather-tomorrow).', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 124, 'prompt_tokens': 727, 'total_tokens': 851, 'completion_tokens_details': None, 'prompt_tokens_details': None}, 'model_name': 'gpt-4o-mini', 'system_fingerprint': 'fp_04751d0b65', 'finish_reason': 'stop', 'logprobs': None}, id='run-a4ac2976-a80b-4b4c-8844-d249f94ce1d3-0', usage_metadata={'input_tokens': 727, 'output_tokens': 124, 'total_tokens': 851, 'input_token_details': {}, 'output_token_details': {}})]}}

9. Summary

Through this tutorial, we learned how to:

  1. 1. Build an intelligent agent using LangGraph
  2. 2. Integrate a large language model as the decision core
  3. 3. Add practical tools to extend agent capabilities
  4. 4. Implement memory functionality to maintain conversation continuity

This system lays the foundation for building more complex intelligent agents. You can enhance the system’s functionality by adding more tools or customizing the agent’s behavior.

10. Complete Code

from langchain_openai import ChatOpenAI
from langchain_community.tools.tavily_search import TavilySearchResults
from langchain_core.messages import HumanMessage
from langgraph.checkpoint.memory import MemorySaver
from langgraph.prebuilt import create_react_agent

# Define model
model = ChatOpenAI(model="gpt-4o-mini")

# Define memory storage
memory = MemorySaver()

# Define search tool
search = TavilySearchResults(max_results=2)
tools = [search]

# Create agent (using model, tools, memory storage)
agent_executor = create_react_agent(model, tools, checkpointer=memory)

# Use agent for chatting
config = {"configurable": {"thread_id": "abc123"}}

while True:
    query = input("Please enter your question:")
    for chunk in agent_executor.stream(
        {"messages": [HumanMessage(content=query)]}, config
    ):
        print(chunk)
        print("----")
    print('\n')

Recommended Reading

  • FastAPI Beginner Series Collection

  • Django Beginner Series Collection

  • Flask Tutorial Series Collection

  • tkinter Tutorial Series Collection

  • Flet Tutorial Series Collection

Please open in WeChat client

Leave a Comment