核心内容摘要
灵魂的碰撞与禁忌的边缘:一次关于欲望、艺术与社会解读的深度探索
代理原理代理的核心思想是使用语言模型来选择一系列操作。
在链中,一系列操作是硬编码的。
在代理中,语言模型被用作推理引擎来确定要采取哪些操作以及按什么顺序。
需要了解的重要概念:需要了解的重要概念:AgentAction:表示代理应采取的操作。
它有一个tool属性(要调用的工具的名称)和一个tool_input属性(该工具的输入)AgentFinish:表示代理已完成,应返回给用户。
它有一个return_values参数,它通常只有一个键——output,即一个字符串,因此通常只返回这个键。
intermediate_steps:代表之前的代理操作和相应输出。
这对于传递给未来迭代非常重要,所以代理知道它已经完成了哪些工作。
它被编码为List[Tuple[AgentAction, Any]].总的来说,代理的核心思想是:使用语言模型来选择一系列操作AgentAction表示一个操作 [] messagelogAgentFinish表示代理已完成 [AgentFinish(return_values{‘output’: ‘单词color有5个字母。
’}, log‘单词color有5个字母。
’)]intermediate_steps记录之前的操作和输出,用于未来迭代【tool3 tools2tools3】语言模型作为推理引擎,确定要采取哪些操作和按什么顺序。
Agent代理在 Langchain 中Agent 是指一个智能合约的实例。
它代表了合约的执行者可以看作是一个具有特定功能的智能合约的化身。
Agent 能够根据合约的逻辑执行相应的操作如转账、查询余额等。
它是区块链网络中的一个基本单位可以理解为一个可编程的、自主执行任务的角色。
Chain链Langchain 中的 Chain 指的是一个由多个 Agent 组成的序列。
这些 Agent 按照一定的顺序链接在一起形成一个链式结构。
Chain 是 Langchain 平台的基本组织结构用于实现分布式账本、智能合约等功能。
每个 Chain 都对应一个唯一的标识符如一个哈希值。
Chain 中的 Agent 按照预先设定的规则执行任务共同维护整个链的稳定和安全。
Agent 是 Chain 的基本组成单元一个 Chain 由多个 Agent 构成。
Chain 是 Agent 存在的载体Agent 通过加入 Chain 来实现其功能和价值。
Agent 和 Chain 共同构成了 Langchain 平台的核心技术体系
源码查看https://github.com/langchain-ai/langchain/blob/804390ba4bcc306b90cb6d75b7f01a4231ab6463/libs/langchain/langchain/agents/init.py
创建工具 装饰器方法from langchain.chat_models import ChatOpenAI # 创建语言模型 llm ChatOpenAI(temperature
# 构建工具 from langchain.agents import tool tool def get_word_length(word: str) - int: 返回单词的长度 return len(word) # 创建工具清单 tools [get_word_length]看看工具函数一个name参数代表这个函数名称一个description返回这个工具的使用说明
绑定工具# 绑定工具 from langchain.tools.render import format_tool_to_openai_function # 格式化函数作为符合openai格式的描述体 llm_with_tools llm.bind( functions[format_tool_to_openai_function(t) for t in tools] )format_tool_to_openai_function 这个方法将工具函数转换为符合 OpenAi格式的描述体即fucntion calling函数调用是构建由 LLM 驱动的聊天机器人或代理的一项重要功能这些聊天机器人或代理需要检索 LLM 的上下文或通过将自然语言转换为 API 调用来与外部工具交互。
创建代理下面代码一个是prompt创建了2个输入keyinput 用于用户输入内容agent_scratchpad 用户代理中间使用过程的记录# 创建代理 from langchain.agents.format_scratchpad import format_to_openai_functions from langchain.agents.output_parsers import OpenAIFunctionsAgentOutputParser from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder prompt ChatPromptTemplate.from_messages([ (system, 你是一个非常优秀的人但是不会计算单词的长度), (user, {input}), MessagesPlaceholder(variable_nameagent_scratchpad), # 消息体当中添加一个 key记录代理的使用过程 ]) agent { input: lambda x: x[input], agent_scratchpad: lambda x: format_to_openai_functions(x[intermediate_steps]) # 代理的使用过程 } | prompt | llm_with_tools | OpenAIFunctionsAgentOutputParser()现在来使用它output agent.invoke({ input: 关于color有多少个字母?, intermediate_steps: [],# 中间步骤 })可以看到生成了 一个AgentActionMessageLog这个表示代理应该要采集的动作并没有到结束为了更加直观我复制出来可以看到将用户的问“关于color有多少个字母?”这个问题去提取了 color并且准备调用get_word_length工具函数关键字tool、tool_input现在我询问另外一个问题看看输出的样式直接为AgentFinish这个表明代理已经完成动作原因在于我们封装的工具函数并没有解决 “太阳和地球的距离”关键字return_values
完整代码好了到现在是不是看起来有点懵逼现在通过下面代码来加深一步过程一个代理Agent从白话文来说-简化成2个过程AgentAction 代理开始AgentFinish 代理结束当只有看到这个类型才视为结束那么现在将前面的代码抽取出来通过while True 完善 工具链的使用from langchain.chat_models import ChatOpenAI # 创建语言模型 llm ChatOpenAI(temperature
# 构建工具 from langchain.agents import tool tool def get_word_length(word: str) - int: 返回单词的长度 return len(word) # 创建工具清单 tools [get_word_length] # 绑定工具 from langchain.tools.render import format_tool_to_openai_function # 格式化函数作为符合openai格式的描述体 llm_with_tools llm.bind( functions[format_tool_to_openai_function(t) for t in tools] ) # 创建代理 from langchain.agents.format_scratchpad import format_to_openai_functions from langchain.agents.output_parsers import OpenAIFunctionsAgentOutputParser from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder prompt ChatPromptTemplate.from_messages([ (system, 你是一个非常优秀的人但是不会计算单词的长度), (user, {input}), MessagesPlaceholder(variable_nameagent_scratchpad), # 消息体当中添加一个 key记录代理的使用过程 ]) agent { input: lambda x: x[input], agent_scratchpad: lambda x: format_to_openai_functions(x[intermediate_steps]) # 代理的使用过程 } | prompt | llm_with_tools | OpenAIFunctionsAgentOutputParser() from langchain.schema.agent import AgentFinish intermediate_steps [] count 1 while True: output agent.invoke({ input: 关于color有多少个字母?, intermediate_steps: intermediate_steps }) print(f\n轮询第{count}次,output,过程对象,type(output)) count 1 # 判断代理是否有结束标记有的话结束 if isinstance(output, AgentFinish): final_result output.return_values[output] break else: # 从AgentAction 中提取要执行的 tool工具名称跟tool_input工具的输入参数 tool { get_word_length: get_word_length }[output.tool] observation tool.run(output.tool_input) # 运行工具函数并且得到结果 intermediate_steps.append((output, observation))查看结果可以看到出来了回复
简化代码前面的代码更多的是为了让大家了解底层原理langchain提供了一个函数用于简化操作。
from langchain.chat_models import ChatOpenAI # 创建语言模型 llm ChatOpenAI(temperature
# 构建工具 from langchain.agents import tool tool def get_word_length(word: str) - int: 返回单词的长度 return len(word) # 创建工具清单 tools [get_word_length] # 绑定工具 from langchain.tools.render import format_tool_to_openai_function # 格式化函数作为符合openai格式的描述体 llm_with_tools llm.bind( functions[format_tool_to_openai_function(t) for t in tools] ) # 创建代理 from langchain.agents.format_scratchpad import format_to_openai_functions from langchain.agents.output_parsers import OpenAIFunctionsAgentOutputParser from langchain.prompts import ChatPromptTemplate, MessagesPlaceholder prompt ChatPromptTemplate.from_messages([ (system, 你是一个非常优秀的人但是不会计算单词的长度), (user, {input}), MessagesPlaceholder(variable_nameagent_scratchpad), # 消息体当中添加一个 key记录代理的使用过程 ]) agent { input: lambda x: x[input], agent_scratchpad: lambda x: format_to_openai_functions(x[intermediate_steps]) # 代理的使用过程 } | prompt | llm_with_tools | OpenAIFunctionsAgentOutputParser() # 使用代理 from langchain.agents import AgentExecutor agent_executor AgentExecutor(agentagent, toolstools, verboseTrue) agent_executor.invoke({input: 关于color有多少个字母?})看看结果关于AgentExecutor这个方法常用参数说明max_iterations 默认迭代工具15次可以设置return_intermediate_steps 是否返回代理的中间步骤轨迹在最后除了最终输出之外关于AgentExecutor的源码https://github.com/langchain-ai/langchain/blob/804390ba4bcc306b90cb6d75b7f01a4231ab6463/libs/langchain/langchain/agents/agent.py#L
加上历史对话为了做到这一点需要添加内存来解决这个问题
在提升中添加内存变量的位置
跟踪聊天记录首先在提示中添加一个内存位置。
通常使用带有key的消息添加占位符来实现此目的的“chat_history”这个放入的位置是有讲究放到新用户输入的之上符合对话流程MessagesPlaceholder注意看 prompt 该位置from langchain.agents.format_scratchpad import format_to_openai_functions from langchain.agents.output_parsers import OpenAIFunctionsAgentOutputParser from langchain.prompts import MessagesPlaceholder, ChatPromptTemplate from langchain.chat_models import ChatOpenAI from langchain.agents import tool, AgentExecutor from langchain.tools.render import format_tool_to_openai_function # 创建语言模型 llm ChatOpenAI(temperature
# 构建工具 tool def get_word_length(word: str) - int: 返回单词的长度 return len(word) tools [get_word_length] # 绑定工具 llm_with_tools llm.bind( functions[format_tool_to_openai_function(t) for t in tools] ) MEMORY_KEY chat_history prompt ChatPromptTemplate.from_messages([ (system, 你是一个非常优秀的人但是不会计算单词的长度), MessagesPlaceholder(variable_nameMEMORY_KEY), (user, {input}), MessagesPlaceholder(variable_nameagent_scratchpad), ]) chat_history [] agent { input: lambda x: x[input], agent_scratchpad: lambda x: format_to_openai_functions(x[intermediate_steps]), chat_history: lambda x: x[chat_history] } | prompt | llm_with_tools | OpenAIFunctionsAgentOutputParser() agent_executor AgentExecutor(agentagent, toolstools, verboseTrue) # 模拟已经对话过一次 input1 关于color有多少个字母? result agent_executor.invoke({input: input1, chat_history: chat_history}) # 历史消息加上聊天记录 chat_history.append(HumanMessage(contentinput
) chat_history.append(AIMessage(contentresult[output])) agent_executor.invoke({input: 这个单词中文翻译是什么, chat_history: chat_history})可以看到执行了2次
Agent使用在开始下面之前以12 小节知识作为更好理解代理Agent既可以看到成tool工具chain链等等
langchain-smith 介绍在开始之前先了解一下 langchain - smith 上提供的 hub 平台当然这个平台还有其它功能比如测试应用的流等等https://smith.langchain.com/hub其中这个平台提供了很多 prompt 的用例我们可以通过代码拉取现成的prompt 在langchain中使用我们来看一下这个 prompthttps://smith.langchain.com/hub/hwchase17/react-chat?organizationIdbe7e61a9-df
f-e90160a9f
ReAct 介绍ReAct 是一个结合了推理和行动功能的方法通过交叉生成推理轨迹和特定于任务的动作从而实现更大的协同作用。
它在问答和决策任务中表现优秀具有较高的可解释性和可信度。
通过人类对齐的 ReAct 提示设计使得模型能够更好地理解和应用人类思维的模式取得了令人印象深刻的结果。
虽然还存在改进的空间但ReAct 在许多任务上展示出了很高的潜力和有效性。
关键词记忆Action 行动Thought 思考做出何种决策Observation 观察决策的结果Answer 回复
总结答案Finish 结束推理决策当然这是一种prompt的写法能够很好的提升对于交互问题另外还有COT、TOT等架构如果想了解更多promtp等使用可以阅读下面网站https://www.promptingguide.ai/research
使用内置工具在本案例中通过内置工具调用并且利用langchain-smith 中 hub 的prompt 将工具绑定进去使用from langchain.tools import YouTubeSearchTool,Tool tool YouTubeSearchTool() tool.run(成龙)可以看到能够出来2个url此时打开网页查询一下利用partial格式化部分模版的参数这里将hub模版拉下来指定2个参数添加内容这个模版有5个参数这里只要2个使用https://github.com/langchain-ai/langchain/blob/804390ba4bcc306b90cb6d75b7f01a4231ab6463/libs/core/langchain_core/prompts/base.py#L181如果用format_prompt 则需要指定额外参数才行可以看源码或者自己体验只传2个参数会出错from langchain.tools import YouTubeSearchTool,Tool tool YouTubeSearchTool() # 创建工具 tools [ Tool( nameyoutube搜索, functool.run, description用户如果问题有关成龙则使用这个工具 ) ] # 在prompt中绑定工具 from langchain.tools.render import render_text_description source_prompt hub.pull(hwchase17/react-chat) prompt source_prompt.partial( toolsrender_text_description(tools),# 返回工具的文本描述 tool_names, .join([t.name for t in tools]), ) # 绑定工具 from langchain.llms import OpenAI llm OpenAI(temperature
llm_with_stop llm.bind(stop[\nObservation]) # 参考ReAct架构添加一个停止词 # 创建代理可以看到这里对于模版剩下3个提示词进行了操作 from langchain.agents.output_parsers import ReActSingleInputOutputParser from langchain.agents.format_scratchpad import format_log_to_str agent { input: lambda x: x[input],# 用户输入 agent_scratchpad: lambda x: format_log_to_str(x[intermediate_steps]),# 一个是代理执行步骤 chat_history: lambda x: x[chat_history] # 聊天记录 } | prompt | llm_with_stop | ReActSingleInputOutputParser() # 创建代理执行执行器 from langchain.agents import AgentExecutor from langchain.memory import ConversationBufferMemory memory ConversationBufferMemory(memory_keychat_history) agent_executor AgentExecutor(agentagent, toolstools, verboseTrue, memorymemory)看看结果2轮对话
AgentType在前面我们看到了工具创建好了都通过自己创建Agent进行使用现在我们可以通过现成的封装直接使用关于更多功能查看源代码准备工作去这个平台注册一个keyhttps://serpapi.com/manage-api-key安装一个包pip install google-search-resultsfrom langchain.agents import Tool from langchain.agents import AgentType from langchain.memory import ConversationBufferMemory from langchain.llms import OpenAI from langchain.utilities import SerpAPIWrapper from langchain.agents import initialize_agent import os os.environ[SERPAPI_API_KEY] search SerpAPIWrapper() tools [ Tool( name物流工具, funcsearch.run, description这对于回答相关船期与货物跟踪的时候非常有用如果计算问题不要使用这个工具 ) ] llm OpenAI(temperature
memory ConversationBufferMemory(memory_keychat_history) # 使用现成的代理类创建代理 agent_executor initialize_agent( tools, llm, agentAgentType.CONVERSATIONAL_REACT_DESCRIPTION, verboseTrue, memorymemory, )关于AgentType.CONVERSATIONAL_REACT_DESCRIPTION执行一下看看结果agent_executor.invoke({盐田到洛杉矶会经过哪些港口})
多工具组合以及AgentExecutorIterator使用AgentExecutorIterator 在 langchain 中主要用于:批量执行代理AgentExecutorIterator 可以将一组输入数据,批量传递给代理,并获取代理的批量输出。
迭代执行代理AgentExecutorIterator 可以迭代执行代理,每次传递一个输入,获取一个输出。
提供进度提示AgentExecutorIterator 可以提供进度提示,显示当前执行到第几个输入。
step1创建模型跟链from langchain.chains import LLMMathChain from langchain.chat_models import ChatOpenAI llm ChatOpenAI(temperature0, modelgpt-
llm_math_chain LLMMathChain.from_llm(llmllm, verboseTrue)step2创建2个工具import pydantic.v1 as pydantic from langchain.agents.tools import Tool primes {998: 7901, 999: 7907, 1000: 7919} class CalculatorInput(pydantic.BaseModel): 计算器的输入 question: str pydantic.Field() class PrimeInput(pydantic.BaseModel): 主输入 n: int pydantic.Field() def is_prime(n: int) - bool: if n 1 or (n % 2 0 and n
: return False for i in range(3, int(n **
0.
1,
: if n % i 0: return False return True def get_prime(n: int, primes: dict primes) - str: 计算素数 return str(primes.get(int(n))) async def aget_prime(n: int, primes: dict primes) - str: 代理 return str(primes.get(int(n))) # 工具清单 tools [ Tool( nameGetPrime, funcget_prime, description返回第 n 个素数的工具, args_schemaPrimeInput, # 以pydantic 进行约束字段 coroutineaget_prime, # 异步 ), Tool.from_function( funcllm_math_chain.run, nameCalculator, description当您需要计算数学表达式时很有用, args_schemaCalculatorInput, # 以pydantic 进行约束字段 coroutinellm_math_chain.arun, # 异步 ), ]step3创建代理并且使用代理# 创建代理 agent initialize_agent( tools, llm, agentAgentType.ZERO_SHOT_REACT_DESCRIPTION, verboseTrue ) # 使用代理 question 第 998 个、第 999 个和第 1000 个素数的乘积是多少 for step in agent.iter(question): if output : step.get(intermediate_step): action, value output[0] if action.tool GetPrime: print(f正在检查 {value} 是否为质数...) assert is_prime(int(value)) # Ask user if they want to continue _continue input(代理是否应该继续 (Y/n)?:\n) if _continue ! Y: break查看结果很有意思
检查用户输入的9989991000 通过工具is_prime检查是否为素数
然后最后得到3个素数调用get_prime工具进行计算
整个过程当中因为使用了ReAct 能够看到关键词- Action- Action input- Observation- Thought- Answer- Final Answer
什么时候使用另外一个工具也做到了这就是prompt工程的魅力平替方法from langchain.agents import AgentExecutorIterator AgentExecutorIterator( agent_executoragent_executor, inputs[{input: 第 998 个、第 999 个和第 1000 个素数的乘积是多少}] ) # 迭代执行代理,获取输出 outputs [] for output in iterator: outputs.append(output)
6、
总结为了更好的理解Agentlangchain封装了挺多的函数对于用户输入前内容处理的函数 比如利用 prompt对于模型与内容交互时候处理工艺的函数比如利用 ReAct模式对于返回结果格式化某样式的工艺函数比如输出JSON对于Agent而言前文也做了部分解释Agent代理在 Langchain 中Agent 是指一个智能合约的实例。
它代表了合约的执行者可以看作是一个具有特定功能的智能合约的化身。
Agent 能够根据合约的逻辑执行相应的操作如转账、查询余额等。
它是区块链网络中的一个基本单位可以理解为一个可编程的、自主执行任务的角色。
Chain链Langchain 中的 Chain 指的是一个由多个 Agent 组成的序列。
这些 Agent 按照一定的顺序链接在一起形成一个链式结构。
Chain 是 Langchain 平台的基本组织结构用于实现分布式账本、智能合约等功能。
每个 Chain 都对应一个唯一的标识符如一个哈希值。
Chain 中的 Agent 按照预先设定的规则执行任务共同维护整个链的稳定和安全。
Agent 是 Chain 的基本组成单元一个 Chain 由多个 Agent 构成。
Chain 是 Agent 存在的载体Agent 通过加入 Chain 来实现其功能和价值。
Agent 和 Chain 共同构成了 Langchain 平台的核心技术体系源码地址https://github.com/langchain-ai/langchain/blob/804390ba4bcc306b90cb6d75b7f01a4231ab6463/libs/langchain/langchain/agents/init.py可以看到有很多方法跟功能对于部分封装函数以案例介绍对于详细函数的理解建议大家看源码比如这样复制create_json_agent这个函数在源码进行查看如何学习AGI大模型作为一名热心肠的互联网老兵我决定把宝贵的AI知识分享给大家。
至于能学习到多少就看你的学习毅力和能力了 。
我已将重要的AI大模型资料包括AI大模型入门学习思维导图、精品AI大模型学习书籍手册、视频教程、实战学习等录播视频免费分享出来。
因篇幅有限仅展示部分资料需要点击下方链接即可前往获取2025最新版CSDN大礼包《AGI大模型学习资源包》免费分享**
2025最新大模型学习路线一个明确的学习路线可以帮助新人了解从哪里开始按照什么顺序学习以及需要掌握哪些知识点。
大模型领域涉及的知识点非常广泛没有明确的学习路线可能会导致新人感到迷茫不知道应该专注于哪些内容。
我们把学习路线分成L1到L4四个阶段一步步带你从入门到进阶从理论到实战。
L1级别:AI大模型时代的华丽登场L1阶段我们会去了解大模型的基础知识以及大模型在各个行业的应用和分析学习理解大模型的核心原理
关键技术以及大模型应用场景通过理论原理结合多个项目实战从提示工程基础到提示工程进阶掌握Prompt提示工程。
L2级别AI大模型RAG应用开发工程L2阶段是我们的AI大模型RAG应用开发工程我们会去学习RAG检索增强生成包括Naive RAG、Advanced-RAG以及RAG性能评估还有GraphRAG在内的多个RAG热门项目的分析。
L3级别大模型Agent应用架构进阶实践L3阶段大模型Agent应用架构进阶实现我们会去学习LangChain、 LIamaIndex框架也会学习到AutoGPT、 MetaGPT等多Agent系统打造我们自己的Agent智能体同时还可以学习到包括Coze、Dify在内的可视化工具的使用。
L4级别大模型微调与私有化部署L4阶段大模型的微调和私有化部署我们会更加深入的探讨Transformer架构学习大模型的微调技术利用DeepSpeed、Lamam Factory等工具快速进行模型微调并通过Ollama、vLLM等推理部署框架实现模型的快速部署。
整个大模型学习路线L1主要是对大模型的理论基础、生态以及提示词他的一个学习掌握而L3 L4更多的是通过项目实战来掌握大模型的应用开发针对以上大模型的学习路线我们也整理了对应的学习视频教程和配套的学习资料。
大模型经典PDF书籍书籍和学习文档资料是学习大模型过程中必不可少的我们精选了一系列深入探讨大模型技术的书籍和学习文档它们由领域内的顶尖专家撰写内容全面、深入、详尽为你学习大模型提供坚实的理论基础。
书籍含电子版PDF
大模型视频教程对于很多自学或者没有基础的同学来说书籍这些纯文字类的学习教材会觉得比较晦涩难以理解因此我们提供了丰富的大模型视频教程以动态、形象的方式展示技术概念帮助你更快、更轻松地掌握核心知识。
大模型项目实战学以致用当你的理论知识积累到一定程度就需要通过项目实战在实际操作中检验和巩固你所学到的知识同时为你找工作和职业发展打下坚实的基础。
大模型面试题面试不仅是技术的较量更需要充分的准备。
在你已经掌握了大模型技术之后就需要开始准备面试我们将提供精心整理的大模型面试题库涵盖当前面试中可能遇到的各种技术问题让你在面试中游刃有余。
因篇幅有限仅展示部分资料需要点击下方链接即可前往获取2025最新版CSDN大礼包《AGI大模型学习资源包》免费分享