按需加载技能构建SQL助手
该教程介绍用中间件把技能描述注入系统提示,由load_skill工具按需加载数据库模式,从而减少上下文占用并支持团队独立开发技能,同时说明按需加载会带来首次请求延迟。
此教程显示如何使用 **逐步披露** - 一种上下文管理技术,即代理人按需而不是按前置方式加载信息以实施 **技能** (专门的即时指令) 代理通过工具调用来加载技能,而不是动态地改变系统即时,只发现和加载每个任务所需的技能. **使用大小写 :** 想象一下,在大型企业中建立一个代理机构来帮助编写跨不同企业垂直的SQL查询。你的组织可能为每个垂直有单独的数据存储器,或者一个有数千个表格的单一的单一数据库。 无论如何,加载所有前置计划都会覆盖上下文窗口。 渐进的披露只通过在需要时加载相关的计划来解决。这种结构还使不同的产品所有人和利益攸关方能够独立贡献和维持其具体业务纵向技能。 **你们将构建的:** SQL 查询助理,具有两种技能(销售分析与库存管理). 代理在其系统中看到轻量级技能描述即时,然后通过工具调用在用户查询时才加载完整的数据库计划和业务逻辑。 完整的SQL代理实例包括查询执行、错误校正和验证,请参见我们 [SQL 代理教程](<https://docs.langchain.com/oss/python/langchain/sql-agent>)。该教程侧重于可适用于任何领域的渐进披露模式。 逐步披露被Anthropic普及为构建可伸缩代理技能系统的一种技术,这种方法使用三级架构(元数据 → 核心内容 → 详细资源),代理只按需要加载信息。关于这一技术的更多信息,请参见 [为现实世界配备特工技能](<https://www.anthropic.com/engineering/equipping-agents-for-the-real-world-with-agent-skills>). ## 如何运作 以下是用户询问 SQL 查询时的流程: **为何逐步披露:** - **减少上下文使用量** - 只装入任务所需的 2 - 3 技能,而非所有可用的技能 - **启用团队自主** - 不同的团队可以独立发展专业技能(类似于其他多代理架构). - **高效规模** - 增加数十或数百个技能,没有压倒性上下文 - **简化对话历史** - 只有一个对话线程的单一代理 **什么是技能:** Claude Code 所普及的技巧主要是即时的:特定业务任务专用指令的自成一体的单位. Claude Code 中,技能作为目录在文件系统中被曝光,通过文件操作发现. 技能通过提示指导行为,并且可以提供工具使用信息,或者包含编码代理执行的样本代码. 逐步披露的技能可被视为一种形式: [RAG(检索增强型)](<https://docs.langchain.com/oss/python/deepagents/rag>),其中每个技能是一个检索单元——虽然不一定有嵌入或关键字搜索的支持,而是有浏览内容的工具(如文件操作,或在此教程中直接查找). **权衡:** - **延迟**:按需装入技能需要额外的工具呼叫,这增加了第一个需要每种技能的请求的耐用性 - **工作流程控制**: 基本执行依赖于提示来指导技能使用 - 你不能强制硬约束,如“总是在技能B之前尝试技能A”而不习惯逻辑 **实施自己的技能系统**在建立自己的技能实施(如我们在本教程中所做的那样)时,核心概念是逐步披露——按需加载信息。除此之外,你在执行中具有充分的灵活性: - **储存**: 数据库, S3, 内存数据结构, 或任何后端 - **发现**: 直接查询( 此教程), 用于大型技能收藏的 RAG, 文件系统扫描, 或 API 呼叫 - **装入逻辑**:定制耐久特性,并增加逻辑,通过技能内容或排名关联性进行搜索 - **副作用**:定义技能负载时会发生什么,例如曝光与该技能相关的工具(涵盖在8部分). 这种灵活性使你能够优化自己在性能、存储和工作流程控制方面的具体要求。 ## 设置 ### 安装 此教程要求 `langchain` 软件包 : ``` pip install langchain ``` ``` uv add langchain ``` ``` conda install langchain -c conda-forge ``` 详细情况请见我们 [安装指南](<https://docs.langchain.com/oss/python/langchain/install>). ### LangSmith 设置 [LangSmith](<https://smith.langchain.com/?utm_source=docs&utm_medium=cta&utm_campaign=langsmith-signup&utm_content=oss-langchain-multi-agent-skills-sql-assistant>) 以检查您的代理服务器内发生的情况。然后设置以下环境变量: ``` export LANGSMITH_TRACING="true" export LANGSMITH_API_KEY="..." ``` ``` import getpass import os os.environ["LANGSMITH_TRACING"] = "true" os.environ["LANGSMITH_API_KEY"] = getpass.getpass() ``` ### 选择一个 LLM 从 LangChain 的整合套件中选择聊天模式 : - OpenAI - 人类 - 阿苏雷 - 谷歌双子座 - AWS 贝德洛克 - HuggingFace - OpenRouter 读吧 [OpenAI 聊天模式集成文件](<https://docs.langchain.com/oss/python/integrations/chat/openai/>) ``` pip install -U "langchain[openai]" ``` ``` uv add "langchain[openai]" ``` ``` import os from langchain.chat_models import init_chat_model os.environ["OPENAI_API_KEY"] = "sk-..." model = init_chat_model("gpt-6.1-sol") ``` ``` import os from langchain_openai import ChatOpenAI os.environ["OPENAI_API_KEY"] = "sk-..." model = ChatOpenAI(model="gpt-6.1-sol") ``` 读吧 [Anthropic 聊天模式集成文件](<https://docs.langchain.com/oss/python/integrations/chat/anthropic/>) ``` pip install -U "langchain[anthropic]" ``` ``` uv add "langchain[anthropic]" ``` ``` import os from langchain.chat_models import init_chat_model os.environ["ANTHROPIC_API_KEY"] = "sk-..." model = init_chat_model("claude-sonnet-4-6") ``` ``` import os from langchain_anthropic import ChatAnthropic os.environ["ANTHROPIC_API_KEY"] = "sk-..." model = ChatAnthropic(model="claude-sonnet-4-6") ``` 读吧 [Azure 聊天模式集成文件](<https://docs.langchain.com/oss/python/integrations/chat/azure_chat_openai/>) ``` pip install -U "langchain[openai]" ``` ``` uv add "langchain[openai]" ``` ``` import os from langchain.chat_models import init_chat_model os.environ["AZURE_OPENAI_API_KEY"] = "..." os.environ["AZURE_OPENAI_ENDPOINT"] = "..." os.environ["OPENAI_API_VERSION"] = "2025-03-01-preview" model = init_chat_model( "azure_openai:gpt-6.1-sol", azure_deployment=os.environ["AZURE_OPENAI_DEPLOYMENT_NAME"], ) ``` ``` import os from langchain_openai import AzureChatOpenAI os.environ["AZURE_OPENAI_API_KEY"] = "..." os.environ["AZURE_OPENAI_ENDPOINT"] = "..." os.environ["OPENAI_API_VERSION"] = "2025-03-01-preview" model = AzureChatOpenAI( model="gpt-6.1-sol", azure_deployment=os.environ["AZURE_OPENAI_DEPLOYMENT_NAME"] ) ``` 读吧 [Google GenAI 聊天模式集成文件](<https://docs.langchain.com/oss/python/integrations/chat/google_generative_ai/>) ``` pip install -U "langchain[google-genai]" ``` ``` uv add "langchain[google-genai]" ``` ``` import os from langchain.chat_models import init_chat_model os.environ["GOOGLE_API_KEY"] = "..." model = init_chat_model("google_genai:gemini-4-hydrogen") ``` ``` import os from langchain_google_genai import ChatGoogleGenerativeAI os.environ["GOOGLE_API_KEY"] = "..." model = ChatGoogleGenerativeAI(model="gemini-4-hydrogen") ``` 读吧 [AWS Bedrock 聊天模式集成文件](<https://docs.langchain.com/oss/python/integrations/chat/bedrock/>) ``` pip install -U "langchain[aws]" ``` ``` uv add "langchain[aws]" ``` ``` from langchain.chat_models import init_chat_model # Follow the steps here to configure your credentials: # https://docs.aws.amazon.com/bedrock/latest/userguide/getting-started.html model = init_chat_model( "us.anthropic.claude-sonnet-4-6", model_provider="bedrock_converse", ) ``` ``` from langchain_aws import ChatBedrock model = ChatBedrock(model="us.anthropic.claude-sonnet-4-6") ``` 读吧 [HuggingFace 聊天模式集成文件](<https://docs.langchain.com/oss/python/integrations/chat/huggingface/>) ``` pip install -U "langchain[huggingface]" ``` ``` uv add "langchain[huggingface]" ``` ``` import os from langchain.chat_models import init_chat_model os.environ["HUGGINGFACEHUB_API_TOKEN"] = "hf_..." model = init_chat_model( "microsoft/Phi-3-mini-4k-instruct", model_provider="huggingface", temperature=0.7, max_tokens=1024, ) ``` ``` import os from langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint os.environ["HUGGINGFACEHUB_API_TOKEN"] = "hf_..." llm = HuggingFaceEndpoint( repo_id="microsoft/Phi-3-mini-4k-instruct", temperature=0.7, max_length=1024, ) model = ChatHuggingFace(llm=llm) ``` 读吧 [OpenRouter 聊天模式集成文件](<https://docs.langchain.com/oss/python/integrations/chat/openrouter/>) ``` pip install -U "langchain-openrouter" ``` ``` uv add "langchain-openrouter" ``` ``` import os from langchain.chat_models import init_chat_model os.environ["OPENROUTER_API_KEY"] = "sk-..." model = init_chat_model( "auto", model_provider="openrouter", ) ``` ``` import os from langchain_openrouter import ChatOpenRouter os.environ["OPENROUTER_API_KEY"] = "sk-..." model = ChatOpenRouter(model="auto") ``` ## 1. 界定技能 首先,定义技能的结构。每个技能都有名称、简要说明(在系统上显示)和全部内容(按需加载): ``` from typing import TypedDict class Skill(TypedDict): """A skill that can be progressively disclosed to the agent.""" name: str # Unique identifier for the skill description: str # 1-2 sentence description to show in system prompt content: str # Full skill content with detailed instructions ``` 现在定义一个 SQL 查询助理的示例技能。这些技能被设计为 **说明中的轻量级** (向代理前倾斜) 但是 **详细内容** (仅在需要时才装入): 查看完整的技能定义 ``` SKILLS: list[Skill] = [ { "name": "sales_analytics", "description": "Database schema and business logic for sales data analysis including customers, orders, and revenue.", "content": """# Sales Analytics Schema ## Tables ### customers - customer_id (PRIMARY KEY) - name - email - signup_date - status (active/inactive) - customer_tier (bronze/silver/gold/platinum) ### orders - order_id (PRIMARY KEY) - customer_id (FOREIGN KEY -> customers) - order_date - status (pending/completed/cancelled/refunded) - total_amount - sales_region (north/south/east/west) ### order_items - item_id (PRIMARY KEY) - order_id (FOREIGN KEY -> orders) - product_id - quantity - unit_price - discount_percent ## Business Logic **Active customers**: status = 'active' AND signup_date <= CURRENT_DATE - INTERVAL '90 days' **Revenue calculation**: Only count orders with status = 'completed'. Use total_amount from orders table, which already accounts for discounts. **Customer lifetime value (CLV)**: Sum of all completed order amounts for a customer. **High-value orders**: Orders with total_amount > 1000 ## Example Query -- Get top 10 customers by revenue in the last quarter SELECT c.customer_id, c.name, c.customer_tier, SUM(o.total_amount) as total_revenue FROM customers c JOIN orders o ON c.customer_id = o.customer_id WHERE o.status = 'completed' AND o.order_date >= CURRENT_DATE - INTERVAL '3 months' GROUP BY c.customer_id, c.name, c.customer_tier ORDER BY total_revenue DESC LIMIT 10; """, }, { "name": "inventory_management", "description": "Database schema and business logic for inventory tracking including products, warehouses, and stock levels.", "content": """# Inventory Management Schema ## Tables ### products - product_id (PRIMARY KEY) - product_name - sku - category - unit_cost - reorder_point (minimum stock level before reordering) - discontinued (boolean) ### warehouses - warehouse_id (PRIMARY KEY) - warehouse_name - location - capacity ### inventory - inventory_id (PRIMARY KEY) - product_id (FOREIGN KEY -> products) - warehouse_id (FOREIGN KEY -> warehouses) - quantity_on_hand - last_updated ### stock_movements - movement_id (PRIMARY KEY) - product_id (FOREIGN KEY -> products) - warehouse_id (FOREIGN KEY -> warehouses) - movement_type (inbound/outbound/transfer/adjustment) - quantity (positive for inbound, negative for outbound) - movement_date - reference_number ## Business Logic **Available stock**: quantity_on_hand from inventory table where quantity_on_hand > 0 **Products needing reorder**: Products where total quantity_on_hand across all warehouses is less than or equal to the product's reorder_point **Active products only**: Exclude products where discontinued = true unless specifically analyzing discontinued items **Stock valuation**: quantity_on_hand * unit_cost for each product ## Example Query -- Find products below reorder point across all warehouses SELECT p.product_id, p.product_name, p.reorder_point, SUM(i.quantity_on_hand) as total_stock, p.unit_cost, (p.reorder_point - SUM(i.quantity_on_hand)) as units_to_reorder FROM products p JOIN inventory i ON p.product_id = i.product_id WHERE p.discontinued = false GROUP BY p.product_id, p.product_name, p.reorder_point, p.unit_cost HAVING SUM(i.quantity_on_hand) <= p.reorder_point ORDER BY units_to_reorder DESC; """, }, ] ``` ## 2. 创建技能加载工具 创建一个工具来按需装入全部技能内容 : ``` from langchain.tools import tool @tool def load_skill(skill_name: str) -> str: """Load the full content of a skill into the agent's context. Use this when you need detailed information about how to handle a specific type of request. This will provide you with comprehensive instructions, policies, and guidelines for the skill area. Args: skill_name: The name of the skill to load (e.g., "expense_reporting", "travel_booking") """ # Find and return the requested skill for skill in SKILLS: if skill["name"] == skill_name: return f"Loaded skill: {skill_name}\n\n{skill['content']}" # Skill not found available = ", ".join(s["name"] for s in SKILLS) return f"Skill '{skill_name}' not found. Available skills: {available}" ``` 那个... `load_skill` 工具以字符串的形式返回全部技能内容,它作为 ToolMessage 成为对话的一部分。关于创建和使用工具的详情,请参见 [工具指南](<https://docs.langchain.com/oss/python/langchain/tools>). ## 3. 构建技能中间软件 创建自定义的中间软件, 将技能描述输入系统提示。 此中间软件使技能可以在不将全部内容加载的情况下发现 。 本指南演示了自定义中间软件的创建。关于中间软件概念和模式的综合指南,请参见: [自定义中间软件文档](<https://docs.langchain.com/oss/python/langchain/middleware/custom>). ``` from langchain.agents.middleware import ModelRequest, ModelResponse, AgentMiddleware from langchain.messages import SystemMessage from typing import Callable class SkillMiddleware(AgentMiddleware): """Middleware that injects skill descriptions into the system prompt.""" # Register the load_skill tool as a class variable tools = [load_skill] def __init__(self): """Initialize and generate the skills prompt from SKILLS.""" # Build skills prompt from the SKILLS list skills_list = [] for skill in SKILLS: skills_list.append( f"- **{skill['name']}**: {skill['description']}" ) self.skills_prompt = "\n".join(skills_list) def wrap_model_call( self, request: ModelRequest, handler: Callable[[ModelRequest], ModelResponse], ) -> ModelResponse: """Sync: Inject skill descriptions into system prompt.""" # Build the skills addendum skills_addendum = ( f"\n\n## Available Skills\n\n{self.skills_prompt}\n\n" "Use the load_skill tool when you need detailed information " "about handling a specific type of request." ) # Append to system message content blocks new_content = list(request.system_message.content_blocks) + [ {"type": "text", "text": skills_addendum} ] new_system_message = SystemMessage(content=new_content) modified_request = request.override(system_message=new_system_message) return handler(modified_request) ``` 中间软件将技能描述附加到系统上, 使代理商在不装满其全部内容的情况下, 了解可用的技能 。 `load_skill` 工具被登记为类变量,使其提供给代理。 **生产考虑**: 此教程加载技能列表 `__init__` 在生产系统中,你可能想要在生产系统中装入技能 `before_agent` 钩子,允许它们定期刷新以反映up-to-date的更改(例如,在添加新技能或修改现有技能时)。 [before_agent 钩文件](<https://docs.langchain.com/oss/python/langchain/middleware/custom#node-style-hooks>) 详细情况。 ## 4. 以技能支持创建代理 现在用技术中间器件创建代理, 并设置一个状态持续状态检查器 : ``` from langchain.agents import create_agent from langgraph.checkpoint.memory import InMemorySaver # Create the agent with skill support agent = create_agent( model, system_prompt=( "You are a SQL query assistant that helps users " "write queries against business databases." ), middleware=[SkillMiddleware()], checkpointer=InMemorySaver(), ) ``` 特工现在可以及时获得系统内的技能描述,并可以打电话 `load_skill` 当需要时, 检查器会保存所有的技能内容。 检查器会保持相互间的对话历史 。 ## 5. 测试渐进披露 用一个需要特定技能知识的问题测试代理商: ``` from langchain_core.utils.uuid import uuid7 # Configuration for this conversation thread thread_id = str(uuid7()) config = {"configurable": {"thread_id": thread_id}} # Ask for a SQL query result = agent.invoke( { "messages": [ { "role": "user", "content": ( "Write a SQL query to find all customers " "who made orders over $1000 in the last month" ), } ] }, config ) # Print the conversation for message in result["messages"]: if hasattr(message, 'pretty_print'): message.pretty_print() else: print(f"{message.type}: {message.content}") ``` 预期产出: ``` ================================ Human Message ================================= Write a SQL query to find all customers who made orders over $1000 in the last month ================================== Ai Message ================================== Tool Calls: load_skill (call_abc123) Call ID: call_abc123 Args: skill_name: sales_analytics ================================= Tool Message ================================= Name: load_skill Loaded skill: sales_analytics # Sales Analytics Schema ## Tables ### customers - customer_id (PRIMARY KEY) - name - email - signup_date - status (active/inactive) - customer_tier (bronze/silver/gold/platinum) ### orders - order_id (PRIMARY KEY) - customer_id (FOREIGN KEY -> customers) - order_date - status (pending/completed/cancelled/refunded) - total_amount - sales_region (north/south/east/west) [... rest of schema ...] ## Business Logic **High-value orders**: Orders with `total_amount > 1000` **Revenue calculation**: Only count orders with `status = 'completed'` ================================== Ai Message ================================== Here's a SQL query to find all customers who made orders over $1000 in the last month: \`\`\`sql SELECT DISTINCT c.customer_id, c.name, c.email, c.customer_tier FROM customers c JOIN orders o ON c.customer_id = o.customer_id WHERE o.total_amount > 1000 AND o.status = 'completed' AND o.order_date >= CURRENT_DATE - INTERVAL '1 month' ORDER BY c.customer_id; \`\`\` This query: - Joins customers with their orders - Filters for high-value orders (>$1000) using the total_amount field - Only includes completed orders (as per the business logic) - Restricts to orders from the last month - Returns distinct customers to avoid duplicates if they made multiple qualifying orders ``` 代理商看到其系统中的轻量级技能描述迅速,认识到问题需要销售数据库知识,称为: `load_skill("sales_analytics")` 以获得完整的计划和商业逻辑,然后使用该信息在数据库常规之后写出正确的查询。 ## 6. 高级: 添加自定义状态的制约 可选: 跟踪加载技能和强制工具约束 您可以添加限制, 强制执行某些工具只能在特定技能被装入后才能使用。 这需要跟踪哪些技能已经在自定义代理状态中装入 。 ### 定义自定义状态 首先, 扩展代理状态以跟踪加载的技能 : ``` from langchain.agents.middleware import AgentState class CustomState(AgentState): skills_loaded: NotRequired[list[str]] # Track which skills have been loaded ``` ### 更新 load_skill 以修改状态 修改 `load_skill` 用于在技能装入时更新状态的工具 : ``` from langgraph.types import Command from langchain.tools import tool, ToolRuntime from langchain.messages import ToolMessage @tool def load_skill(skill_name: str, runtime: ToolRuntime) -> Command: """Load the full content of a skill into the agent's context. Use this when you need detailed information about how to handle a specific type of request. This will provide you with comprehensive instructions, policies, and guidelines for the skill area. Args: skill_name: The name of the skill to load """ # Find and return the requested skill for skill in SKILLS: if skill["name"] == skill_name: skill_content = f"Loaded skill: {skill_name}\n\n{skill['content']}" # Update state to track loaded skill return Command( update={ "messages": [ ToolMessage( content=skill_content, tool_call_id=runtime.tool_call_id, ) ], "skills_loaded": [skill_name], } ) # Skill not found available = ", ".join(s["name"] for s in SKILLS) return Command( update={ "messages": [ ToolMessage( content=f"Skill '{skill_name}' not found. Available skills: {available}", tool_call_id=runtime.tool_call_id, ) ] } ) ``` ### 创建受限制的工具 创建一个只能在特定技能装入后才能使用的工具 : ```` @tool def write_sql_query( query: str, vertical: str, runtime: ToolRuntime, ) -> str: """Write and validate a SQL query for a specific business vertical. This tool helps format and validate SQL queries. You must load the appropriate skill first to understand the database schema. Args: query: The SQL query to write vertical: The business vertical (sales_analytics or inventory_management) """ # Check if the required skill has been loaded skills_loaded = runtime.state.get("skills_loaded", []) if vertical not in skills_loaded: return ( f"Error: You must load the '{vertical}' skill first " f"to understand the database schema before writing queries. " f"Use load_skill('{vertical}') to load the schema." ) # Validate and format the query return ( f"SQL Query for {vertical}:\n\n" f"```sql\n{query}\n```\n\n" f"✓ Query validated against {vertical} schema\n" f"Ready to execute against the database." ) ```` ### 更新中间软件和代理 更新中间软件以使用自定义状态计划 : ``` class SkillMiddleware(AgentMiddleware[CustomState]): """Middleware that injects skill descriptions into the system prompt.""" state_schema = CustomState tools = [load_skill, write_sql_query] # ... rest of the middleware implementation stays the same ``` 使用注册受限制工具的中间软件创建代理 : ``` agent = create_agent( model, system_prompt=( "You are a SQL query assistant that helps users " "write queries against business databases." ), middleware=[SkillMiddleware()], checkpointer=InMemorySaver(), ) ``` 现在,如果代理试图使用 `write_sql_query` 在装入所需技能之前,它会收到一个错误消息,提醒它装入适当的技能(例如, `sales_analytics` 或 时 间 `inventory_management`首先,这确保代理人在试图验证查询之前具备必要的计划知识。 ## 完整实例 查看完整的可运行脚本 以下是一个完整、可运行的执行, 结合了这个教程中的所有部分: ``` from langchain_core.utils.uuid import uuid7 from typing import TypedDict, NotRequired from langchain.tools import tool from langchain.agents import create_agent from langchain.agents.middleware import ModelRequest, ModelResponse, AgentMiddleware from langchain.messages import SystemMessage from langgraph.checkpoint.memory import InMemorySaver from typing import Callable # Define skill structure class Skill(TypedDict): """A skill that can be progressively disclosed to the agent.""" name: str description: str content: str # Define skills with schemas and business logic SKILLS: list[Skill] = [ { "name": "sales_analytics", "description": "Database schema and business logic for sales data analysis including customers, orders, and revenue.", "content": """# Sales Analytics Schema ## Tables ### customers - customer_id (PRIMARY KEY) - name - email - signup_date - status (active/inactive) - customer_tier (bronze/silver/gold/platinum) ### orders - order_id (PRIMARY KEY) - customer_id (FOREIGN KEY -> customers) - order_date - status (pending/completed/cancelled/refunded) - total_amount - sales_region (north/south/east/west) ### order_items - item_id (PRIMARY KEY) - order_id (FOREIGN KEY -> orders) - product_id - quantity - unit_price - discount_percent ## Business Logic **Active customers**: status = 'active' AND signup_date <= CURRENT_DATE - INTERVAL '90 days' **Revenue calculation**: Only count orders with status = 'completed'. Use total_amount from orders table, which already accounts for discounts. **Customer lifetime value (CLV)**: Sum of all completed order amounts for a customer. **High-value orders**: Orders with total_amount > 1000 ## Example Query -- Get top 10 customers by revenue in the last quarter SELECT c.customer_id, c.name, c.customer_tier, SUM(o.total_amount) as total_revenue FROM customers c JOIN orders o ON c.customer_id = o.customer_id WHERE o.status = 'completed' AND o.order_date >= CURRENT_DATE - INTERVAL '3 months' GROUP BY c.customer_id, c.name, c.customer_tier ORDER BY total_revenue DESC LIMIT 10; """, }, { "name": "inventory_management", "description": "Database schema and business logic for inventory tracking including products, warehouses, and stock levels.", "content": """# Inventory Management Schema ## Tables ### products - product_id (PRIMARY KEY) - product_name - sku - category - unit_cost - reorder_point (minimum stock level before reordering) - discontinued (boolean) ### warehouses - warehouse_id (PRIMARY KEY) - warehouse_name - location - capacity ### inventory - inventory_id (PRIMARY KEY) - product_id (FOREIGN KEY -> products) - warehouse_id (FOREIGN KEY -> warehouses) - quantity_on_hand - last_updated ### stock_movements - movement_id (PRIMARY KEY) - product_id (FOREIGN KEY -> products) - warehouse_id (FOREIGN KEY -> warehouses) - movement_type (inbound/outbound/transfer/adjustment) - quantity (positive for inbound, negative for outbound) - movement_date - reference_number ## Business Logic **Available stock**: quantity_on_hand from inventory table where quantity_on_hand > 0 **Products needing reorder**: Products where total quantity_on_hand across all warehouses is less than or equal to the product's reorder_point **Active products only**: Exclude products where discontinued = true unless specifically analyzing discontinued items **Stock valuation**: quantity_on_hand * unit_cost for each product ## Example Query -- Find products below reorder point across all warehouses SELECT p.product_id, p.product_name, p.reorder_point, SUM(i.quantity_on_hand) as total_stock, p.unit_cost, (p.reorder_point - SUM(i.quantity_on_hand)) as units_to_reorder FROM products p JOIN inventory i ON p.product_id = i.product_id WHERE p.discontinued = false GROUP BY p.product_id, p.product_name, p.reorder_point, p.unit_cost HAVING SUM(i.quantity_on_hand) <= p.reorder_point ORDER BY units_to_reorder DESC; """, }, ] # Create skill loading tool @tool def load_skill(skill_name: str) -> str: """Load the full content of a skill into the agent's context. Use this when you need detailed information about how to handle a specific type of request. This will provide you with comprehensive instructions, policies, and guidelines for the skill area. Args: skill_name: The name of the skill to load (e.g., "sales_analytics", "inventory_management") """ # Find and return the requested skill for skill in SKILLS: if skill["name"] == skill_name: return f"Loaded skill: {skill_name}\n\n{skill['content']}" # Skill not found available = ", ".join(s["name"] for s in SKILLS) return f"Skill '{skill_name}' not found. Available skills: {available}" # Create skill middleware class SkillMiddleware(AgentMiddleware): """Middleware that injects skill descriptions into the system prompt.""" # Register the load_skill tool as a class variable tools = [load_skill] def __init__(self): """Initialize and generate the skills prompt from SKILLS.""" # Build skills prompt from the SKILLS list skills_list = [] for skill in SKILLS: skills_list.append( f"- **{skill['name']}**: {skill['description']}" ) self.skills_prompt = "\n".join(skills_list) def wrap_model_call( self, request: ModelRequest, handler: Callable[[ModelRequest], ModelResponse], ) -> ModelResponse: """Sync: Inject skill descriptions into system prompt.""" # Build the skills addendum skills_addendum = ( f"\n\n## Available Skills\n\n{self.skills_prompt}\n\n" "Use the load_skill tool when you need detailed information " "about handling a specific type of request." ) # Append to system message content blocks new_content = list(request.system_message.content_blocks) + [ {"type": "text", "text": skills_addendum} ] new_system_message = SystemMessage(content=new_content) modified_request = request.override(system_message=new_system_message) return handler(modified_request) # Initialize your chat model (replace with your model) # Example: from langchain_anthropic import ChatAnthropic # model = ChatAnthropic(model="claude-sonnet-4-6") from langchain_openai import ChatOpenAI model = ChatOpenAI(model="gpt-6.1-sol") # Create the agent with skill support agent = create_agent( model, system_prompt=( "You are a SQL query assistant that helps users " "write queries against business databases." ), middleware=[SkillMiddleware()], checkpointer=InMemorySaver(), ) # Example usage if __name__ == "__main__": # Configuration for this conversation thread thread_id = str(uuid7()) config = {"configurable": {"thread_id": thread_id}} # Ask for a SQL query result = agent.invoke( { "messages": [ { "role": "user", "content": ( "Write a SQL query to find all customers " "who made orders over $1000 in the last month" ), } ] }, config ) # Print the conversation for message in result["messages"]: if hasattr(message, 'pretty_print'): message.pretty_print() else: print(f"{message.type}: {message.content}") ``` 这一完整的例子包括: - 具有完整数据库计划的技能定义 - 那个... `load_skill` 供按需加载的工具 - `SkillMiddleware` 将技能描述输入系统时提示 - 用中间软件和检查器创建代理程序 - 显示代理机如何装入技能和写入 SQL 查询的示例用法 要运行此程序,您需要: 1. 安装所需的软件包 : `pip install langchain langchain-openai langgraph` 2. 设置您的 API 密钥( 例如 ) `export OPENAI_API_KEY=...`) 3. 将模型初始化替换为您首选的 LLM 提供者 ## 执行变化 查看执行备选方案和权衡 通过工具调用加载的内嵌 Python 词典中这种已执行的教学技能。 但是,有几种方法可以使用技能进行渐进的披露:**存储后端 :** - **记忆** (此教程):技能定义为 Python 数据结构, 快速访问, 无 I/ O 间接费用 - **文件系统** (Claude Code 方法): 技能作为文件目录, 通过文件操作发现, 如 `read_file` - **远程存储**: 在 S3 、 数据库、 逗号或 API 中的技能,按需获取 **技术发现** (经纪人如何学习哪些技能): - **系统即时上市**: 系统提示中的技能描述(在本教程中使用) - **基于文件**:通过扫描目录发现技能(Claude Code 方法) - **书记官处**:查询技能注册服务或可用技能的API - **动态查询**: 通过工具调用列出可用的技能 **逐步披露战略** (技能内容如何加载): - **单项负载**: 将全部技能内容装入一个工具调用( 用于此教程) - **标注**: 将技能内容装入多页/圆箱中,用于大技能 - **基于搜索**: 在一个特定技能内容内搜索相关部分(例如,在技能文件中使用grep/读取操作) - **等级**:先装入技能概览,然后钻入特定小节 **大小考虑** (未校准的心理模型 - 优化您的系统): - **小型技能** ( < 1K 令牌 / ~ 750 单词):可以直接包含在系统即时和缓存中,并及时缓存以节省成本和更快的响应 - **中等技能** (1 - 10K 令牌 / ~ 750 - 7.5K 单词):从点播加载中受益,以避免上下文(本教程) - **高技能** ( > 10K 令牌 / ~ 7.5K 单词, 或 > 5 - 上下文窗口的 10% ): 应使用渐进的披露技术,如页标、基于搜索的加载或分级探索,以避免消耗过多的上下文 选择取决于你的要求:内存最快,但需要重新调配技能更新,而基于文件或远程存储则可以在不更改代码的情况下进行动态技能管理. ## 逐步披露和背景工程 与几发催泪弹和其他技术相结合 逐步披露从根本上讲是 **[环境工程](<https://docs.langchain.com/oss/python/langchain/context-engineering>) 技术** - 您正在管理代理商可得到的信息和时间。此教程侧重于装入数据库计划,但同样的原则适用于其他类型的上下文。 ### 与少发提示相结合 对于 SQL 查询使用大小写,您可以将渐进披露扩展为动态加载 **少镜头示例** 匹配用户查询的:**实例办法:** 1. 用户问道:“寻找在6月未订购的客户”。 2. 代理负载 `sales_analytics` schema( 如此教程所示) 3. 代理也加载 2 - 3 相关实例查询(通过语义搜索或基于标记的查询) : - 查找不活动客户的查询 - 使用日期过滤查询 - 查询客户和订单表 4. Agent 使用两种计划知识 AND 实例模式编写查询 渐进的披露(按需加载计数)和动态的几发提示(加载相关实例)相结合,形成了强大的上下文工程模式,在提供高质量、有根据的产出的同时,将规模扩大到大型知识基地。 ## 今后的步骤 - 学习关于 [中间软件](<https://docs.langchain.com/oss/python/langchain/middleware>) 用于更动态的代理行为 - 探索 [环境工程](<https://docs.langchain.com/oss/python/langchain/context-engineering>) 管理代理商的技术背景 - 探索 [交割模式](<https://docs.langchain.com/oss/python/langchain/multi-agent/handoffs-customer-support>) 用于顺序工作流程 - 读读 [子剂图案](<https://docs.langchain.com/oss/python/langchain/multi-agent/subagents-personal-assistant>) 用于并行任务路径 - 见 [多剂模式](<https://docs.langchain.com/oss/python/langchain/multi-agent>) 对专门机构采取的其他办法 - 使用( U) [LangSmith](<https://smith.langchain.com/?utm_source=docs&utm_medium=cta&utm_campaign=langsmith-signup&utm_content=oss-langchain-multi-agent-skills-sql-assistant>) 调试并监视技能加载 --- [连接这些文件](<https://docs.langchain.com/use-these-docs>) 通过 MCP 向您选择的代理提供实时答案。 [在 GitHub 上编辑此页面](<https://github.com/langchain-ai/docs/edit/main/src/oss/langchain/multi-agent/skills-sql-assistant.mdx>) 或 时 间 [提交一个问题](<https://github.com/langchain-ai/docs/issues/new/choose>). 这页有用吗?
查看原始来源