YouTip LogoYouTip

Langchain First Agent

Title: First LangChain Agent | Online Tutorial Agent is the core concept in LangChain. It enables AI to automatically determine when to call tools and continue thinking after obtaining tool results until the task is completed. * * * ## What is Agent A regular model call is a simple Q&A: You send a message, the model replies, and it's done. Agent is different - it enters a think-act-observe loop: The model determines it needs to call a certain tool β†’ Executes the tool and gets the result β†’ The model continues thinking based on the result β†’ May call the tool again β†’ Until the final answer is obtained. For example, if you ask "What's the weather like in Hangzhou today?", a regular model can only answer based on training data (which might be months old). However, Agent will actively call a weather query tool to get real-time data, then answer you based on the actual data. * * * ## Creating Your First Agent The entire process requires only three steps: (1) Define tools; (2) Create Agent; (3) Run. ### Step 1: Define Tool Functions Use the @tool decorator to turn a regular Python function into a tool that Agent can call: ## Example # File path: 04_first_agent.py from dotenv import load_dotenv load_dotenv() from langchain.tools import tool # Step 1: Define a tool using @tool decorator # The function's docstring is the tool's description # The model will use the description to determine when to call this tool @tool def get_weather(city: str) ->str: """Query the weather for a specified city. Args: city: City name, e.g., "Hangzhou", "Beijing" """ # Using mock data here for demonstration # In actual projects, replace with real weather API calls weather_data ={ "Hangzhou": "Sunny, 25Β°C, humidity 60%", "Beijing": "Cloudy, 18Β°C, humidity 45%", "Shanghai": "Light rain, 22Β°C, humidity 80%", } return weather_data.get(city, f"Weather data for {city} not found") @tool def calculate(expression: str) ->str: """Perform mathematical calculations. Supports basic operations like addition, subtraction, multiplication, and division. Args: expression: Mathematical expression, e.g., "3 * 7 + 2" """ try: # Safely evaluate mathematical expression result =eval(expression,{"__builtins__": {}},{}) return f"Calculation result: {expression} = {result}" except Exception as e: return f"Calculation error: {e}" > The docstring (the """...""" part of the function) is very important. The model reads the tool's description to decide whether to call this tool and what parameters to pass. The clearer the description, the less likely the model will use it incorrectly. ### Step 2: Create Agent ## Example # Step 2: Create Agent from langchain.agents import create_agent from langchain.chat_models import init_chat_model # Initialize the model model = init_chat_model("openai:gpt-4o-mini") # Create Agent, passing in the model and tool list agent = create_agent( model=model, tools=[get_weather, calculate], system_prompt="You are a helpful assistant who uses tools to answer questions.", ) | Parameter | Description | Required | | --- | --- | --- | | model | The language model to use | Yes | | tools | List of tools that the Agent can call | No (if not passed, Agent cannot call tools) | | system_prompt | System prompt that defines the Agent's role and behavior | No | ### Step 3: Run Agent ## Example # Step 3: Run Agent # Build the input message # The first message in the message list is usually HumanMessage (user message) from langchain.messages import HumanMessage inputs ={"messages": [HumanMessage(content="How's the weather in Hangzhou today?")]} # invoke() runs the Agent and returns the final state result = agent.invoke(inputs) # View message history (including AI's tool calls and tool return results) print("=== Full Message History ===") for msg in result: print(f"[{msg.type}] {msg.content[:100]}")# Truncate to first 100 characters print("\n=== Final Response ===") # The last AI message is the final answer print(result.content) Running result: === Full Message History === How's the weather in Hangzhou today? Sunny, 25Β°C, humidity 60% Today's weather in Hangzhou is sunny, with a temperature of 25Β°C and humidity of 60%. Perfect for going out!=== Final Response ===Today's weather in Hangzhou is sunny, with a temperature of 25Β°C and humidity of 60%. Perfect for going out! * * * ## Agent Execution Flow Analysis The complete execution process of this example is as follows: 1. User sends message: "How's the weather in Hangzhou today?" 2. After receiving the message, the model determines: need to query weather β†’ returns a tool_call (calling get_weather, parameter city="Hangzhou") 3. Agent executes get_weather tool β†’ returns "Sunny, 25Β°C, humidity 60%" 4. Model receives tool result β†’ determines task is complete β†’ generates final response This is the think-act-observe loop of Agent. !(https://example.com/wp-content/uploads/2026/05/6fde20ee-22ee-4ddf-9824-0d4c667f2e99.png) * * * ## Let Agent Call Multiple Tools The real power of Agent lies in its ability to automatically combine multiple tools: ## Example # Ask a complex question that requires querying weather and calculating simultaneously inputs ={"messages": [HumanMessage( content="What's the temperature difference between Hangzhou and Beijing today?" )]} result = agent.invoke(inputs) print("=== Full Message History ===") for msg in result: if msg.type=="tool": print(f"[tool {msg.name}] {msg.content}") else: print(f"[{msg.type}] {msg.content[:120]}") print("\n=== Final Response ===") print(result.content) Running result: === Full Message History === What's the temperature difference between Hangzhou and Beijing today? Sunny, 25Β°C, humidity 60% Cloudy, 18Β°C, humidity 45% Calculation result: 25 - 18 = 7 The temperature difference between Hangzhou and Beijing today is 7Β°C.=== Final Response ===The temperature difference between Hangzhou and Beijing today is 7Β°C. Agent automatically executed three steps: (1) Query Hangzhou weather; (2) Query Beijing weather; (3) Calculate temperature difference. You don't need to write any logic to control these steps - Agent automatically completes the planning and execution. > Note: Agent sent two tool calls in the first model call (get_weather("Hangzhou") and get_weather("Beijing")), and they were executed in parallel. The model automatically determines which tool calls can be parallelized. * * * ## Complete Code ## Example # File path: 04_first_agent.py (Complete version) from dotenv import load_dotenv load_dotenv() from langchain.tools import tool from langchain.agents import create_agent from langchain.chat_models import init_chat_model from langchain.messages import HumanMessage # Define tools @tool def get_weather(city: str) ->str: """Query the weather for a specified city. Args: city: City name, e.g., "Hangzhou", "Beijing" """ weather_data ={ "Hangzhou": "Sunny, 25Β°C, humidity 60%", "Beijing": "Cloudy, 18Β°C, humidity 45%", "Shanghai": "Light rain, 22Β°C, humidity 80%", } return weather_data.get(city, f"Weather data for {city} not found") @tool def calculate(expression: str) ->str: """Perform mathematical calculations. Supports basic operations like addition, subtraction, multiplication, and division. Args: expression: Mathematical expression, e.g., "3 * 7 + 2" """ try: result =eval(expression,{"__builtins__":
← Langchain Model ParamsLangchain Env Setup β†’