Agent的定义:
Agents combine language models with tools to create systems that can reason about tasks, decide which tools to use, and iteratively work towards solutions.
Agent 可以将大语言模型跟工具结合起来,创建能够对任务进行推理、决定使用哪种工具并进行迭代的寻找解决方案的系统。
create_agent 提供 agent 实现的接口
核心组件
-
模型(model)
- 静态模型
-
# static model # 方式一 from langchain.agents import create_agent from langchain.tools import tool @tool def tools(): pass agent = create_agent( 'gpt-5', tools=[tool] ) # 方式二 from langchain.agents import create_agent from langchain_openai import ChatOpenAI model = ChatOpenAI( model='gpt-5', temperature=0.1, max_tokens=1000, timeout=30 ) agent1 = create_agent(model, tools=[tools])
-
- 动态模型
-
# dynamic model import os from langchain_openai import ChatOpenAI from langchain.agents import create_agent from langchain.agents.middleware import wrap_model_call, ModelRequest,ModelResponse os.environ['DEEPSEEK_API_KEY'] = 'xxxxxxxxxxx' basic_model = ChatOpenAI( model='deepseek-chat', api_key=os.getenv('DEEPSEEK_API_KEY'), base_url='https://api.deepseek.com', temperature=0.3 ) advanced_model = ChatOpenAI( model='deepseek-chat', api_key=os.getenv('DEEPSEEK_API_KEY'), base_url='https://api.deepseek.com', max_tokens=2000 ) @wrap_model_call def dynamic_model_selection(request: ModelRequest, handler) -> ModelResponse: message_count = len(request.state['messages']) if message_count > 10: model = advanced_model else: model = basic_model request.model = model return handler(request) agent = create_agent( model = basic_model, middleware=[dynamic_model_selection] )
-
- 静态模型
-
工具(tools)
- Multiple tool calls in sequence (triggered by a single prompt)
- Parallel tool calls when appropriate
- Dynamic tool selection based on previous results
- Tool retry logic and error handling
- State persistence across tool calls
- 定义工具
-
from langchain.tools import tool from langchain.agents import create_agent import os from langchain_openai import ChatOpenAI @tool def search(query: str) -> str: """Search for information.""" return f"Results for query: {query}" @tool def get_weather(location: str) -> str: """Get weather information for a location.""" return f"Weather in {location}: Sunny, 72F" os.environ['DEEPSEEK_API_KEY'] = 'xxxxxxxxx' model = ChatOpenAI( model='deepseek-chat', api_key=os.getenv('DEEPSEEK_API_KEY'), base_url='https://api.deepseek.com', temperature=0.3 ) agent = create_agent(model, tools=[search, get_weather])
-
- 工具错误处理
-
from langchain.tools import tool from langchain.agents import create_agent import os from langchain_openai import ChatOpenAI @tool def search(query: str) -> str: """Search for information.""" return f"Results for query: {query}" @tool def get_weather(location: str) -> str: """Get weather information for a location.""" return f"Weather in {location}: Sunny, 72F" os.environ['DEEPSEEK_API_KEY'] = 'xxxxxxxxx' model = ChatOpenAI( model='deepseek-chat', api_key=os.getenv('DEEPSEEK_API_KEY'), base_url='https://api.deepseek.com', temperature=0.3 ) # Tool error handing @wrap_tool_call def handle_tool_errors(request, handler): try: return handler(request) except Exception as e: return ToolMessage( content=f"Tool Error: Please check input and try again. ({str(e)})", tool_call_id=request.tool_call["id"] ) agent = create_agent( model=model, tools=[search, get_weather], middleware=[handle_tool_errors] )
-
- 使用ReAct loop 工具
-
系统提示词(System prompt)
- 设置方式
-
agent = create_agent( model=model, tools=[search, get_weather], system_prompt="You are a helpful assistant. Be concise and accurate." )
-
- 动态系统提示词
-
from typing import TypedDict from langchain.agents import create_agent from langchain.agents.middleware import dynamic_prompt, ModelRequest class Context(TypedDict): user_role: str @dynamic_prompt def user_role_prompt(request: ModelRequest) -> str: user_role = request.runtime.context.get('user_role','user') base_prompt = "You are a helpful assistant." if user_role == 'expert': return f"{base_prompt} Provide detailed technical responses." elif user_role == 'beginner': return f"{base_prompt} Explain concepts simply and avoid jargon." return base_prompt agent = create_agent( model=model, tools=[search], middleware=[user_role_prompt], context_schema=Context ) result = agent.invoke( {"message": [{ "role": "user", "content": "Explain machine learning", }]}, context={"user_role": "expert"} )
-
- 调用方式
-
result = agent.invoke( {"messages": [{"role": "user", "content": "What's the weather in San Francisco?"}]} )
-
- 设置方式
1267

被折叠的 条评论
为什么被折叠?



