from langchain_openai import ChatOpenAI from langchain.agents import create_agent from langchain.agents.middleware import wrap_model_call, ModelRequest, ModelResponse from langchain.tools import tool
@tool defget_weather_for_location(city: str) -> str: """Get weather for a given city.""" returnf"It's always sunny in {city}!"
@wrap_model_call defdynamic_model_selection(request: ModelRequest, handler) -> ModelResponse: """Choose model based on conversation complexity.""" message_count = len(request.state["messages"])
if message_count > 10 : # 对话较长(超过 10 条消息),使用高级模型处理 model = advanced_model else : # 对话较短,使用基础模型即可 model = basic_model
request.model = model # 更新请求中的模型 return handler(request) # 继续执行模型调用
import os from langchain.agents.middleware import wrap_tool_call from langchain.messages import ToolMessage from langchain.tools import tool from langchain.agents import create_agent from langchain_openai import ChatOpenAI @wrap_tool_call defhandle_tool_errors(request, handler): """Handle tool execution errors with custom messages.""" try: return handler(request) except Exception as e: # Return a custom error message to the model return ToolMessage( content=f"Tool error: Please check your input and try again. ({str(e)})", tool_call_id=request.tool_call["id"] )
================================ Human Message ================================= Find the most popular wireless headphones right now and check if they're in stock
================================= Tool Message ================================= Product WH-1000XM5: 10 units in stock
推理: “我拥有最受欢迎的型号及其库存状态。现在我能够回答用户的问题。”
行动:生成最终答案
1 2
================================== Ai Message ================================== I found wireless headphones (model WH-1000XM5) with 10 units in stock...
import os from typing import TypedDict from langchain_openai import ChatOpenAI from langchain.agents import create_agent from langchain.agents.middleware import dynamic_prompt, ModelRequest from langchain.tools import tool
classContext(TypedDict): user_role: str
model = ChatOpenAI( api_key=os.getenv('DEEPSEEK_API_KEY'), base_url="https://api.deepseek.com/v1", model="deepseek-chat", temperature=0.1, max_tokens=100 )
@dynamic_prompt defuser_role_prompt(request: ModelRequest) -> str: """Generate system prompt based on user role.""" user_role = request.runtime.context.get("user_role", "user") base_prompt = "You are a helpful assistant."
if user_role == "expert": returnf"{base_prompt} Provide detailed technical responses." elif user_role == "beginner": returnf"{base_prompt} Explain concepts simply and avoid jargon."
# The system prompt will be set dynamically based on context result = agent.invoke( {"messages": [{"role": "user", "content": "Explain machine learning"}]}, context={"user_role": "expert"} )
import os from pydantic import BaseModel from langchain.agents import create_agent from langchain.agents.structured_output import ToolStrategy from langchain_openai import ChatOpenAI
class ContactInfo(BaseModel): name: str email: str phone: str
# Create DeepSeek model with proper configuration model = ChatOpenAI( api_key=os.getenv('DEEPSEEK_API_KEY'), base_url="https://api.deepseek.com/v1", model="deepseek-chat", temperature=0.1, max_tokens=1000 # Increased for structured output )
# Create agent with ToolStrategy for structured output agent = create_agent( model=model, tools=[], # No tools needed for extraction response_format=ToolStrategy(ContactInfo) )
# Invoke the agent result = agent.invoke({ "messages": [ { "role": "user", "content": "Extract contact info from: John Doe, john@example.com, (555) 123-4567" } ] })
import os from typing importAny from langchain_openai import ChatOpenAI from langchain.agents import create_agent from langchain.agents.middleware import AgentState, AgentMiddleware from typing_extensions import NotRequired
Test 1: Technical user with detailed preferences ✓ User Preferences Applied: style=technical, verbosity=detailed Call #1 ✓ User Preferences Applied: style=technical, verbosity=detailed Call #2
✓ Final Response: Now, about machine learning:
**Machine Learning** is a subset of artificial intelligence that focuses on developing algorithms and statistical models that enable computers to perform tasks without being explicitly programmed for every scenario. Instead, these systems learn from data and improve their performance over time.
Key aspects of machine learning include:
- **Learning from data**: ML algorithms analyze patterns in data to make predictions or decisions - **Adaptive improvement**: The models get better as they're exposed to more data - **Automated pattern recognition**: They can identify complex patterns that might be difficult for humans to detect
Common types of machine learning: - **Supervised learning**: Training with labeled data (like classification and regression) - **Unsupervised learning**: Finding patterns in unlabeled data (like clustering) - **Reinforcement learning**: Learning through trial and error with rewards/punishments
Machine learning is used in many applications today, including recommendation systems, image recognition, natural language processing, fraud detection, and autonomous vehicles.
And regarding the weather in Beijing - it's currently sunny and 22°C, which sounds like pleasant weather!
Test 2: Simple user with brief preferences ✓ User Preferences Applied: style=simple, verbosity=brief Call #1 ✓ User Preferences Applied: style=simple, verbosity=brief Call #2
✓ Final Response: 2 + 2 = 4
Test 3: Default user (no preferences) ✓ User Preferences Applied: style=default, verbosity=normal Call #1 ✓ User Preferences Applied: style=default, verbosity=normal Call #2
✓ Final Response: 10 * 5 equals 50.
Defining state via state_schema 通过 state_schema 定义状态
✓ Success! Response: I understand you prefer technical explanations. However, I'm currently limited in my ability to provide detailed technical information as the available tools are quite basic. The only function I have access to right now is a simple information retrieval tool that doesn't require any parameters.
If you have specific technical questions or topics you'd like me to explain, I'd be happy to provide technical explanations based on my general knowledge. Just let me know what particular subject or concept you're interested in, and I'll do my best to give you a thorough technical breakdown.
What technical area would you like to explore? User Preferences: {'style': 'technical', 'verbosity': 'detailed'}
for chunk in agent.stream({ "messages": [{"role": "user", "content": "Search for AI news and summarize the findings"}] }, stream_mode="values"): # Each chunk contains the full state at that point latest_message = chunk["messages"][-1] if latest_message.content: print(f"Agent: {latest_message.content}") elif latest_message.tool_calls: print(f"Calling tools: {[tc['name'] for tc in latest_message.tool_calls]}")