← Vytvářejte agenty na Cloudflare / agents / runtime / lifecycle
getCurrentAgent()
getCurrentAgent() funkce vám umožňuje přistupovat k aktuálnímu kontextu agenta odkudkoli ve vašem kódu, včetně externích pomocných funkcí a knihoven. To se hodí, když potřebujete informace o agentovi ve funkcích, které nemají přímý přístup k this.
Automatický kontext pro vlastní metody
Framework při inicializaci rozpozná a obalí vlastní metody Agenta, aby getCurrentAgent() uvnitř dokážou rozpoznat aktivního agenta i funkce, které volají.
Jak to funguje
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;
}
}Není vyžadována žádná konfigurace. Framework automaticky:
- Prohledává třídu vašeho agenta a hledá vlastní metody.
- Obaluje je kontextem agenta během inicializace.
- Zajišťuje
getCurrentAgent()funguje ve všech externích funkcích volaných z vašich metod.
Praktický příklad
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;
}
}Vestavěné vs. vlastní metody
- Vestavěné metody (
onRequest,onEmail,onStateChanged): Kontext už máte. - Vlastní metody (vaše metody): automaticky obaleny během inicializace.
- Externí funkce: Přistupte ke kontextu prostřednictvím
getCurrentAgent().
Tok kontextu
// 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()Běžné případy použití
Práce s nástroji 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;
}
}Volání externích knihoven
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);
}
}Přístup ke kontextu požadavku a připojení
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);
}
}Když dojde ke ztrátě kontextu
Kontext agenta se šíří pouze podél stromu volání původního vyvolání. Kód, ke kterému se přistupuje mimo tento strom volání, začíná s prázdným kontextem, takže getCurrentAgent() vrátí objekt, jehož pole jsou undefined. Mezi běžné případy patří:
- callback hostitele volaný přes RPC z podřízeného izolátu Worker Loaderu, například sandboxované spouštění Codemode;
- vazba na službu nebo vstupní bod RPC Durable Object;
- konzument fronty nebo jiný vstupní bod, který si uchovává referenci na agenta.
Směrujte callback přes veřejnou metodu agenta. Vlastní metody se obalují automaticky, takže volání agent.someMethod() se vrátí zpět do kontextu tohoto agenta:
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.
}
}Takto obnovený kontext má connection, request, a email nenastaveno. Není vázáno na živý vstup a výstup klienta.
Požadavky MCP iniciované serverem (elicitInput, createMessage, a listRoots) na McpAgent tuto nepřímost nevyžadují, protože transport MCP si uchovává svého vlastnícího agenta.
Referenční dokumentace API
getCurrentAgent()
Získá aktuálního agenta z libovolného kontextu, ve kterém je dostupný.
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;
};Vrací:
| Vlastnost | Typ | Popis |
|---|---|---|
agent |
T | undefined |
Aktuální instance agenta |
connection |
Connection | undefined |
Připojení WebSocket (pokud je voláno z handleru WebSocket) |
request |
Request | undefined |
HTTP požadavek (pokud je volán z obslužné rutiny požadavku) |
email |
AgentEmail | undefined |
E-mail (je-li voláno z e-mailového handleru) |
Použití:
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
}
}Dostupnost kontextu
Dostupný kontext závisí na tom, jak byla metoda vyvolána:
| Vyvolání | agent |
connection |
request |
email |
|---|---|---|---|---|
onRequest() |
Ano | Ne | Ano | Ne |
onConnect() |
Ano | Ano | Ano | Ne |
onMessage() |
Ano | Ano | Ne | Ne |
onEmail() |
Ano | Ne | Ne | Ano |
| Vlastní metoda (přes RPC) | Ano | Ano | Ne | Ne |
| Naplánovaná úloha | Ano | Ne | Ne | Ne |
| Callback fronty | Ano | Záleží | Záleží | Záleží |
Osvědčené postupy
-
Použijte
thispokud je to možné: Uvnitř metod agenta dávejte přednostthis.name,this.state, atd. předgetCurrentAgent(). -
Použijte
getCurrentAgent()v externích funkcích: Když potřebujete kontext agenta v pomocných funkcích nebo knihovnách, které nemají přístup kthis. -
Kontrola hodnoty undefined: Vrácené hodnoty mohou být
undefinedpokud je volána mimo kontext agenta.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); } -
Otypujte agenta: Předejte třídu svého agenta jako typový parametr pro správné typování.
const { agent } = getCurrentAgent(); // agent is typed as MyAgent | undefinedconst { agent } = getCurrentAgent<MyAgent>(); // agent is typed as MyAgent | undefined