当前位置:   article > 正文

AI Agent学习笔记_travily搜索引擎

travily搜索引擎

       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,代码简单易学,可以参考参考。

  1. import os
  2. import json
  3. from langchain_community.tools.tavily_search import TavilySearchResults
  4. import broadscope_bailian
  5. import datetime
  6. def llm(query,history=[],user_stop_words=[]): # 调用api_server
  7. access_key_id=os.environ.get("ACCESS_KEY_ID")
  8. access_key_secret=os.environ.get("ACCESS_KEY_SECRET")
  9. agent_key=os.environ.get("AGENT_KEY")
  10. app_id=os.environ.get("APP_ID")
  11. try:
  12. messages=[{'role':'system','content':'You are a helpful assistant.'}]
  13. for hist in history:
  14. messages.append({'role':'user','content':hist[0]})
  15. messages.append({'role':'assistant','content':hist[1]})
  16. messages.append({'role':'user','content':query})
  17. client=broadscope_bailian.AccessTokenClient(access_key_id=access_key_id, access_key_secret=access_key_secret,
  18. agent_key=agent_key)
  19. resp=broadscope_bailian.Completions(token=client.get_token()).create(
  20. app_id=app_id,
  21. messages=messages,
  22. result_format="message",
  23. stop=user_stop_words,
  24. )
  25. # print(resp)
  26. content=resp.get("Data", {}).get("Choices", [])[0].get("Message", {}).get("Content")
  27. return content
  28. except Exception as e:
  29. return str(e)
  30. # travily搜索引擎
  31. os.environ['TAVILY_API_KEY']='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' # travily搜索引擎api key
  32. tavily=TavilySearchResults(max_results=5)
  33. tavily.description='这是一个类似谷歌和百度的搜索引擎,搜索知识、天气、股票、电影、小说、百科等都是支持的哦,如果你不确定就应该搜索一下,谢谢!s'
  34. # 工具列表
  35. tools=[tavily, ]
  36. tool_names='or'.join([tool.name for tool in tools]) # 拼接工具名
  37. tool_descs=[] # 拼接工具详情
  38. for t in tools:
  39. args_desc=[]
  40. for name,info in t.args.items():
  41. args_desc.append({'name':name,'description':info['description'] if 'description' in info else '','type':info['type']})
  42. args_desc=json.dumps(args_desc,ensure_ascii=False)
  43. tool_descs.append('%s: %s,args: %s'%(t.name,t.description,args_desc))
  44. tool_descs='\n'.join(tool_descs)
  45. prompt_tpl='''Today is {today}. Please Answer the following questions as best you can. You have access to the following tools:
  46. {tool_descs}
  47. These are chat history before:
  48. {chat_history}
  49. Use the following format:
  50. Question: the input question you must answer
  51. Thought: you should always think about what to do
  52. Action: the action to take, should be one of [{tool_names}]
  53. Action Input: the input to the action
  54. Observation: the result of the action
  55. ... (this Thought/Action/Action Input/Observation can be repeated zero or more times)
  56. Thought: I now know the final answer
  57. Final Answer: the final answer to the original input question
  58. Begin!
  59. Question: {query}
  60. {agent_scratchpad}
  61. '''
  62. def agent_execute(query,chat_history=[]):
  63. global tools,tool_names,tool_descs,prompt_tpl,llm,tokenizer
  64. agent_scratchpad='' # agent执行过程
  65. while True:
  66. # 1)触发llm思考下一步action
  67. history='\n'.join(['Question:%s\nAnswer:%s'%(his[0],his[1]) for his in chat_history])
  68. today=datetime.datetime.now().strftime('%Y-%m-%d')
  69. prompt=prompt_tpl.format(today=today,chat_history=history,tool_descs=tool_descs,tool_names=tool_names,query=query,agent_scratchpad=agent_scratchpad)
  70. print('\033[32m---等待LLM返回... ...\n%s\n\033[0m'%prompt,flush=True)
  71. response=llm(prompt,user_stop_words=['Observation:'])
  72. print('\033[34m---LLM返回---\n%s\n---\033[34m'%response,flush=True)
  73. # 2)解析thought+action+action input+observation or thought+final answer
  74. thought_i=response.rfind('Thought:')
  75. final_answer_i=response.rfind('\nFinal Answer:')
  76. action_i=response.rfind('\nAction:')
  77. action_input_i=response.rfind('\nAction Input:')
  78. observation_i=response.rfind('\nObservation:')
  79. # 3)返回final answer,执行完成
  80. if final_answer_i!=-1 and thought_i<final_answer_i:
  81. final_answer=response[final_answer_i+len('\nFinal Answer:'):].strip()
  82. chat_history.append((query,final_answer))
  83. return True,final_answer,chat_history
  84. # 4)解析action
  85. if not (thought_i<action_i<action_input_i):
  86. return False,'LLM回复格式异常',chat_history
  87. if observation_i==-1:
  88. observation_i=len(response)
  89. response=response+'Observation: '
  90. thought=response[thought_i+len('Thought:'):action_i].strip()
  91. action=response[action_i+len('\nAction:'):action_input_i].strip()
  92. action_input=response[action_input_i+len('\nAction Input:'):observation_i].strip()
  93. # 5)匹配tool
  94. the_tool=None
  95. for t in tools:
  96. if t.name==action:
  97. the_tool=t
  98. break
  99. if the_tool is None:
  100. observation='the tool not exist'
  101. agent_scratchpad=agent_scratchpad+response+observation+'\n'
  102. continue
  103. # 6)执行tool
  104. try:
  105. action_input=json.loads(action_input)
  106. tool_ret=the_tool.invoke(input=json.dumps(action_input))
  107. except Exception as e:
  108. observation='the tool has error:{}'.format(e)
  109. else:
  110. observation=str(tool_ret)
  111. agent_scratchpad=agent_scratchpad+response+observation+'\n'
  112. def agent_execute_with_retry(query,chat_history=[],retry_times=3):
  113. for i in range(retry_times):
  114. success,result,chat_history=agent_execute(query,chat_history=chat_history)
  115. if success:
  116. return success,result,chat_history
  117. return success,result,chat_history
  118. my_history=[]
  119. while True:
  120. query=input('query:')
  121. success,result,my_history=agent_execute_with_retry(query,chat_history=my_history)
  122. 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模板

  1. from langchain_core.prompts import PromptTemplate
  2. template = '''Answer the following questions as best you can. You have access to the following tools:
  3. {tools}
  4. Use the following format:
  5. Question: the input question you must answer
  6. Thought: you should always think about what to do
  7. Action: the action to take, should be one of [{tool_names}]
  8. Action Input: the input to the action
  9. Observation: the result of the action
  10. ... (this Thought/Action/Action Input/Observation can repeat N times)
  11. Thought: I now know the final answer
  12. Final Answer: the final answer to the original input question
  13. Begin!
  14. Question: {input}
  15. Thought:{agent_scratchpad}'''
  16. 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

2、手把手教你从零搭建Agent框架_agent 架构-CSDN博客

3、手把手教你从0到1搭建一个AI Agent(智能体)_搭建ai agent-CSDN博客

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/907990?site
推荐阅读
相关标签
  

闽ICP备14008679号