但在我们深入技术之前,我们能等一下吗?这是来自《黑客帝国》的 Agent Smith 。记得他们是矩阵创造的一段代码,用来保持系统中的“秩序”,这个系统让人类处于模拟中。(_即使系统崩溃了,向Neo致敬_)。Smiths处于一个等级体系中;有“Smith”命令其他Smith去做事情。(_他后来可以在模拟中复制自己的存在。实际上,这是一种处理有许多请求的系统的非常酷的方式,也许是LangChain的下一个动作;_)
经过我的玩笑时间,LangGraph是一个非常酷的库;在LangChain无法处理的情况下,它非常有用。它提供了解决复杂问题、用例或流程的方案,当需要时,一个代理系统并不够好。正如我之前所说,我将讨论 Multi-Agent Systems ,主要是 Supervisor 的实现,因为有不同的方法可以组合这些代理。由于我们正在尝试实现一个聊天机器人,我们从 Customer Support Bot 教程中获得了很多帮助。它清晰地展示了你可以在聊天中做什么,以及如何控制你的代理去做正确的事情。
from langchain_openai import ChatOpenAI from typing import Annotated, List, Tuple, Union from langchain.tools import BaseTool, StructuredTool, Tool from langchain_experimental.tools import PythonREPLTool from langchain_core.tools import tool import random
llm = ChatOpenAI(model="gpt-3.5-turbo")
python_repl_tool = PythonREPLTool()
@tool("random_number", return_direct=False) def random_number(input:str) -> str: """Returns a random number between 0-100. input the word 'random'""" return random.randint(0, 100)
from langchain.agents import AgentExecutor, create_openai_tools_agent from langchain_core.messages import BaseMessage, HumanMessage from langchain_openai import ChatOpenAI
from langchain.output_parsers.openai_functions import JsonOutputFunctionsParser from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
members = ["Random_Number_Generator", "Coder"] system_prompt = ( "You are a supervisor tasked with managing a conversation between the" " following workers: {members}. Given the following user request," " respond with the worker to act next. Each worker will perform a" " task and respond with their results and status. When finished," " respond with FINISH." )
options = ["FINISH"] + members
function_def = { "name": "route", "description": "Select the next role.", "parameters": { "title": "routeSchema", "type": "object", "properties": { "next": { "title": "Next", "anyOf": [ {"enum": options}, ], } }, "required": ["next"], }, } prompt = ChatPromptTemplate.from_messages( [ ("system", system_prompt), MessagesPlaceholder(variable_name="messages"), ( "system", "Given the conversation above, who should act next?" " Or should we FINISH? Select one of: {options}", ), ] ).partial(options=str(options), members=", ".join(members))
for s in graph.stream( { "messages": [ HumanMessage(content="Get 10 random numbers and generate a histogram") ] }, config={"recursion_limit": 20} ): if "__end__" not in s: print(s) print("----")