getCurrentAgent()
getCurrentAgent() 函数让你可以在代码中的任意位置访问当前 Agent 的上下文,包括外部工具函数与第三方库。当函数无法直接访问 this 时,这个能力非常有用。
自定义方法的自动上下文
所有自定义方法自动具备完整的 Agent 上下文。框架在初始化时会自动检测并包装你的自定义方法,确保 getCurrentAgent() 在任何位置都能正常工作。
工作原理
JavaScript
import { AIChatAgent } from "agents/ai-chat-agent";
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;
}
}
Explain Code
TypeScript
import { AIChatAgent } from "agents/ai-chat-agent";
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;
}
}
Explain Code
无需任何配置。框架会自动:
- 扫描你的 Agent 类中的自定义方法。
- 在初始化时为它们包装上 Agent 上下文。
- 确保
getCurrentAgent()可以在你方法内调用的所有外部函数中工作。
实际示例
JavaScript
import { AIChatAgent } from "agents/ai-chat-agent";
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;
}
}
Explain Code
TypeScript
import { AIChatAgent } from "agents/ai-chat-agent";
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;
}
}
Explain Code
内置方法 vs 自定义方法
- 内置方法(
onRequest、onEmail、onStateChanged):已经具备上下文。 - 自定义方法(你写的方法):在初始化时被自动包装。
- 外部函数:通过
getCurrentAgent()访问上下文。
上下文流转
JavaScript
// When you call a custom method:
agent.customMethod();
// → automatically wrapped with agentContext.run()
// → your method executes with full context
// → external functions can use getCurrentAgent()
TypeScript
// 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 工具配合使用
JavaScript
import { AIChatAgent } from "agents/ai-chat-agent";
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;
}
}
Explain Code
TypeScript
import { AIChatAgent } from "agents/ai-chat-agent";
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;
}
}
Explain Code
调用外部库
JavaScript
import { AIChatAgent } from "agents/ai-chat-agent";
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);
}
}
Explain Code
TypeScript
import { AIChatAgent } from "agents/ai-chat-agent";
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);
}
}
Explain Code
访问请求与连接上下文
JavaScript
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);
}
}
Explain Code
TypeScript
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);
}
}
Explain Code
API 参考
getCurrentAgent()
从任意可用的上下文中获取当前 Agent。
JavaScript
import { getCurrentAgent } from "agents";
TypeScript
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 处理器调用时可用) |
| request | Request | undefined | HTTP 请求(从请求处理器调用时可用) |
| AgentEmail | undefined | 邮件(从邮件处理器调用时可用) |
用法:
JavaScript
import { AIChatAgent } from "agents/ai-chat-agent";
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
}
}
Explain Code
TypeScript
import { AIChatAgent } from "agents/ai-chat-agent";
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
}
}
Explain Code
上下文可用性
可用的上下文取决于方法是如何被调用的:
| 调用方式 | agent | connection | request | |
|---|---|---|---|---|
| onRequest() | 是 | 否 | 是 | 否 |
| onConnect() | 是 | 是 | 是 | 否 |
| onMessage() | 是 | 是 | 否 | 否 |
| onEmail() | 是 | 否 | 否 | 是 |
| 自定义方法(通过 RPC) | 是 | 是 | 否 | 否 |
| 定时任务 | 是 | 否 | 否 | 否 |
| Queue 回调 | 是 | 视情况而定 | 视情况而定 | 视情况而定 |
最佳实践
- 能用
this就用this:在 Agent 方法内部,优先使用this.name、this.state等,而不是getCurrentAgent()。 - 在外部函数中使用
getCurrentAgent():当你在工具函数或外部库中需要 Agent 上下文,而它们无法访问this时使用。 - 检查 undefined:如果在 Agent 上下文之外调用,返回值可能是
undefined。- JavaScript
- TypeScript JavaScript
TypeScriptconst { 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); } - 为 agent 标注类型:将你的 Agent 类作为类型参数传入,从而获得正确的类型推断。
- JavaScript
- TypeScript JavaScript
TypeScriptconst { agent } = getCurrentAgent(); // agent is typed as MyAgent | undefinedconst { agent } = getCurrentAgent<MyAgent>(); // agent is typed as MyAgent | undefined
后续步骤
Agents API Agents SDK 完整 API 参考。
Callable methods 通过 RPC 向客户端暴露方法。
State management 管理与同步 Agent 状态。