【AI开发实践】LangChain开发AI Agent实操-Quick Start(3) | 系统提示词 | 工具封装 | 上下文 | 结构化返回 | 记忆体

张开发
2026/4/8 18:33:43 15 分钟阅读

分享文章

【AI开发实践】LangChain开发AI Agent实操-Quick Start(3) | 系统提示词 | 工具封装 | 上下文 | 结构化返回 | 记忆体
这是我们《AI开发实践》系列的第3篇,我们继续学习Langchain。上一次,我们只是创建了一个最简单的对话机器人, 严格来说,还不是一个Agent。本次我们将在上次的基础上,开发一个包括了完整的部件的Agent ,麻雀虽小,五脏俱全,让我们体验理解一下Agent有哪些必须的部件,这些部件有什么用,以及如何简单的使用。二、执行过程STEP1: 定义系统提示词大模型本身是无状态的,对它来说,每一次请求都是一个独立的请求。为了约束模型,Langchain提供了System Prompt, 设定了模型的“身份、规则和行为边界”,在每一次提交给模型用户问题时都添加上,保证模型输出的稳定性.SYSTEM_PROMPT = """ Actor: You are an expert weather forecaster, who speaks in puns. Tools: You have access to two tools: - get_weather_for_location: use this to get the weather for a specific location - get_user_location: use this to get the user's location Rules: - If a user asks you for the weather, make sure you know the location. - If you can tell from the question that they mean wherever they are, use the get_user_location tool to find their location. Others: - answer short and simply, no more than 50 chars - answer in Chinese"""这一段提示词,包括三个重要的部分:定义角色以及角色风格,“You are an expert weather forecaster” , 角色的风格“who speaks in puns”。 在大模型的Attention注意力机制中,Q(用户输入),K(用户输入词的向量标签)决定着V(输出)。通过将角色和角色风格编码为上下文中,会直接提升模型对这些输入的注意力权重,模型会优先关注与提示词语义相近(在多向量空间上计算)的训练语料。简单打个比方,这会过滤出来所有与forecaster expert , 以及 speaks in puns相关的语料,收缩了答案空间。定义工具及基本用途,如:“get_weather_for_location:use this to get the weather for a specific location”,“get_user_location: use this to get the user’s location”。这里通过{工具:描述}格式来定义。要注意:工具的名称,与实际定义的工具名称要严格一致, 保证模型能准确无误的生成规范的API tool call JSON语句, 本地程序在收到后,才能调用本地的工具。;定义如何使用工具,如:“- If a user asks you for the weather, make sure you know the location. ”,“If you can tell from the question that they mean wherever they are, use the get_user_location tool to find their location.” 系统提示词中的工具描述是工具的「使用手册」(调用条件、流程、规则),告诉模型工具该怎么用(什么时候要用,用完了该做什么,与其它的工具的配合关系)。可以通过{条件:行为} 添加规则去引导模型按一定的顺序执行。STEP2:创建工具Tool允许模型调用我们定义的函数,这样模型就可以调用现有的一些程序,实现与其它系统的交互。Tool的运行依赖于runtime context, 也能与agent memory 进行交互。下文实现上在提示词中述及的两个方法:from dataclasses import dataclass from langchain.tools import tool, ToolRuntime @tool def get_weather_for_location(city: str) - str: """Get weather for a given city.""" return f"It's always sunny in {city}!"

更多文章