Skip to content

.output()


AgentForceAgent Execution Method Asynchronous

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>
Parameter
Type
Default
Description
outputType
OutputType
undefined
The output format: 'text' (string), 'json' (object), or 'md' (string)

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 timestamp
import { 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';
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()
};
}
}
}
// Usage
const apiResponse = await AIService.processApiRequest({
prompt: "Create a marketing email for our new product",
format: "json"
});
console.log("API Response:", apiResponse);
// Extract specific data from JSON output
const 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 fields
const 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);
Parameter
Type
Default
Description
text
string
Structured
Human-readable format with clear sections for system, user, and response
json
object
Complete
Full structured data including chat history, metadata, and timestamp
md
string
Clean + Timestamp
Clean markdown response content with generation timestamp appended

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 case
const jsonData = await agent.output("json"); // For APIs and data processing
const markdown = await agent.output("md"); // For content display
const textLog = await agent.output("text"); // For debugging and logs
// Type assertion for JSON format
const result = await agent.output("json") as {
agent: string;
response: string;
timestamp: string;
// ... other properties
};
// Handle different return types properly
async 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 handling
const 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 expectations
const result = await agent.output("text");
const data = result.response; // Error: text format returns string, not object
// ❌ Invalid output type
await agent.output("xml"); // Error: Only text, json, md supported
await agent.output(""); // Error: Empty string not valid
// ❌ Not handling return types properly
const jsonResult = await agent.output("json") as string; // Wrong type assertion
const 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 handling
async 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 type
  • Output type must be one of: text, json, md - Unsupported format
  • Unsupported output type: [type] - Internal format validation error