跳转到内容
搜索文档

获取当前 Agent

最后更新 查看 MarkdownAgent 设置

getCurrentAgent() 函数允许你从代码任意位置(包括外部工具函数和库)访问当前 Agent 上下文。当你需要在无法直接访问 this 的函数中获取 Agent 信息时,这很有用。

自定义方法的自动上下文

框架在初始化期间检测并包装自定义 Agent 方法,使 getCurrentAgent() 能在这些方法及其调用的函数内解析活动 Agent。

工作原理

import { AIChatAgent } from "@cloudflare/ai-chat";
import { getCurrentAgent } from "agents";

export class MyAgent extends AIChatAgent {
	async customMethod() {
		const { agent } = getCurrentAgent();
		// agent is automatically available
		console.log(agent.name);
	}

	async anotherMethod() {
		// This works too - no setup needed
		const { agent } = getCurrentAgent();
		return agent.state;
	}
}
import { AIChatAgent } from "@cloudflare/ai-chat";
import { getCurrentAgent } from "agents";

export class MyAgent extends AIChatAgent {
	async customMethod() {
		const { agent } = getCurrentAgent();
		// agent is automatically available
		console.log(agent.name);
	}

	async anotherMethod() {
		// This works too - no setup needed
		const { agent } = getCurrentAgent();
		return agent.state;
	}
}

无需配置。框架自动:

  1. 扫描 Agent 类中的自定义方法。
  2. 在初始化期间用 Agent 上下文包装它们。
  3. 确保 getCurrentAgent() 在从方法调用的所有外部函数中可用。

真实场景示例

import { AIChatAgent } from "@cloudflare/ai-chat";
import { getCurrentAgent } from "agents";
import { generateText } from "ai";
import { openai } from "@ai-sdk/openai";

// External utility function that needs agent context
async function processWithAI(prompt) {
	const { agent } = getCurrentAgent();
	// External functions can access the current agent

	return await generateText({
		model: openai("gpt-4"),
		prompt: `Agent ${agent?.name}: ${prompt}`,
	});
}

export class MyAgent extends AIChatAgent {
	async customMethod(message) {
		// Use this.* to access agent properties directly
		console.log("Agent name:", this.name);
		console.log("Agent state:", this.state);

		// External functions automatically work
		const result = await processWithAI(message);
		return result.text;
	}
}
import { AIChatAgent } from "@cloudflare/ai-chat";
import { getCurrentAgent } from "agents";
import { generateText } from "ai";
import { openai } from "@ai-sdk/openai";

// External utility function that needs agent context
async function processWithAI(prompt: string) {
	const { agent } = getCurrentAgent();
	// External functions can access the current agent

	return await generateText({
		model: openai("gpt-4"),
		prompt: `Agent ${agent?.name}: ${prompt}`,
	});
}

export class MyAgent extends AIChatAgent {
	async customMethod(message: string) {
		// Use this.* to access agent properties directly
		console.log("Agent name:", this.name);
		console.log("Agent state:", this.state);

		// External functions automatically work
		const result = await processWithAI(message);
		return result.text;
	}
}

内置方法与自定义方法

  • 内置方法onRequestonEmailonStateChanged):已有上下文。
  • 自定义方法(你的方法):初始化期间自动包装。
  • 外部函数:通过 getCurrentAgent() 访问上下文。

上下文流

// When you call a custom method:
agent.customMethod();
// → automatically wrapped with agentContext.run()
// → your method executes with full context
// → external functions can use getCurrentAgent()
// When you call a custom method:
agent.customMethod();
// → automatically wrapped with agentContext.run()
// → your method executes with full context
// → external functions can use getCurrentAgent()

常见用例

使用 AI SDK 工具

import { AIChatAgent } from "@cloudflare/ai-chat";
import { generateText } from "ai";
import { openai } from "@ai-sdk/openai";

export class MyAgent extends AIChatAgent {
	async generateResponse(prompt) {
		// AI SDK tools automatically work
		const response = await generateText({
			model: openai("gpt-4"),
			prompt,
			tools: {
				// Tools that use getCurrentAgent() work perfectly
			},
		});

		return response.text;
	}
}
import { AIChatAgent } from "@cloudflare/ai-chat";
import { generateText } from "ai";
import { openai } from "@ai-sdk/openai";

export class MyAgent extends AIChatAgent {
	async generateResponse(prompt: string) {
		// AI SDK tools automatically work
		const response = await generateText({
			model: openai("gpt-4"),
			prompt,
			tools: {
				// Tools that use getCurrentAgent() work perfectly
			},
		});

		return response.text;
	}
}

调用外部库

import { AIChatAgent } from "@cloudflare/ai-chat";
import { getCurrentAgent } from "agents";

async function saveToDatabase(data) {
	const { agent } = getCurrentAgent();
	// Can access agent info for logging, context, etc.
	console.log(`Saving data for agent: ${agent?.name}`);
}

export class MyAgent extends AIChatAgent {
	async processData(data) {
		// External functions automatically have context
		await saveToDatabase(data);
	}
}
import { AIChatAgent } from "@cloudflare/ai-chat";
import { getCurrentAgent } from "agents";

async function saveToDatabase(data: any) {
	const { agent } = getCurrentAgent();
	// Can access agent info for logging, context, etc.
	console.log(`Saving data for agent: ${agent?.name}`);
}

export class MyAgent extends AIChatAgent {
	async processData(data: any) {
		// External functions automatically have context
		await saveToDatabase(data);
	}
}

访问请求和连接上下文

import { getCurrentAgent } from "agents";

function logRequestInfo() {
	const { agent, connection, request } = getCurrentAgent();

	if (request) {
		console.log("Request URL:", request.url);
		console.log("Request method:", request.method);
	}

	if (connection) {
		console.log("Connection ID:", connection.id);
	}
}
import { getCurrentAgent } from "agents";

function logRequestInfo() {
	const { agent, connection, request } = getCurrentAgent();

	if (request) {
		console.log("Request URL:", request.url);
		console.log("Request method:", request.method);
	}

	if (connection) {
		console.log("Connection ID:", connection.id);
	}
}

何时丢失上下文

Agent 上下文仅沿原始调用的调用树传播。在该调用树之外到达的代码以空上下文开始,因此 getCurrentAgent() 返回各字段为 undefined 的对象。常见情况包括:

  • 通过 Worker Loader 子 isolate 的 RPC 调用的宿主回调,例如沙箱化 Codemode execution;
  • service binding 或 Durable Object RPC 入口点;
  • 保留 Agent 引用的 queue consumer 或其他入口点。

将回调路由到 Agent 上的公共方法。自定义方法自动包装,因此调用 agent.someMethod() 会重新进入该 Agent 的上下文:

import { RpcTarget } from "cloudflare:workers";

class HostCallbackBridge extends RpcTarget {
	agent;

	constructor(agent) {
		super();
		this.agent = agent;
	}

	// Invoked through RPC from a Worker Loader child isolate. There is no context
	// ancestry. Calling a public agent method restores it automatically.
	async invoke() {
		return this.agent.handleSandboxCallback();
	}
}

export class MyMcpAgent extends McpAgent {
	async handleSandboxCallback() {
		const { agent } = getCurrentAgent();
		// `agent` is available again.
	}
}
import { RpcTarget } from "cloudflare:workers";

class HostCallbackBridge extends RpcTarget {
	agent: MyMcpAgent;

	constructor(agent: MyMcpAgent) {
		super();
		this.agent = agent;
	}

	// Invoked through RPC from a Worker Loader child isolate. There is no context
	// ancestry. Calling a public agent method restores it automatically.
	async invoke() {
		return this.agent.handleSandboxCallback();
	}
}

export class MyMcpAgent extends McpAgent {
	async handleSandboxCallback() {
		const { agent } = getCurrentAgent<MyMcpAgent>();
		// `agent` is available again.
	}
}

以此方式恢复的上下文中 connectionrequestemail 未设置。它不绑定到实时客户端 I/O。

McpAgent 上的服务端发起 MCP 请求(elicitInputcreateMessagelistRoots)不需要此间接方式,因为 MCP 传输保留其所属 Agent。

API 参考

getCurrentAgent()

从任何可用上下文中获取当前 Agent。

import { getCurrentAgent } from "agents";
import { getCurrentAgent } from "agents";

function getCurrentAgent<T extends Agent>(): {
	agent: T | undefined;
	connection: Connection | undefined;
	request: Request | undefined;
	email: AgentEmail | undefined;
};

返回值:

属性 类型 描述
agent T | undefined 当前 Agent 实例
connection Connection | undefined WebSocket 连接(若从 WebSocket handler 调用)
request Request | undefined HTTP 请求(若从 request handler 调用)
email AgentEmail | undefined 邮件(若从 email handler 调用)

用法:

import { AIChatAgent } from "@cloudflare/ai-chat";
import { getCurrentAgent } from "agents";

export class MyAgent extends AIChatAgent {
	async customMethod() {
		const { agent, connection, request } = getCurrentAgent();
		// agent is properly typed as MyAgent
		// connection and request available if called from a request handler
	}
}
import { AIChatAgent } from "@cloudflare/ai-chat";
import { getCurrentAgent } from "agents";

export class MyAgent extends AIChatAgent {
	async customMethod() {
		const { agent, connection, request } = getCurrentAgent<MyAgent>();
		// agent is properly typed as MyAgent
		// connection and request available if called from a request handler
	}
}

上下文可用性

可用上下文取决于方法的调用方式:

调用 agent connection request email
onRequest()
onConnect()
onMessage()
onEmail()
自定义方法(通过 RPC)
调度任务
Queue 回调 视情况 视情况 视情况

最佳实践

  1. 尽可能使用 this:在 Agent 方法内,优先使用 this.namethis.state 等,而非 getCurrentAgent()

  2. 在外部函数中使用 getCurrentAgent():当你需要在无法访问 this 的工具函数或库中获取 Agent 上下文时。

  3. 检查 undefined:若在 Agent 上下文外调用,返回值可能为 undefined

    const { agent } = getCurrentAgent();
    if (agent) {
    	// Safe to use agent
    	console.log(agent.name);
    }
    const { agent } = getCurrentAgent();
    if (agent) {
    	// Safe to use agent
    	console.log(agent.name);
    }
  4. 为 Agent 指定类型:传入 Agent 类作为类型参数以获得正确类型。

    const { agent } = getCurrentAgent();
    // agent is typed as MyAgent | undefined
    const { agent } = getCurrentAgent<MyAgent>();
    // agent is typed as MyAgent | undefined

后续步骤

这篇文档对您有帮助吗?