API Responses
Format: JSON
Best for: Web services, data processing, structured applications
Example: Return complete agent data for API endpoints
Execute the agent and return the response in a specified format with full control over output structure. This is a execution method that triggers agent execution and returns formatted output - not the agent instance for chaining.
output(outputType: OutputType): Promise<string | object>
outputType
OutputType
undefined
Returns a Promise<string | object>
containing the formatted response:
"text"
: Returns structured string with metadata"json"
: Returns object with complete agent data"md"
: Returns markdown string with timestampimport { AgentForceAgent } from '@agentforce/adk';
const agent = new AgentForceAgent({ name: "QuestionAgent"}) .useLLM("ollama", "gemma3:4b") .systemPrompt("You are a helpful assistant") .prompt("What is the capital of France?");
const result = await agent.output("text");console.log(result);
// Output:// === Agent QuestionAgent Output (Text Format) ===// System: You are a helpful assistant// User: What is the capital of France?// Response: Paris is the capital of France.
import { AgentForceAgent } from '@agentforce/adk';
const agent = new AgentForceAgent({ name: "DataAgent"}) .systemPrompt("You are a data analyst") .useLLM("google", "gemini-1.5-flash") .prompt("Analyze this sales data trend");
const result = await agent.output("json");console.log(JSON.stringify(result, null, 2));
// Output:// {// "agent": "DataAgent",// "provider": "google",// "model": "gemini-1.5-flash",// "systemPrompt": "You are a data analyst",// "userPrompt": "Analyze this sales data trend",// "response": "Based on the analysis...",// "chatHistory": [...],// "timestamp": "2024-03-15T10:30:00.000Z",// "status": "success"// }
import { AgentForceAgent } from '@agentforce/adk';
const agent = new AgentForceAgent({ name: "DocumentationAgent"}) .systemPrompt("You are a technical writer. Use proper markdown formatting") .useLLM("openrouter", "mistralai/mistral-small") .prompt("Write a guide on REST API best practices");
const result = await agent.output("md");console.log(result);
// Output:// # REST API Best Practices//// ## 1. Use HTTP Status Codes Correctly// ...//// *Generated at: 2024-03-15T10:30:00.000Z*
import { AgentForceAgent } from '@agentforce/adk';
class AIService { static async generateContent(prompt: string, format: 'text' | 'json' | 'md' = 'json') { const agent = new AgentForceAgent({ name: "ContentGenerator" }) .systemPrompt("You are a professional content creator") .useLLM("google", "gemini-1.5-pro") .prompt(prompt);
return await agent.output(format); }
static async processApiRequest(request: { prompt: string, format: string }) { try { const result = await this.generateContent(request.prompt, request.format as any);
return { success: true, data: result, timestamp: new Date().toISOString() }; } catch (error) { return { success: false, error: error.message, timestamp: new Date().toISOString() }; } }}
// Usageconst apiResponse = await AIService.processApiRequest({ prompt: "Create a marketing email for our new product", format: "json"});
console.log("API Response:", apiResponse);
import { AgentForceAgent } from '@agentforce/adk';
class DataProcessor { private agent: AgentForceAgent;
constructor() { this.agent = new AgentForceAgent({ name: "DataProcessor", tools: ["fs_read_file", "fs_write_file"] }) .systemPrompt("You are a data processing expert") .useLLM("ollama", "qwen3-coder-tool", { appendToolResults: true, maxToolRounds: 3 }); }
async processCSV(filePath: string) { this.agent.prompt(`Read and analyze the CSV file at ${filePath}. Provide insights and summary statistics.`);
const jsonResult = await this.agent.output("json") as any;
return { insights: jsonResult.response, metadata: { agent: jsonResult.agent, model: jsonResult.model, timestamp: jsonResult.timestamp }, fullData: jsonResult }; }
async generateReport(data: any) { this.agent.prompt(`Generate a markdown report from this analysis: ${JSON.stringify(data.insights)}`);
const markdownReport = await this.agent.output("md"); return markdownReport; }}
// Usageconst processor = new DataProcessor();const analysis = await processor.processCSV("data/sales-q4.csv");const report = await processor.generateReport(analysis);
console.log("Analysis:", analysis);console.log("Report:", report);
import { AgentForceAgent } from '@agentforce/adk';import { writeFile } from 'fs/promises';
class OutputHandler { static async processWithAllFormats(agent: AgentForceAgent, baseFileName: string) { const results = { text: await agent.output("text"), json: await agent.output("json"), markdown: await agent.output("md") };
// Save each format to appropriate file await writeFile(`${baseFileName}.txt`, results.text as string); await writeFile(`${baseFileName}.json`, JSON.stringify(results.json, null, 2)); await writeFile(`${baseFileName}.md`, results.markdown as string);
return { formats: Object.keys(results), files: [`${baseFileName}.txt`, `${baseFileName}.json`, `${baseFileName}.md`], data: results }; }}
// Usageconst agent = new AgentForceAgent({ name: "MultiFormatAgent"}) .systemPrompt("You are a versatile assistant") .prompt("Explain the benefits of TypeScript over JavaScript");
const allOutputs = await OutputHandler.processWithAllFormats(agent, "typescript-benefits");console.log("Generated files:", allOutputs.files);
// Extract specific data from JSON outputconst agent = new AgentForceAgent({ name: "StructuredAgent" }) .systemPrompt("Always provide structured responses") .prompt("List the top 3 programming languages with their use cases");
const jsonResult = await agent.output("json") as any;
// Extract specific fieldsconst metadata = { model: jsonResult.model, timestamp: jsonResult.timestamp, status: jsonResult.status};
const responseContent = jsonResult.response;const chatHistory = jsonResult.chatHistory;
console.log("Agent used:", jsonResult.agent);console.log("Response:", responseContent);console.log("Full history available:", chatHistory.length > 0);
// Process markdown output for web displayconst agent = new AgentForceAgent({ name: "ContentAgent" }) .systemPrompt("Format responses as clean markdown with proper headers") .prompt("Create a tutorial on React hooks");
const markdownContent = await agent.output("md") as string;
// Remove timestamp footer for web displayconst cleanMarkdown = markdownContent.replace(/\n\n\*Generated at:.*\*$/, '');
// Extract just the content without timestampconst contentOnly = markdownContent.split('\n\n*Generated at:')[0];
console.log("Clean markdown:", cleanMarkdown);console.log("Content only:", contentOnly);
// Parse structured text outputconst agent = new AgentForceAgent({ name: "InfoAgent" }) .prompt("What is machine learning?");
const textOutput = await agent.output("text") as string;
// Parse the structured text formatconst lines = textOutput.split('\n');const systemLine = lines.find(line => line.startsWith('System:'));const userLine = lines.find(line => line.startsWith('User:'));const responseLine = lines.find(line => line.startsWith('Response:'));
const parsed = { system: systemLine?.replace('System: ', '') || '', user: userLine?.replace('User: ', '') || '', response: responseLine?.replace('Response: ', '') || ''};
console.log("Parsed components:", parsed);
text
string
Structured
json
object
Complete
md
string
Clean + Timestamp
API Responses
Format: JSON
Best for: Web services, data processing, structured applications
Example: Return complete agent data for API endpoints
Content Display
Format: Markdown
Best for: Web pages, documentation, blogs, clean formatting
Example: Generate articles and tutorials for direct display
Logging & Debug
Format: Text
Best for: Human-readable logs, debugging, audit trails
Example: Detailed execution logs with all context information
Data Integration
Format: JSON
Best for: Database storage, analytics, further processing
Example: Store agent interactions with full metadata
// Choose appropriate format for use caseconst jsonData = await agent.output("json"); // For APIs and data processingconst markdown = await agent.output("md"); // For content displayconst textLog = await agent.output("text"); // For debugging and logs
// Type assertion for JSON formatconst result = await agent.output("json") as { agent: string; response: string; timestamp: string; // ... other properties};
// Handle different return types properlyasync function processOutput(agent: AgentForceAgent, format: 'text' | 'json' | 'md') { const result = await agent.output(format);
if (format === 'json') { const jsonResult = result as any; return jsonResult.response; } else { return result as string; }}
// Use consistent naming for output handlingconst responses = { structured: await agent.output("json"), readable: await agent.output("text"), formatted: await agent.output("md")};
// ❌ Trying to chain after output()const result = await agent .prompt("Hello") .output("json") .prompt("Follow up"); // Error: output() is terminal
// ❌ Wrong type expectationsconst result = await agent.output("text");const data = result.response; // Error: text format returns string, not object
// ❌ Invalid output typeawait agent.output("xml"); // Error: Only text, json, md supportedawait agent.output(""); // Error: Empty string not valid
// ❌ Not handling return types properlyconst jsonResult = await agent.output("json") as string; // Wrong type assertionconst textResult = await agent.output("text") as object; // Wrong type assertion
try { const agent = new AgentForceAgent({ name: "OutputAgent" }) .systemPrompt("You are a helpful assistant") .prompt("Explain quantum computing");
const result = await agent.output("json");
// Handle success case const jsonResult = result as any; console.log("Agent response:", jsonResult.response); console.log("Status:", jsonResult.status);
} catch (error) { if (error.message.includes("Output type must be a string")) { console.error("Invalid output type parameter"); } else if (error.message.includes("must be one of: text, json, md")) { console.error("Unsupported output format"); } else { console.error("Execution error:", error.message); }}
// Robust output handlingasync function safeOutput(agent: AgentForceAgent, format: 'text' | 'json' | 'md') { try { const result = await agent.output(format); return { success: true, data: result, format }; } catch (error) { return { success: false, error: error.message, format, timestamp: new Date().toISOString() }; }}
Common Error Messages:
Output type must be a string
- Invalid parameter typeOutput type must be one of: text, json, md
- Unsupported formatUnsupported output type: [type]
- Internal format validation error.getResponse()
- Execute and return raw response string only.saveToFile()
- Execute and save response to file with auto-format.run()
- Execute multi-step task workflows.prompt()
- Set the main user prompt