This example demonstrates how to create an AI Agent using Cloudflare Agents that leverages Cloudflare Workers AI as a tool. The agent will act as a general-purpose assistant, and when it needs to answer a factual question, it will call an external Cloudflare Worker (which itself uses Workers AI) to get the answer.
This setup showcases:
- Cloudflare Agent: The orchestrator, deciding when to use tools.
- Cloudflare Workers AI: The underlying LLM inference service.
- Cloudflare Worker (RPC Tool): A separate Worker acting as a callable "tool" for the Agent, wrapping the Workers AI call.
Scenario: AI Assistant with External Knowledge Tool
Our Cloudflare Agent will be an "AI Assistant." When asked a question that requires knowledge (e.g., "What is the capital of France?"), it will identify the need for external knowledge and call a specific RPC tool. This RPC tool will be another Cloudflare Worker that uses Workers AI to provide the answer.
Step 1: Create the Cloudflare Worker AI Tool
This Worker will expose an RPC endpoint that the Agent can call. It will take a prompt and use Cloudflare Workers AI to get an answer.
1.1. worker-ai-tool.js
// worker-ai-tool.js
// This Worker acts as an RPC tool that the Cloudflare Agent can call.
// It uses Cloudflare Workers AI to get responses.
export default {
async fetch(request, env, ctx) {
// Only allow POST requests for the RPC call
if (request.method !== 'POST') {
return new Response('Method Not Allowed', { status: 405 });
}
try {
const { prompt } = await request.json();
if (!prompt) {
return new Response(JSON.stringify({ error: 'Missing prompt in request body.' }), {
status: 400,
headers: { 'Content-Type': 'application/json' }
});
}
// Use the Cloudflare Workers AI binding
// Make sure to bind 'AI' in your wrangler.toml
const response = await env.AI.run('@cf/meta/llama-3-8b-instruct', {
messages: [{ role: 'user', content: prompt }]
});
if (!response || !response.response) {
return new Response(JSON.stringify({ error: 'Failed to get response from AI model.' }), {
status: 500,
headers: { 'Content-Type': 'application/json' }
});
}
// Return the AI model's response
return new Response(JSON.stringify({ result: response.response }), {
headers: { 'Content-Type': 'application/json' }
});
} catch (e) {
return new Response(JSON.stringify({ error: `Internal Server Error: ${e.message}` }), {
status: 500,
headers: { 'Content-Type': 'application/json' }
});
}
},
};
1.2. wrangler.toml for the AI Tool Worker
# wrangler.toml for the AI Tool Worker
name = "ai-tool-worker" # Choose a unique name
main = "worker-ai-tool.js"
compatibility_date = "2024-05-15" # Use a recent date
# IMPORTANT: Bind the AI service
ai_bindings = [ { binding = "AI" } ]
1.3. Deploy the AI Tool Worker
Navigate to the directory containing worker-ai-tool.js and its wrangler.toml, then run:
wrangler deploy
After deployment, wrangler will give you the URL for this Worker (e.g., https://ai-tool-worker.your-account.workers.dev). Copy this URL, you'll need it for the Agent configuration.
Step 2: Create the Cloudflare Agent
This will be our main AI Agent. It will define the ai-tool-worker as an RPC tool it can use.
2.1. agent.js
// agent.js
// This is the Cloudflare Agent that orchestrates the AI interaction.
export default {
async main({ message }) {
return {
// The system prompt defines the Agent's persona and instructions.
// It tells the Agent to use the 'ask_llm' tool for factual questions.
messages: [
{
role: "system",
content: `You are a helpful AI assistant.
If the user asks a question that requires factual knowledge, use the 'ask_llm' tool to get the answer.
Be concise in your responses.
If the question is not factual or doesn't require external knowledge (e.g., "hello"), respond directly.`
},
{
role: "user",
content: message // The user's input message
}
],
// Define the tools this Agent can use.
tools: [
{
type: "rpc", // Specifies this is a Remote Procedure Call tool
name: "ask_llm", // The name the Agent will use to call this tool
description: "Asks a large language model a question and gets a direct answer for factual queries.",
parameters: {
type: "object",
properties: {
// The 'prompt' parameter is what the Agent will pass to our RPC Worker
prompt: {
type: "string",
description: "The factual question to ask the large language model."
}
},
required: ["prompt"] // 'prompt' is a mandatory parameter
},
// !!! IMPORTANT: REPLACE THIS WITH THE ACTUAL URL OF YOUR DEPLOYED 'ai-tool-worker' !!!
url: "YOUR_AI_TOOL_WORKER_URL_HERE"
}
],
// 'tool_choice: "auto"' allows the Agent's reasoning model to decide
// whether to use a tool or respond directly.
tool_choice: "auto",
// The model used by the Agent for its own reasoning and decision-making
// (e.g., deciding which tool to call, or how to formulate a direct answer).
model: "@cf/meta/llama-3-8b-instruct",
// Enable streaming for faster responses
stream: true
};
},
};
2.2. wrangler.toml for the Agent
# wrangler.toml for the Cloudflare Agent
name = "my-cloudflare-agent" # Choose a unique name for your agent
main = "agent.js"
compatibility_date = "2024-05-15" # Use a recent date
# IMPORTANT: This tells Cloudflare this is an Agent
agent_config = { version = 1 }
# Optional: Add nodejs_compat if you use Node.js specific APIs in your agent.js
# compatibility_flags = ["nodejs_compat"]
2.3. Update agent.js with your tool's URL
Before deploying, open agent.js and replace "YOUR_AI_TOOL_WORKER_URL_HERE" with the actual URL you copied in Step 1.3 (e.g., "https://ai-tool-worker.your-account.workers.dev").
2.4. Deploy the Cloudflare Agent
Navigate to the directory containing agent.js and its wrangler.toml, then run:
wrangler deploy
Step 3: Test Your Cloudflare Agent
Once both the ai-tool-worker and my-cloudflare-agent are deployed, you can test the Agent using wrangler.
3.1. Test a direct response (no tool needed):
wrangler agents run my-cloudflare-agent "Hello, who are you?"
Expected Output: The agent should respond directly, e.g., "Hello! I am a helpful AI assistant." or similar, without invoking the tool.
3.2. Test a response requiring the tool:
wrangler agents run my-cloudflare-agent "What is the capital of France?"
Expected Output:
- The Agent's reasoning model will identify that this is a factual question requiring external knowledge.
- It will decide to call the
ask_llm tool.
- It will pass
"What is the capital of France?" as the prompt parameter to your ai-tool-worker.
- The
ai-tool-worker will use Workers AI to get the answer ("Paris").
- The
ai-tool-worker will return {"result": "Paris"} to the Agent.
- The Agent will then respond to you with the result, e.g., "The capital of France is Paris."
3.3. Test another factual query:
wrangler agents run my-cloudflare-agent "Tell me a fun fact about cats."
Expected Output: Similar to the above, it should use the tool and return a fun fact about cats.
How it Works Together:
- User Input: You send a message to
my-cloudflare-agent via wrangler agents run.
- Agent's Reasoning: The Cloudflare Agent (powered by its own LLM,
@cf/meta/llama-3-8b-instruct) receives your message and the messages and tools definitions from agent.js.
- Tool Selection: Based on its
system prompt and your input, the Agent's reasoning model decides if it needs to use one of its defined tools.
- If your input is conversational ("Hello"), it responds directly.
- If your input is a factual question ("What is the capital of X?"), it identifies the need for external knowledge and selects the
ask_llm tool.
- Tool Invocation (RPC Call): When the Agent decides to use
ask_llm, it makes an HTTP POST request (RPC call) to the url specified in the tool definition (YOUR_AI_TOOL_WORKER_URL_HERE), passing the required prompt parameter as JSON.
- Tool Worker Execution: Your
ai-tool-worker receives this POST request. It extracts the prompt.
- Workers AI Inference: The
ai-tool-worker then uses its env.AI binding to call Cloudflare Workers AI (e.g., llama-3-8b-instruct) with the extracted prompt.
- Result Back to Tool Worker: Workers AI returns the LLM's response to the
ai-tool-worker.
- Tool Worker Returns Result to Agent: The
ai-tool-worker sends this result back to the Cloudflare Agent as an HTTP response.
- Agent Integrates Result: The Cloudflare Agent receives the result from the tool. Its reasoning model then incorporates this information into its final response to you.
This architecture provides a powerful way to extend the capabilities of your AI Agents by allowing them to intelligently use custom logic and external data sources encapsulated within Cloudflare Workers.