我一直想看看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
非常清晰的介绍

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐