[langgraph]创建第一个agent
我一直想看看agent到底是怎么建起来的。
我一直想看看agent到底是怎么建起来的。
agent的好处:
1、工具的自动调用
之前的流程是,调用大模型,判断响应是否有工具调用,调用工具,把工具的结果再传递给大模型,获取响应。
使用agent框架,这些步骤可以为你封装,简化了操作。就好比我们在tcp之上构建http,我们在htt之上进行接口调用。
2、允许human in the loop,approval(一种方法是写在工具里面,但是这种方法耦合度太高)
langchain和langgraph还是有缺点的,缺点之一就是api变来变去,不同版本不太兼容。
还有就是一些包你需要单独安装
langchain ->langgraph
pip install -U langgraph “langchain[anthropic]”
Then, create an agent using prebuilt components:
# pip install -qU "langchain[anthropic]" to call the model
from langgraph.prebuilt import create_react_agent
def get_weather(city: str) -> str:
"""Get weather for a given city."""
return f"It's always sunny in {city}!"
agent = create_react_agent(
model="anthropic:claude-3-7-sonnet-latest",
tools=[get_weather],
prompt="You are a helpful assistant"
)
# Run the agent
agent.invoke(
{"messages": [{"role": "user", "content": "what is the weather in sf"}]}
)
什么是fallbacks?不是failback,不是callback
fallback是备用策略,兜底策略
model_with_fallbacks = (
init_chat_model(“anthropic:claude-3-5-haiku-latest”)
.with_fallbacks([
init_chat_model(“deepseek-chat”),
])
)
5. Add memory
因为llm本身没有memory,使用过传递提示词,让llm 有类似记忆的表现。在langgraph里面可以用使用config包含thread_id来表示对话的会话
from langgraph.prebuilt import create_react_agent
from dotenv import load_dotenv
load_dotenv()
from langchain.chat_models import init_chat_model
from pydantic import BaseModel
from langgraph.checkpoint.memory import InMemorySaver
class WeatherResponse(BaseModel):
conditions: str
model = (
init_chat_model("deepseek-chat")
)
checkpointer = InMemorySaver()
def get_weather(city: str) -> str:
"""Get weather for a given city."""
return f"It's always sunny in {city}!"
agent = create_react_agent(
model=model,
tools=[get_weather],
checkpointer=checkpointer,
response_format=WeatherResponse
)
# Run the agent
config = {"configurable": {"thread_id": "1"}}
sf_response = agent.invoke(
{"messages": [{"role": "user", "content": "what is the weather in sf"}]},
config
)
ny_response = agent.invoke(
{"messages": [{"role": "user", "content": "what about new york?"}]},
config
)
print(ny_response['structured_response'])
langchain vs langgraph
https://www.youtube.com/watch?v=qAF1NjEVHhY&t=197s
非常清晰的介绍

为武汉地区的开发者提供学习、交流和合作的平台。社区聚集了众多技术爱好者和专业人士,涵盖了多个领域,包括人工智能、大数据、云计算、区块链等。社区定期举办技术分享、培训和活动,为开发者提供更多的学习和交流机会。
更多推荐
所有评论(0)