理解API代码:高效REST API集成的综合指南
一文探秘LLM应用开发(26)-Prompt(架构模式之Agent框架AutoGPT、AutoGen等)
第二部分 应用挑战
2.基本流程与相关技术
4)Prompt
在前面的内容里,我们提到过要使用模型完成下游任务,有两种方式,一种是通过收集标记样本针对不同的任务进行指令微调,另一种方式便是大模型特有的,可以通过将指令以对话的方式提供给模型,期待模型能够给我们返回预期的结果。相较于前者,后者具有更高的灵活性,使用成本也更低,因此,这一方式成了如今大语言模型区别于传统NLP模型的重要标志。在本章你将学习到:
1)Prompt,In-Context-Learning,Prompt engineering等相关概念
2)如何写好一个Prompt及相关Prompt调试工具
3)基于Prompt催生的一些新的编程范式
Agent框架
在了解了Agent的基本概念,原理之后,我们这一节介绍一些有关Agent的知名框架和项目,通过这些项目可以快速构建自己的Agent应用。
编排框架类-(Langchain/llamaindex/Semantic Kernel)
如前面介绍,Agent本质上是一种使用LLM替代人工制定目标任务处理执行流程的应用形态,因此,从RAG应用衍生出来的编排框架,如Langchain,llamaindex,Semantic Kernel都随着应用复杂度的不断提高,有了对agent以及mutiAgent应用的支持。下面以langchain为例重点介绍一下编排框架类的agent应用的相关细节,其他框架更多使用介绍见下一章编排与集成。
在langchain中,agent 应用构建涉及到几个核心概念:
1)Agent
其核心作用是与大模型交互,提供大模型当前可以使用的工具,用户的输入,以及历史过程中的执行动作及相关工具的输出。大模型基于这些输入,进而获得下一步行动或发送给用户的最终响应(AgentActions 或 AgentFinish)。这里的行动可以是指定一个工具和该工具的输入。
try:
# Call the LLM to see what to do.
output = self.agent.plan(
intermediate_steps,
callbacks=run_manager.get_child() if run_manager else None,
**inputs,
)
except Exception as e:
if not self.handle_parsing_errors:
raise e
text = str(e).split("`")[1]
observation = "Invalid or incomplete response"
output = AgentAction("_Exception", observation, text)
tool_run_kwargs = self.agent.tool_run_logging_kwargs()
observation = ExceptionTool().run(
output.tool,
verbose=self.verbose,
color=None,
callbacks=run_manager.get_child() if run_manager else None,
**tool_run_kwargs,
)
return [(output, observation)]
不难想到,要和大模型进行沟通,自然需要Prompt,langchain默认内置了若干agent类型(agent type),如:Zero-shot ReAct,Structured input ReAct,OpenAI Functions,Self-ask with search等,也可以自定义agent。
2)Tools
作为LLM能力的扩展,需要提供可被Agent调起的工具(可以理解为一个函数调用)。这里的工具必须满足两个条件:提供解决该任务合适的工具及一个有效的工具描述,让大模型知道这个工具到底有啥功能,什么时候可以使用它。langchain默认提供了大量的内置工具,包含搜索,查库,计算等,详见:https://python.langchain.com/docs/integrations/tools/。
return Tool(
name="Calculator",
description="Useful for when you need to answer questions about math.",
func=LLMMathChain.from_llm(llm=llm).run,
coroutine=LLMMathChain.from_llm(llm=llm).arun,
)
3)Toolkits
langchain将一组相关的工具合并在一个toolkits中方便管理,比如对于一个网站的增删改查。同样,langchain提供了大量的toolkits的预置集合。在使用方法上没有太多区别,都会打平成Tools提交给LLM。
tools = []
unwanted_tools = ["Get Issue", "Delete File", "Create File", "Create Pull Request"]
for tool in toolkit.get_tools():
if tool.name not in unwanted_tools:
tools.append(tool)
tools += [
Tool(
name="Search",
func=DuckDuckGoSearchRun().run,
description="useful for when you need to search the web",
)
]
4)AgentExecutor
Agent执行的运行环境,通过它来串联agent的工作流程,可以认为是一个无限循环,并保证在执行过程中可能出现的一些错误及执行兜底策略。下面是langchain默认的最常见泛化运行时的实现示例:
next_action = agent.get_action(...)
while next_action != AgentFinish:
observation = run(next_action)
next_action = agent.get_action(..., next_action, observation)
return next_action
除此之外,langchain还提供了一些特定模式的Agent执行环境,比如Plan-and-execute Agent,AutoGPT等,其中Plan-and-execute 的使用方法如下:
from langchain.agents.tools import Tool
from langchain.chains import LLMMathChain
from langchain.chat_models import ChatOpenAI
from langchain.llms import OpenAI
from langchain.utilities import DuckDuckGoSearchAPIWrapper
from langchain_experimental.plan_and_execute import (
PlanAndExecute,
load_agent_executor,
load_chat_planner,
)
search = DuckDuckGoSearchAPIWrapper()
llm = OpenAI(temperature=0)
llm_math_chain = LLMMathChain.from_llm(llm=llm, verbose=True)
tools = [
Tool(
name="Search",
func=search.run,
description="useful for when you need to answer questions about current events",
),
Tool(
name="Calculator",
func=llm_math_chain.run,
description="useful for when you need to answer questions about math",
),
]
model = ChatOpenAI(temperature=0)
planner = load_chat_planner(model)
executor = load_agent_executor(model, tools, verbose=True)
agent = PlanAndExecute(planner=planner, executor=executor)
agent.run(
"Who is the current prime minister of the UK? What is their current age raised to the 0.43 power?"
)
这里关键的planner的prompt如下:
SYSTEM_PROMPT = (
"Let's first understand the problem and devise a plan to solve the problem."
" Please output the plan starting with the header 'Plan:' "
"and then followed by a numbered list of steps. "
"Please make the plan the minimum number of steps required "
"to accurately complete the task. If the task is a question, "
"the final step should almost always be 'Given the above steps taken, "
"please respond to the users original question'. "
"At the end of your plan, say '<END_OF_PLAN>'"
)
基于以上的分析,想要定义一个自己的Agent应用,就是需要自定义这些关键组件。
OpenAI原生Assistant
在早期,OpenAI仅仅对外提供生成和对话接口,外围的编排框架需要完成输出解析,需要基于应用模式进行检索增强或者调用工具,随着function call,code interperter等能力的增强,OpenAI将这些原本外部实现的Agent需要的核心功能放到了内部,提供了Assistant接口,基于这个接口大大简化了LLM应用开发的模式,RAG及Agent应用开发变得更加简单。因此,在不久未来基于OpenAI原生的GPTs的Agent应用将会大量出现。
在新的Assistant接口中,有这样一些领域概念。
领域对象 | 解释 |
Assistant | 使用 OpenAI 模型和调用工具的特定目的的Assistant,它有多个属性,其中包括 tools 和 file_ids,分别对应 Tool 对象和 File 对象。 |
Thread | 对象表示一个聊天会话,它是有状态的,就像 ChatGPT 网页上的每个历史记录,我们可以对历史记录进行重新对话,它包含了多个 Message 对象。 |
Message | 表示一条聊天消息,分不同角色的消息,包括 user、assistant 和 tool 等。Message以列表形式存储在Thread中。 |
Run | 表示一次指令执行的过程,需要指定执行命令的对象 Assistant 和聊天会话 Thread,一个 Thread 可以创建多个 Run。 |
Run Step | 对象表示执行的步骤,一个 Run 包含多个 Run Step。查看”Run Step”可让您了解助手是如何取得最终结果的。 |
其开发过程如下:
assistant = client.beta.assistants.create(
name="Data visualizer",
description="You are great at creating beautiful data visualizations. You analyze data present in .csv files, understand trends, and come up with data visualizations relevant to those trends. You also share a brief text summary of the trends observed.",
model="gpt-4-1106-preview",
tools=[{"type": "code_interpreter"}],
file_ids=[file.id]
)
其中,tool参数可以最多128个,也就是最多支持128个工具调用,其中OpenAI托管code_interpreter and retrieval两种工具,第三方自定义工具采用functioncall。file_ids参数可指定绑定的文件,最多可以绑定20个,单个不超过512MB,最大不能超过100GB。通过file创建接口可获得file.id然后附在assistant创建接口上。同时也可以通过AssistantFile方式与具体Assitant关联,并且注意删除AssistantFile并不会删除原始的File对象,它只是删除该File和Assistant之间的关联。若要删除文件,还需要进一步利用file接口删除。
curl https://api.openai.com/v1/assistants/asst_abc123/files \
-H 'Authorization: Bearer $OPENAI_API_KEY"' \
-H 'Content-Type: application/json' \
-H 'OpenAI-Beta: assistants=v1' \
-d '{
"file_id": "file-abc123"
}'
2.创建 Thread 和 Message,可以分开创建也可以一起创建。
thread = client.beta.threads.create(
messages=[
{
"role": "user",
"content": "Create 3 data visualizations based on the trends in this file.",
"file_ids": [file.id]
}
]
)
虽然thread没有设置Message条数上限,但整体收受到context window限制。在当前thread仍然可以关联上传文件。
3.创建 由 Assistant 和 Thread 组成的 Run,创建完 Run 后会自动执行 Thread 中的指令
run = client.beta.threads.runs.create(
thread_id=thread.id,
assistant_id=assistant.id,
model="gpt-4-1106-preview",
instructions="additional instructions",
tools=[{"type": "code_interpreter"}, {"type": "retrieval"}]
)
4.轮询 Run 状态,检查是否为 completed,整个流转状态如图:
状态 | 定义 |
queued | 新建Run或完成 required_action时会变为queued状态。进而立即变为in_progress。 |
in_progress | 在in_progress,助手会使用模型和工具来执行指令。可以通过检查 ” Run Steps”来查看当前RUN的进度。 |
completed | Run成功执行。可以查看Assistant添加到Thread中所有消息,以及当前RUN的所有步骤。您还可以通过向Thread添加更多用户消息和创建另一个RUN来继续对话。 |
requires_action | 使用Function calling时,一旦模型确定了要调用的函数名称和参数,运行就会转入 required_action 状态。然后,调用方必须运行这些函数,并在运行继续之前提交输出。如果在过期时间戳(expires_at,大约为创建后 10 分钟)前未提供输出,运行将转入expired状态。 |
expired | 如果调用方未将Function calling输出在 expires_at 之前提交,运行就会过期。此外,如果运行时间过长,超过了 expires_at 中规定的时间,OpenAI系统就会使运行过期。 |
cancelling | 可以使用 “取消运行 “接口尝试取消正在进行的RUN。一旦尝试取消成功,RUN的状态将变为cancelled。尝试取消但不保证一定能够取消。 |
cancelled | RUN成功取消。 |
failed | 可以通过查看RUN中的 last_error 对象来了解故障原因。失败的时间戳将记录在 failed_at 下。 |
这个过程是个异步过程,可以通过之前生成的assistant_id,thread_id,run_id来轮询来检查执行的进度以及run step,如果有调用自定义工具(Function call),需要提交工具的执行结果,避免RUN任务停留在requires_action或者expired状态。
- 获得Run信息:
curl https://api.openai.com/v1/threads/thread_abc123/runs/run_abc123/steps/step_abc123 \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json" \
-H "OpenAI-Beta: assistants=v1"
{
"id": "step_abc123",
"object": "thread.run.step",
"created_at": 1699063291,
"run_id": "run_abc123",
"assistant_id": "asst_abc123",
"thread_id": "thread_abc123",
"type": "message_creation",
"status": "completed",
"cancelled_at": null,
"completed_at": 1699063291,
"expired_at": null,
"failed_at": null,
"last_error": null,
"step_details": {
"type": "message_creation",
"message_creation": {
"message_id": "msg_abc123"
}
}
}
获得Run Step信息:
curl https://api.openai.com/v1/threads/thread_abc123/runs/run_abc123/steps/step_abc123 \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json" \
-H "OpenAI-Beta: assistants=v1"
{
"id": "step_abc123",
"object": "thread.run.step",
"created_at": 1699063291,
"run_id": "run_abc123",
"assistant_id": "asst_abc123",
"thread_id": "thread_abc123",
"type": "message_creation",
"status": "completed",
"cancelled_at": null,
"completed_at": 1699063291,
"expired_at": null,
"failed_at": null,
"last_error": null,
"step_details": {
"type": "message_creation",
"message_creation": {
"message_id": "msg_abc123"
}
}
}
5.如果状态是 completed 则可获取最终结果
run = client.beta.threads.runs.retrieve(
thread_id=thread.id,
run_id=run.id
)
while run.status != "completed":
print(run.status)
time.sleep(60) # 等待60秒
run = client.beta.threads.runs.retrieve(
thread_id=thread.id,
run_id=run.id
)
messages = client.beta.threads.messages.list(
thread_id=thread.id
)
print(messages.data)
以上整个过程可以在OpenAI的playGround中进行调试开发。
Langchain也第一时间支持了该接口,并提供了新的Agent实现教程。
!pip install e2b duckduckgo-search
from langchain.tools import DuckDuckGoSearchRun, E2BDataAnalysisTool
tools = [E2BDataAnalysisTool(api_key="..."), DuckDuckGoSearchRun()]
agent = OpenAIAssistantRunnable.create_assistant(
name="langchain assistant e2b tool",
instructions="You are a personal math tutor. Write and run code to answer math questions. You can also search the internet.",
tools=tools,
model="gpt-4-1106-preview",
as_agent=True,
)
from langchain.agents import AgentExecutor
agent_executor = AgentExecutor(agent=agent, tools=tools)
agent_executor.invoke({"content": "What's the weather in SF today divided by 2.7"})
目前该接口处于Beta测试阶段,未来官方将补齐如下功能。
- 支持流式输出(包括 “Message”和 “Run Step”)。
- 支持无需轮询即可共享对象状态更新的通知。
- 支持作为图片生成工具 DALL-E。
- 支持用图片类用户信息。
不仅如此,在API的基础上,OpenAI还提供了面向普通用户的无代码界面化的Agent开发方法,那就是的GPTs。
可观看此视频学习如何创建(来自@agishaun的一个简历向导的GPTs):
相较于当前Beta版本的API构建方式,GPTS的界面操作更为简单直观,提供了更多的内置插件能力,如网页浏览,图片生成等,以及外部的Action调用,能够方便的分享给其它用户,甚至直接获得收益。由于其制作门槛足够低,发布之后短短几天就有上千GPTs上架GPT store。这里提供一些导航网站可以探索和借鉴最新最热的GPTs:
Agent专有框架(单agent/MutiAgent)
除了上面这些基本的agent构建的工具外,业内还有一些专门设计旨在更好完成agent构建的项目。通常包含单Agent和多Agent协同两类项目。
单Agent
- babyAGI
由Yohei Nakajima开发的babyAGI作为chatGPT横空出世后,是最先利用大模型能力构建的任务驱动型自主Agent的概念性项目之一,在当时获得了巨大的关注,对后面的Agent项目有很大的启发。它使用 OpenAI GPT-4接口和向量数据库(如 Chroma 或 Weaviate)来创建、优先排序和执行任务。其核心实现就在babyagi.py这一个脚本中,在里面可以看到其精华所在来自于prompt,其关键的三个Agent的prompt如下:
1.task_creation_agent:根据目标创建任务
prompt = f""" You are a task creation AI that uses the result of an execution agent to create new tasks with the following objective: {objective}, The last completed task has the result: {result}. This result was based on this task description: {task_description}. These are incomplete tasks: {', '.join(task_list)}. Based on the result, create new tasks to be completed by the AI system that do not overlap with incomplete tasks. Return the tasks as an array."""
2.execution_agent:根据运行历史及当前任务,获得任务返回
prompt = f""" You are an AI who performs one task based on the following objective: {objective}\n. Take into account these previously completed tasks: {context}\n. Your task: {task}\nResponse:"""
3.prioritization_agent:基于目标对任务进行排序
prompt = f""" You are a task prioritization AI tasked with cleaning the formatting of and reprioritizing the following tasks: {task_names}. Consider the ultimate objective of your team:{OBJECTIVE}. Do not remove any tasks. Return the result as a numbered list, like: #. First task #. Second task Start the task list with number {next_task_id}."""
其工作过程如下:
1. 设定目标,并通过任务生成Agent生成任务列表,从任务列表中提取第一个任务。
2. 将任务发送给执行Agent,Agent根据上下文构建prompt调用OpenAI接口完成任务。
3. 将任务与结果存储在记忆模块中,如Chroma/Weaviate 等向量数据库中。
4. 根据目标和上下文,任务创建Agent创建新的任务。
5. 任务优先级Agent,根据目标和先前任务的结果重新排列任务列表的优先级。
6. 重复步骤2-5,直到任务列表为空,判定结束目标。该项目项目历经多次迭代,其最初实现参考:https://yoheinakajima.com/task-driven-autonomous-agent-utilizing-gpt-4-pinecone-and-langchain-for-diverse-applications/。不过遗憾的是,作为概念性产品,其核心思想也被langchain等框架吸收替代,项目本身也停止了更新。
- AutoGPT
AutoGPT由Toran Bruce Richards开发的开源自主AI代理,于2023年3月发布,与babyAGI齐名,并且其功能更为完善,支持抓取网站、搜索信息、生成图像、创建和运行代码等。
AutoGPT相较于babyAGI来讲,在Prompt engieering层面走的更远,充分发挥大模型能力,让大模型代替编程来控制流程。因此,它的核心在于如何构造prompt,其执行过程分为六步:
1.创建计划,包含agent的名字,角色,以及计划目标。对应的prompt片段如下:
You are
AI Name <-(Variable)
AI Role <-(Variable)
Your decisions must always be made independently
without seeking user assistance.
Play to your strengths as a LLM and
pursue simple strategies with no legal complications.
Golas <-(Variable)
2.提供可用的工具列表,如下包含搜索、浏览网站和生成图像。
COMMANDS:
1. Google Search: "google", args: "input": "<search>"
5. Browse Website: "browse_website", args: "url": "<url>", "question": "<what_you_want_to_find_on_website>"
20. Generate Image: "generate_image", args: "prompt": "<prompt>"
3.提供可用的命令,此部分与工具都在COMMANDS下声明。
8. List GPT Agents: "list_agents", args: ""
9. Delete GPT Agent: "delete_agent", args: "key": "<key>"
10. Write to file: "write_to_file", args: "file": "<file>", "text": "<text>"
11. Read file: "read_file", args: "file": "<file>"
12. Append to file: "append_to_file", args: "file": "<file>", "text": "<text>"
13. Delete file: "delete_file", args: "file": "<file>"
4.进入执行计划迭代。框架可基于大模型返回来调用相关工具。下面是框架调用工具的基本逻辑。
if command_name == "google":
# Check if the Google API key is set and use the official search method
# If the API key is not set or has only whitespaces, use the unofficial search method
if cfg.google_api_key and (cfg.google_api_key.strip() if cfg.google_api_key else None):
return google_official_search(arguments["input"])
else:
return google_search(arguments["input"])
5.准备上下文信息,这里包含大模型在执行过程中的限制、可以使用的资源及评价方法,执行历史,结果返回格式等,部分Prompt如下:
CONSTRAINTS:
1. ~4000 word limit for short term memory. Your short term memory is short, so immediately save important information to files.
2. If you are unsure how you previously did something or want to recall past events, thinking about similar events will help you remember.
3. No user assistance
4. Exclusively use the commands listed in double quotes e.g. "command name"
RESOURCES:
1. Internet access for searches and information gathering.
2. Long Term memory management.
3. GPT-3.5 powered Agents for delegation of simple tasks.
4. File output.
PERFORMANCE EVALUATION:
1. Continuously review and analyze your actions to ensure you are performing to the best of your abilities.
2. Constructively self-criticize your big-picture behavior constantly.
3. Reflect on past decisions and strategies to refine your approach.
4. Every command has a cost, so be smart and efficient. Aim to complete tasks in the least number of steps.
You should only respond in JSON format as described below
RESPONSE FORMAT:
{
"thoughts":
{
"text": "thought",
"reasoning": "reasoning",
"plan": "- short bulleted\n- list that conveys\n- long-term plan",
"criticism": "constructive self-criticism",
"speak": "thoughts summary to say to user"
},
"command": {
"name": "command name",
"args":{
"arg name": "value"
}
}
}
Ensure the response can be parsed by Python json.loads
在Prompt中添加对话历史:
memory_to_add = f"Assistant Reply: {assistant_reply} " \
f"\nResult: {result} " \
f"\nHuman Feedback: {user_input} "
6.将计划,工具,上下文等内容整合为最终Prompt提交给大模型,等待大模型返回下一步更新后的执行计划。
最后,重复4-6步,不断更新计划,直到计划完成。
AutoGPT也提供了自己的前端UI实现,可在 Web、Android、iOS、Windows 和 Mac 上运行。作为当下最领先的Agent开发框架,开发者可以基于AutoGPT作为自己Agent,结合自己的垂直场景进行改造完善。
- AgentGPT
相较于BabyAGI,AutoGPT,AgentGPT最大的特点就是试用方便,官方提供了试用的网站(https://agentgpt.reworkd.ai/zh/),设置自己的OpenAI key,就可以直接使用。在技术实现上,与其它框架区别不大,核心还是在Prompt和工具使用上。下面是它的一个prompt:
start_goal_prompt = PromptTemplate(
template="""You are a task creation AI called AgentGPT.
You answer in the "{language}" language. You have the following objective "{goal}".
Return a list of search queries that would be required to answer the entirety of the objective.
Limit the list to a maximum of 5 queries. Ensure the queries are as succinct as possible.
For simple questions use a single query.
Return the response as a JSON array of strings. Examples:
query: "Who is considered the best NBA player in the current season?", answer: ["current NBA MVP candidates"]
query: "How does the Olympicpayroll brand currently stand in the market, and what are its prospects and strategies for expansion in NJ, NY, and PA?", answer: ["Olympicpayroll brand comprehensive analysis 2023", "customer reviews of Olympicpayroll.com", "Olympicpayroll market position analysis", "payroll industry trends forecast 2023-2025", "payroll services expansion strategies in NJ, NY, PA"]
query: "How can I create a function to add weight to edges in a digraph using {language}?", answer: ["algorithm to add weight to digraph edge in {language}"]
query: "What is the current weather in New York?", answer: ["current weather in New York"]
query: "5 + 5?", answer: ["Sum of 5 and 5"]
query: "What is a good homemade recipe for KFC-style chicken?", answer: ["KFC style chicken recipe at home"]
query: "What are the nutritional values of almond milk and soy milk?", answer: ["nutritional information of almond milk", "nutritional information of soy milk"]""",
input_variables=["goal", "language"],
)
其更多prompt可查看:https://github.com/reworkd/AgentGPT/blob/c2084e4faa46ecd91621be17574ef9532668cbfc/platform/reworkd_platform/web/api/agent/prompts.py
Muti-Agent
https://arxiv.org/pdf/2304.03442.pdf
对于一个复杂系统,如何让Agent之间协同,共同完成更为复杂的系统性工作,自然而然有了多Agent的概念。相较于单Agent,多Agent更为早期,更多是一种概念性的展示,还需要很长的路要走。而被广大同行关注的是来自于斯坦福小镇的项目(Generative Agents: Interactive Simulacra of Human Behavior),也得益于它的启发,大量的多Agent项目出现。
在这个虚拟的小镇里,每个角色都是一个单独的智能体,每天依据制定的计划按照设定的角色去活动和做事情,当他们相遇并交谈时,他们的交谈内容会被存储在记忆数据库中,并在第二天的活动计划中被回忆和引用,这一过程中就能涌现出许多颇有趣味性的社会学现象。
下面我们介绍几个比较知名的MutiAgent项目。
- MetaGPT & ChatDev
MetaGPT是一个开源多智能体框架,模拟一家软件公司,让Agent协同起来完成开发工作,它可以仅凭一行软件需求就能生成 API、用户故事、数据结构、竞争分析等。
MetaGPT符合人类软件开发的标准流程。Agent可以充当产品经理、软件工程师和架构师等角色协同起来完成开发流程。
在线试用:https://huggingface.co/spaces/deepwisdom/MetaGPT
与该项目类似,清华大学等国内机构发起的一个多智能体项目ChatDev,它虚拟一个由多智能体协作运营的软件公司,在人类“用户”指定一个具体的任务需求后,不同角色的Agent将进行交互式协同,以生产一个完整软件(包括源代码、环境依赖说明书、用户手册等)。
- AutoGen
Autogen 是微软开发的一款通用的多代理框架。它提供可定制和可对话的代理,将 LLM、工具和人类整合在一起。通过自动处理多个有能力的代理之间的聊天,人们可以轻松地让它们共同自主地或在人类反馈下执行任务,包括需要通过代码使用工具的任务。相较于MetaGPT,AutoGen是通用的,利用它可以构建各种不同形式的多Agent应用。
该框架具有以下特点:
- 多代理对话:AutoGen 代理可以相互交流,共同完成任务。
- 定制:可以对 AutoGen 代理进行定制,以满足应用程序的特定需求。这包括选择要使用的 LLM、允许的人工输入类型以及要使用的工具。
- 人可参与:AutoGen 可以人无缝对接。这意味着人类可以根据需要向代理提供输入和反馈。
AutoGen框架使我们能够协调编排多智能体工作流,相较于传统流程驱动的任务流,这种消息驱动的任务流程显得更为灵活,对处理复杂流程以及解耦领域逻辑有一定的帮助。它提供了一些通用的代理类,还提供了一个“Group Chat”的上下文,以促进跨Agent协作。以下是一些常用到的Agent类。
- User Proxy Agent:用户代理可以执行我们在python脚本中定义的功能。相当于对外声明了function,可供框架调用,如下面声明了查询wiki的函数。
user_proxy.register_function(
function_map={
"search_and_index_wikipedia": search_and_index_wikipedia,
"query_wiki_index":query_wiki_index,
}
)
Assistant Agent:由大模型能力的支持,使其能够完成特定的任务,可扮演不同的AI角色。比如,设置一个分析师角色。
analyst = autogen.AssistantAgent(
name="analyst",
system_message='''
As the Information Gatherer, you must start by using the `search_and_index_wikipedia`
function to gather relevant data about the user's query. Follow these steps:
1. Upon receiving a query, immediately invoke the `search_and_index_wikipedia`
function to find and index Wikipedia pages related to the query. Do not proceed without completing this step.
2. After successfully indexing, utilize the `query_wiki_index` to extract detailed
information from the indexed content.
3. Present the indexed information and detailed findings to the Reporter,
ensuring they have a comprehensive dataset to draft a response.
4. Conclude your part with "INFORMATION GATHERING COMPLETE" to signal that you have
finished collecting data and it is now ready for the Reporter to use in formulating the answer.
Remember, you are responsible for information collection and indexing only.
The Reporter will rely on the accuracy and completeness of your findings to generate the final answer.
''',
llm_config=llm_config,
)
Group Chat Manager:向群聊提供初始查询,并管理所有代理之间的交互。其协调和任务分发能力受大模型能力的支持。如下:
# Define the group chat manager.
manager = autogen.GroupChatManager(
groupchat=groupchat,
llm_config=llm_config,
system_message='''You should start the workflow by consulting the analyst,
then the reporter and finally the moderator.
If the analyst does not use both the `search_and_index_wikipedia`
and the `query_wiki_index`, you must request that it does.'''
)
下面是一个利用AutoGen实现类似于MetaGPT或chatDev项目软件开发场景的小例子:
# %pip install pyautogen~=0.2.0b4
import autogen
config_list_gpt4 = autogen.config_list_from_json(
"OAI_CONFIG_LIST",
filter_dict={
"model": ["gpt-4", "gpt-4-0314", "gpt4", "gpt-4-32k", "gpt-4-32k-0314", "gpt-4-32k-v0314"],
},
)
llm_config = {"config_list": config_list_gpt4, "cache_seed": 42}
user_proxy = autogen.UserProxyAgent(
name="User_proxy",
system_message="A human admin.",
code_execution_config={"last_n_messages": 2, "work_dir": "groupchat"},
human_input_mode="TERMINATE"
)
coder = autogen.AssistantAgent(
name="Coder",
llm_config=llm_config,
)
pm = autogen.AssistantAgent(
name="Product_manager",
system_message="Creative in software product ideas.",
llm_config=llm_config,
)
groupchat = autogen.GroupChat(agents=[user_proxy, coder, pm], messages=[], max_round=12)
manager = autogen.GroupChatManager(groupchat=groupchat, llm_config=llm_config)
user_proxy.initiate_chat(manager, message="Find a latest paper about gpt-4 on arxiv and find its potential applications in software.")
# type exit to terminate the chat
更多例子:https://microsoft.github.io/autogen/docs/Examples/AgentChat
总结
Prompt是人类与大模型交互的语言,通过本章从概念,理论到应用的介绍,对于其价值已经有了较为深刻的理解。而Agent就是prompt应用的巅峰典范,从某种意义上讲,它将向声明式编程又向前推进了一步,传统的我们只能在某些细分领域采用独特的dsl才可能实现,如SQL,而现在我们只需要利用自然语言,描述我们想要达成的目标,Agent系统就将帮我们实现。另一方面,RAG/Copilot应用到Agent应用的过渡,也体现了“以人为主,AI辅助”向“以AI为主,人为辅助”的模式跃变。
实际上,对于一个LLM应用,不论是Rag或是Agent,仅有一些要素组件,如大模型,Prompt,向量数据库等是不够的,怎么让他们有效整合集成起来形成一个应用系统才是最终的目标,这也是众多LLM应用框架首先切入编排集成领域的关键原因。
本文章转载微信公众号@AI工程化