← Создание агентов на Cloudflare / agents / runtime / lifecycle
getCurrentAgent()
getCurrentAgent() функция позволяет обращаться к текущему контексту агента из любого места кода, включая внешние вспомогательные функции и библиотеки. Это полезно, когда информация об агенте нужна в функциях, у которых нет прямого доступа к this.
Автоматический контекст для пользовательских методов
Framework обнаруживает и оборачивает пользовательские методы Agent во время инициализации, чтобы getCurrentAgent() внутри способны определить активного агента и функции, которые они вызывают.
Как это работает
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;
}
}Настройка не требуется. Фреймворк автоматически:
- Сканирует класс вашего агента в поисках пользовательских методов.
- Оборачивает их контекстом агента при инициализации.
- Обеспечивает
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;
}
}Встроенные и собственные методы
- Встроенные методы (
onRequest,onEmail,onStateChanged): контекст уже есть. - Пользовательские методы (ваши методы): автоматически оборачиваются при инициализации.
- Внешние функции: Доступ к контексту через
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);
}
}Когда контекст теряется
Контекст агента распространяется только вдоль дерева вызовов исходного обращения. Код, до которого добираются за пределами этого дерева вызовов, начинает работу с пустым контекстом, поэтому getCurrentAgent() возвращает объект, поля которого являются undefined. Типичные случаи включают:
- колбэк хоста, вызываемый через RPC из дочернего isolate Worker Loader, например при изолированном выполнении Codemode;
- service binding или точка входа RPC Durable Object;
- потребитель очереди или другая точка входа, которая сохраняет ссылку на агента.
Маршрутизируйте колбэк через публичный метод агента. Пользовательские методы оборачиваются автоматически, поэтому вызов agent.someMethod() снова входит в контекст этого агента:
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.
}
}Контекст, восстановленный таким образом, имеет connection, request, а также email не задан. Он не привязан к вводу-выводу активного клиента.
Запросы MCP, инициированные сервером (elicitInput, createMessage, а также listRoots) на McpAgent не требуют этой косвенности, поскольку транспорт MCP сохраняет владеющего им агента.
Справочник по API
getCurrentAgent()
Получает текущего агента из любого контекста, где он доступен.
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 |
Текущий экземпляр агента |
connection |
Connection | undefined |
Соединение WebSocket (если вызывается из обработчика WebSocket) |
request |
Request | undefined |
HTTP-запрос (если вызывается из обработчика запроса) |
email |
AgentEmail | undefined |
Письмо (если вызвано из обработчика писем) |
Использование:
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) | Да | Да | Нет | Нет |
| Запланированная задача | Да | Нет | Нет | Нет |
| Колбэк очереди | Да | Зависит | Зависит | Зависит |
Рекомендации
-
Используйте
thisкогда это возможно: Внутри методов агента предпочитайтеthis.name,this.state, и т. д. черезgetCurrentAgent(). -
Используйте
getCurrentAgent()во внешних функциях: Когда вам нужен контекст агента в служебных функциях или библиотеках, не имеющих доступа кthis. -
Проверка значения undefined: Возвращаемые значения могут быть
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); } -
Типизация агента: Передайте свой класс агента в качестве параметра типа для корректной типизации.
const { agent } = getCurrentAgent(); // agent is typed as MyAgent | undefinedconst { agent } = getCurrentAgent<MyAgent>(); // agent is typed as MyAgent | undefined