Skip to main content

概述

LangChain的createAgent在LangGraph的运行时下运行。 LangGraph公开了一个运行时对象,其中包含以下信息:
  1. 上下文:智能体调用所需的静态信息,如用户ID、数据库连接或其他依赖项
  2. 存储:用于长期记忆BaseStore实例
  3. 流写入器:用于通过"custom"流模式传输信息的对象
您可以在工具中间件中访问运行时信息。

访问

在创建具有 createAgent 的智能体时,您可以指定一个 contextSchema 来定义存储在智能体 运行时 中的 context 的结构。 在调用智能体时,传递 context 参数并包含运行的相关配置:
import * as z from "zod";
import { createAgent } from "langchain";

const contextSchema = z.object({ 
  userName: z.string(), 
}); 

const agent = createAgent({
  model: "openai:gpt-4o",
  tools: [
    /* ... */
  ],
  contextSchema, 
});

const result = await agent.invoke(
  { messages: [{ role: "user", content: "What's my name?" }] },
  { context: { userName: "John Smith" } } 
);

工具内部

您可以在工具内访问运行时信息以:
  • 访问上下文
  • 读取或写入长期记忆
  • 写入到自定义流(例如,工具进度/更新)
使用 runtime 参数访问工具内部的 运行时 对象。
import * as z from "zod";
import { tool } from "langchain";
import { type Runtime } from "@langchain/langgraph"; 

const contextSchema = z.object({
  userName: z.string(),
});

const fetchUserEmailPreferences = tool(
  async (_, runtime: Runtime<z.infer<typeof contextSchema>>) => { 
    const userName = runtime.context?.userName; 
    if (!userName) {
      throw new Error("userName is required");
    }

    let preferences = "The user prefers you to write a brief and polite email.";
    if (runtime.store) { 
      const memory = await runtime.store?.get(["users"], userName); 
      if (memory) {
        preferences = memory.value.preferences;
      }
    }
    return preferences;
  },
  {
    name: "fetch_user_email_preferences",
    description: "Fetch the user's email preferences.",
    schema: z.object({}),
  }
);

中间件内部

您可以在中间件中访问运行时信息,以创建动态提示、修改消息或根据用户上下文控制智能体行为。 使用 runtime 参数访问中间件内的 运行时 对象。
import * as z from "zod";
import { createAgent, createMiddleware, type AgentState, SystemMessage } from "langchain";
import { type Runtime } from "@langchain/langgraph"; 

const contextSchema = z.object({
  userName: z.string(),
});

// Dynamic prompt middleware
const dynamicPromptMiddleware = createMiddleware({
  name: "DynamicPrompt",
  beforeModel: (state: AgentState, runtime: Runtime<z.infer<typeof contextSchema>>) => {  
    const userName = runtime.context?.userName;  
    if (!userName) {
      throw new Error("userName is required");
    }

    const systemMsg = `You are a helpful assistant. Address the user as ${userName}.`;
    return {
      messages: [new SystemMessage(systemMsg), ...state.messages]
    };
  }
});

// Logging middleware
const loggingMiddleware = createMiddleware({
  name: "Logging",
  beforeModel: (state: AgentState, runtime: Runtime<z.infer<typeof contextSchema>>) => {  
    console.log(`Processing request for user: ${runtime.context?.userName}`);  
    return;
  },
  afterModel: (state: AgentState, runtime: Runtime<z.infer<typeof contextSchema>>) => {  
    console.log(`Completed request for user: ${runtime.context?.userName}`);  
    return;
  }
});

const agent = createAgent({
  model: "openai:gpt-4o",
  tools: [
    /* ... */
  ],
  middleware: [dynamicPromptMiddleware, loggingMiddleware],  
  contextSchema,
});

const result = await agent.invoke(
  { messages: [{ role: "user", content: "What's my name?" }] },
  { context: { userName: "John Smith" } }
);