iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
😎

[LangGraph] A 60-Line Script to Build an Autonomous LLM Agent

に公開

Second installment in the 60-line script series. Check out the previous one here.
This article is aimed at people interested in the multi-agent creation framework "LangGraph" who want to get it up and running quickly.

What you can do with this article

  • Execute tools defined by functions (e.g., web search) for a given topic.
  • Return an answer based on execution results. Repeat tool execution until the answer is found.

I have designed this without using built-in workflows, keeping future extensibility in mind.

First, Setup

poetry init
poetry add langgraph@0.0.39 langchain-openai@0.1.1 langchain@0.1.14
  • Note: Since we are using Tavily, please obtain a TAVILY_API_KEY.

Program and Explanation

# Import necessary libraries
import argparse
from langchain_community.tools.tavily_search import TavilySearchResults
from langchain_openai import ChatOpenAI
from langgraph.checkpoint.sqlite import SqliteSaver
from langgraph.graph import END, MessageGraph
from langgraph.prebuilt.tool_node import ToolNode

# Conditional edge
def should_continue(messages):
    last_message = messages[-1]
    if last_message.tool_calls:
        return "action"
    return END


# Define tools and models to use
# Using the Tavily search tool provided by LangChain
tools = [TavilySearchResults(max_results=1)]
model = ChatOpenAI(model="gpt-3.5-turbo")


# Define the workflow
# Not necessary if using app = create_tool_calling_executor(model, tools)
workflow = MessageGraph()
workflow.add_node("agent", model.bind_tools(tools))
workflow.add_node("action", ToolNode(tools))
workflow.add_edge("action", "agent")
workflow.add_conditional_edges("agent", should_continue)
workflow.set_entry_point("agent")
memory = SqliteSaver.from_conn_string(":memory:")
app = workflow.compile(checkpointer=memory)


# Define CLI arguments
parser = argparse.ArgumentParser(description="Run a language graph")
parser.add_argument("question", type=str, help="The question to ask the graph", nargs="?")
args = parser.parse_args()


# Execution
question = args.question
thread = {"configurable": {"thread_id": "4"}}
for step in app.stream(question, thread):  # type: ignore
    node, message = next(iter(step.items()))
    if message:
        if isinstance(message, list) and isinstance(message[-1], BaseMessage):
            message[-1].pretty_print()
        elif isinstance(message, BaseMessage):
            message.pretty_print()
            if isinstance(message, AIMessage) and len(message.tool_calls) > 0:
                print(message.tool_calls)

Execution Results

$ export OPENAI_API_KEY=sk-xxxxxx
$ export TAVILY_API_KEY=tvly-xxxx
$ python langgraph_base.py "What was the weather in Tokyo on 2024/01/01?"
================================== Ai Message ==================================


[{'name': 'tavily_search_results_json', 'args': {'query': '2024/01/01 Tokyo weather'}, 'id': 'call_CnpHrC6hvoWAY2nx0bRhkIJd'}]
================================= Tool Message =================================
Name: tavily_search_results_json

[{"url": "https://www.weatherapi.com/", "content": "{'location': {'name': 'Tokyo', 'region': 'Tokyo', 'country': 'Japan', 'lat': 35.69, 'lon': 139.69, 'tz_id': 'Asia/Tokyo', 'localtime_epoch': 1714273330, 'localtime': '2024-04-28 12:02'}, 'current': {'last_updated_epoch': 1714273200, 'last_updated': '2024-04-28 12:00', 'temp_c': 23.0, 'temp_f': 73.4, 'is_day': 1, 'condition': {'text': 'Sunny', 'icon': '//cdn.weatherapi.com/weather/64x64/day/113.png', 'code': 1000}, 'wind_mph': 8.1, 'wind_kph': 13.0, 'wind_degree': 150, 'wind_dir': 'SSE', 'pressure_mb': 1014.0, 'pressure_in': 29.94, 'precip_mm': 0.0, 'precip_in': 0.0, 'humidity': 69, 'cloud': 0, 'feelslike_c': 24.7, 'feelslike_f': 76.4, 'vis_km': 10.0, 'vis_miles': 6.0, 'uv': 6.0, 'gust_mph': 12.5, 'gust_kph': 20.2}}"}]
================================== Ai Message ==================================

The weather in Tokyo on January 1, 2024, was sunny. The temperature was 23 degrees, and the wind speed was 8.1 mph. The UV index was 6.0, and the humidity was 69%. For more details, please see [here](https://www.weatherapi.com/).

Adding Your Own Tools

By simply adding the @tool decorator to a function, it can be used as a tool.
Invoking an agent within a tool allows you to achieve a multi-agent setup.
This is useful for calling LLMs specialized for specific tasks or combining high-cost models (like Vision) with lower-cost ones.

from langchain_core.tools import tool

@tool
def exponentiate(x: float, y: float) -> float:
    """Raise 'x' to the 'y'."""
    return x**y

...

tools = [TavilySearchResults(max_results=1), exponentiate]
$ python langgraph_base.py "What is 2 to the power of 3?"
================================== Ai Message ==================================


[{'name': 'exponentiate', 'args': {'x': 2, 'y': 3}, 'id': 'call_1CMEwIueMxvMDd2jn0rvezy5'}]
================================= Tool Message =================================
Name: exponentiate

8.0
================================== Ai Message ==================================

2 to the power of 3 is 8.

References

Full version of the source code created for this article:
https://github.com/HikaruEgashira/python-workspaces/blob/main/langchain/langgraph_base.py

Claude also supports tool calling, but I used OpenAI here because I couldn't get it to work using the method described in the documentation.

Discussion