AI Agent是一种超越简单文本生成的人工智能系统。它使用大型语言模型(LLM)作为其核心计算引擎,使其能够进行对话、执行任务、推理并展现一定程度的自主性。简而言之,Agent是一个具有复杂推理能力、记忆和执行任务手段的系统。Agent相当于整体框架的思维推理系统,通常由大模型、Prompt提供支持。不同的智能体有不同的推理提示风格、不同的输入方式以及不同的解析输出方式,依赖于用户对应用的自定义,说白了就是对大模型进行一层封装更方便管理。
(1)agent组成
在LLM赋能的自主agent系统中(LLM Agent),LLM充当agent大脑的角色,并与若干关键组件协作 。

规划(planning)
- 子目标分解:agent将大任务拆分为更小的可管理的子目标,使得可以有效处理复杂任务。
- 反思与完善:agent对历史动作可以自我批评和自我反思,从错误中学习并在后续步骤里完善,从而改善最终结果的质量。
记忆(Memory)
- 短期记忆:上下文学习即是利用模型的短期记忆学习
- 长期记忆:为agent提供保留和召回长期信息的能力,通常利用外部向量存储和检索实现
工具使用(tool use)
- 对模型权重丢失的信息,agent学习调用外部API获取额外信息,包括当前信息、代码执行能力、专有信息源的访问等等
行动(Action)
- 行动模块是智能体实际执行决定或响应的部分。面对不同的任务,智能体系统有一个完整的行动策略集,在决策时可以选择需要执行的行动,比如广为熟知的记忆检索、推理、学习、编程等。
(2)agent示例
开源社区涌现出多个优秀的 AI Agent 框架,常见的备受关注的开源AI Agent框架包括AutoGPT、AutoGen、Langfuse、ChatDev、BabyAGI、CAMEL、SuperAGI、MetaGPT和ShortGPT。这些框架为开发者提供了丰富的资源和工具,为智能应用的开发和创新提供了强大支持。
Auto-GPT是一个实验性的开源应用程序,展示了GPT-4语言模型的能力。这个程序由GPT-4驱动,将LLM“思想”连接在一起,以自主地实现您设置的任何目标。作为GPT-4完全自主运行的最早示例之一,Auto-GPT突破了人工智能的极限,将AI进程推向了新高度 -- 自主人工智能。

- autogen
微软发布的AutoGen agent是可定制的、可对话的,并能以各种模式运行,这些模式采用 LLM、人类输入和工具的组合。使用 AutoGen,开发人员还可以灵活定义agent交互行为。自然语言和计算机代码都可用于为不同的应用编程灵活的对话模式。AutoGen 可作为一个通用框架,构建具有不同复杂性和 LLM 能力的各种应用。实证研究证明了该框架在许多样本应用中的有效性,应用领域包括数学、编码、问答、运筹学、在线决策、娱乐等。

(3)搭建自己的ai agent
这里推荐一个b站up主,基于阿里通义千问开发的一个个人搜索agent,代码简单易学,可以参考参考。
import os
import json
from langchain_community.tools.tavily_search import TavilySearchResults
import broadscope_bailian
import datetime
def llm(query,history=[],user_stop_words=[]): # 调用api_server
access_key_id=os.environ.get("ACCESS_KEY_ID")
access_key_secret=os.environ.get("ACCESS_KEY_SECRET")
agent_key=os.environ.get("AGENT_KEY")
app_id=os.environ.get("APP_ID")
try:
messages=[{'role':'system','content':'You are a helpful assistant.'}]
for hist in history:
messages.append({'role':'user','content':hist[0]})
messages.append({'role':'assistant','content':hist[1]})
messages.append({'role':'user','content':query})
client=broadscope_bailian.AccessTokenClient(access_key_id=access_key_id, access_key_secret=access_key_secret,
agent_key=agent_key)
resp=broadscope_bailian.Completions(token=client.get_token()).create(
app_id=app_id,
messages=messages,
result_format="message",
stop=user_stop_words,
)
# print(resp)
content=resp.get("Data", {}).get("Choices", [])[0].get("Message", {}).get("Content")
return content
except Exception as e:
return str(e)
# travily搜索引擎
os.environ['TAVILY_API_KEY']='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' # travily搜索引擎api key
tavily=TavilySearchResults(max_results=5)
tavily.description='这是一个类似谷歌和百度的搜索引擎,搜索知识、天气、股票、电影、小说、百科等都是支持的哦,如果你不确定就应该搜索一下,谢谢!s'
# 工具列表
tools=[tavily, ]
tool_names='or'.join([tool.name for tool in tools]) # 拼接工具名
tool_descs=[] # 拼接工具详情
for t in tools:
args_desc=[]
for name,info in t.args.items():
args_desc.append({'name':name,'description':info['description'] if 'description' in info else '','type':info['type']})
args_desc=json.dumps(args_desc,ensure_ascii=False)
tool_descs.append('%s: %s,args: %s'%(t.name,t.description,args_desc))
tool_descs='\n'.join(tool_descs)
prompt_tpl='''Today is {today}. Please Answer the following questions as best you can. You have access to the following tools:
{tool_descs}
These are chat history before:
{chat_history}
Use the following format:
Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should be one of [{tool_names}]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can be repeated zero or more times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question
Begin!
Question: {query}
{agent_scratchpad}
'''
def agent_execute(query,chat_history=[]):
global tools,tool_names,tool_descs,prompt_tpl,llm,tokenizer
agent_scratchpad='' # agent执行过程
while True:
# 1)触发llm思考下一步action
history='\n'.join(['Question:%s\nAnswer:%s'%(his[0],his[1]) for his in chat_history])
today=datetime.datetime.now().strftime('%Y-%m-%d')
prompt=prompt_tpl.format(today=today,chat_history=history,tool_descs=tool_descs,tool_names=tool_names,query=query,agent_scratchpad=agent_scratchpad)
print('\033[32m---等待LLM返回... ...\n%s\n\033[0m'%prompt,flush=True)
response=llm(prompt,user_stop_words=['Observation:'])
print('\033[34m---LLM返回---\n%s\n---\033[34m'%response,flush=True)
# 2)解析thought+action+action input+observation or thought+final answer
thought_i=response.rfind('Thought:')
final_answer_i=response.rfind('\nFinal Answer:')
action_i=response.rfind('\nAction:')
action_input_i=response.rfind('\nAction Input:')
observation_i=response.rfind('\nObservation:')
# 3)返回final answer,执行完成
if final_answer_i!=-1 and thought_i<final_answer_i:
final_answer=response[final_answer_i+len('\nFinal Answer:'):].strip()
chat_history.append((query,final_answer))
return True,final_answer,chat_history
# 4)解析action
if not (thought_i<action_i<action_input_i):
return False,'LLM回复格式异常',chat_history
if observation_i==-1:
observation_i=len(response)
response=response+'Observation: '
thought=response[thought_i+len('Thought:'):action_i].strip()
action=response[action_i+len('\nAction:'):action_input_i].strip()
action_input=response[action_input_i+len('\nAction Input:'):observation_i].strip()
# 5)匹配tool
the_tool=None
for t in tools:
if t.name==action:
the_tool=t
break
if the_tool is None:
observation='the tool not exist'
agent_scratchpad=agent_scratchpad+response+observation+'\n'
continue
# 6)执行tool
try:
action_input=json.loads(action_input)
tool_ret=the_tool.invoke(input=json.dumps(action_input))
except Exception as e:
observation='the tool has error:{}'.format(e)
else:
observation=str(tool_ret)
agent_scratchpad=agent_scratchpad+response+observation+'\n'
def agent_execute_with_retry(query,chat_history=[],retry_times=3):
for i in range(retry_times):
success,result,chat_history=agent_execute(query,chat_history=chat_history)
if success:
return success,result,chat_history
return success,result,chat_history
my_history=[]
while True:
query=input('query:')
success,result,my_history=agent_execute_with_retry(query,chat_history=my_history)
my_history=my_history[-10:]
无论是环境的反馈,还是人类的指令,Agent 都需要完成一个对接收到的信息进行“理解”,并依据得到的理解进行意图识别,转化为下一步任务的过程(CoT,思维链Chain of Thought,以大大帮助模型对现有输入进行“感知”,激活大模型对任务的拆分规划和推理能力),于是出现了React框架,允许 LLMs 与外部工具交互来获取额外信息,从而给出更可靠和实际的回应。可以简单理解llm流程:Standard IO(直接回答) -> COT(chain-of-thought)(思维链) -> Action-Only (Function calling) -> Reason + Action,而ReAct = Reasoning(推理) + Action(行动)。
ReAct 是一个将推理和行为与 LLMs 相结合通用的范例。ReAct 提示 LLMs 为任务生成口头推理轨迹和操作。这使得系统执行动态推理来创建、维护和调整操作计划,同时还支持与外部环境(例如,Wikipedia)的交互,以将额外信息合并到推理中

常用的prompt模板
from langchain_core.prompts import PromptTemplate
template = '''Answer the following questions as best you can. You have access to the following tools:
{tools}
Use the following format:
Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should be one of [{tool_names}]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can repeat N times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question
Begin!
Question: {input}
Thought:{agent_scratchpad}'''
prompt = PromptTemplate.from_template(template)
下面可以参考这篇博客构建一个可以辅助购买车票的agent
(4)基于开源工具搭建agent
这里就不得不推荐腾讯开源的dify和字节的coze,就有点像qt designer,通过拖拽形成自己的ai 工作流,通过配置用到大模型所需的key,完成单独每个工作独有agent的构建,大大降低了ai使用的入门门槛,不需要基于langchain来一点点搭建了。具体的操作可以参考Dify: 轻松助你创建基于 GPT-4 的 AI 原生应用-CSDN博客
参考链接:
1、https://zhuanlan.zhihu.com/p/676544930

4048

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



