Get structured output from agents
Extract structured data from agent responses using JSON schemas and type definitions. Get JSON, typed objects, or specific formats from your agents instead of free-form text.
Agents can return structured data instead of free-form text. This is useful for integrating with APIs, databases, or other systems that require specific data formats.
JSON Output
Request JSON output from agents by specifying the desired format in your instructions or using schema validation.
TypeScript
import { Agent, Runner } from '@autohandai/agent-sdk';
const agent = new Agent({
name: "Data Extractor",
instructions: "Extract structured data and return it as JSON.",
});
const result = await Runner.run(agent,
"Extract the user information from this file and return as JSON with name, email, and age fields."
);
const jsonData = JSON.parse(result.finalOutput);
console.log(jsonData);
Python
import json
from autohand_agents import Agent, Runner
agent = Agent(
name="Data Extractor",
instructions="Extract structured data and return it as JSON.",
)
result = Runner.run_sync(
agent,
"Extract the user information from this file and return as JSON with name, email, and age fields."
)
json_data = json.loads(result.final_output)
print(json_data)
Java
import com.autohand.Agent;
import com.autohand.Runner;
import org.json.JSONObject;
Agent agent = new Agent.Builder()
.name("Data Extractor")
.instructions("Extract structured data and return it as JSON")
.build();
RunResult result = Runner.runSync(agent,
"Extract the user information from this file and return as JSON with name, email, and age fields."
);
JSONObject jsonData = new JSONObject(result.getFinalOutput());
System.out.println(jsonData);
Go
package main
import (
"encoding/json"
"github.com/autohandai/agentsdk-go"
)
func main() {
agent := agentsdk.NewAgent(
"Data Extractor",
"Extract structured data and return it as JSON",
)
result := agentsdk.RunnerRunSync(agent,
"Extract the user information from this file and return as JSON with name, email, and age fields.",
)
var jsonData map[string]interface{}
json.Unmarshal([]byte(result.FinalOutput), &jsonData)
println(jsonData)
}
Swift
import AutohandAgents
import Foundation
let agent = Agent(
name: "Data Extractor",
instructions: "Extract structured data and return it as JSON"
)
let result = try await Runner.run(agent,
prompt: "Extract the user information from this file and return as JSON with name, email, and age fields."
)
if let data = result.finalOutput.data(using: .utf8),
let jsonData = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
print(jsonData)
}
Rust
use autohand_agents::{Agent, Runner};
use serde_json::Value;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let agent = Agent::new("Data Extractor", "Extract structured data and return it as JSON");
let result = Runner::run_sync(&agent,
"Extract the user information from this file and return as JSON with name, email, and age fields."
)?;
let json_data: Value = serde_json::from_str(&result.final_output)?;
println!("{}", json_data);
Ok(())
}Schema Validation
Define JSON schemas to validate that agent output matches your expected structure.
TypeScript
import { z } from 'zod';
import { Agent, Runner } from '@autohandai/agent-sdk';
const UserSchema = z.object({
name: z.string(),
email: z.string().email(),
age: z.number().int().positive(),
});
const agent = new Agent({
name: "Data Extractor",
instructions: "Extract user information and return as JSON with name, email, and age fields.",
});
const result = await Runner.run(agent, "Extract user data from the file");
const validated = UserSchema.parse(JSON.parse(result.finalOutput));
Python
from pydantic import BaseModel, EmailStr
from autohand_agents import Agent, Runner
class User(BaseModel):
name: str
email: EmailStr
age: int
agent = Agent(
name="Data Extractor",
instructions="Extract user information and return as JSON with name, email, and age fields.",
)
result = Runner.run_sync(agent, "Extract user data from the file")
validated = User.model_validate_json(result.final_output)
Java
import com.autohand.Agent;
import com.autohand.Runner;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.annotation.JsonProperty;
class User {
@JsonProperty String name;
@JsonProperty String email;
@JsonProperty int age;
}
Agent agent = new Agent.Builder()
.name("Data Extractor")
.instructions("Extract user information and return as JSON")
.build();
RunResult result = Runner.runSync(agent, "Extract user data from the file");
ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(result.getFinalOutput(), User.class);
Go
package main
import (
"encoding/json"
"github.com/autohandai/agentsdk-go"
)
type User struct {
Name string `json:"name"`
Email string `json:"email"`
Age int `json:"age"`
}
func main() {
agent := agentsdk.NewAgent(
"Data Extractor",
"Extract user information and return as JSON",
)
result := agentsdk.RunnerRunSync(agent, "Extract user data from the file")
var user User
json.Unmarshal([]byte(result.FinalOutput), &user)
println(user.Name, user.Email, user.Age)
}
Swift
import AutohandAgents
import Foundation
struct User: Codable {
let name: String
let email: String
let age: Int
}
let agent = Agent(
name: "Data Extractor",
instructions: "Extract user information and return as JSON"
)
let result = try await Runner.run(agent, prompt: "Extract user data from the file")
let user = try JSONDecoder().decode(User.self, from: result.finalOutput.data(using: .utf8)!)
print(user)
Rust
use autohand_agents::{Agent, Runner};
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize)]
struct User {
name: String,
email: String,
age: u32,
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let agent = Agent::new("Data Extractor", "Extract user information and return as JSON");
let result = Runner::run_sync(&agent, "Extract user data from the file")?;
let user: User = serde_json::from_str(&result.final_output)?;
println!("{:?}", user);
Ok(())
}Best Practices
- Be explicit in instructions: Tell the agent exactly what fields you need and their formats
- Use validation: Always validate the output against a schema before using it
- Handle errors gracefully: If the agent returns invalid JSON, ask it to retry
- Provide examples: Include example JSON in your instructions for better results
TypeScript
import { z } from 'zod';
import { Agent } from '@autohandai/agent-sdk';
const UserSchema = z.object({
name: z.string(),
email: z.string().email(),
age: z.number().int().positive(),
});
const agent = await Agent.create({
instructions: [
'Extract user information and return as JSON.',
'Required fields: name (string), email (valid email), age (positive integer).',
'Example: {"name":"John Doe","email":"john@example.com","age":30}',
].join('\n'),
});
const user = await agent.runJson('Extract user data from the file', {
schemaName: 'User',
validate: UserSchema.parse,
});
Python
from pydantic import BaseModel, EmailStr
from autohand_agents import Agent, Runner
class User(BaseModel):
name: str
email: EmailStr
age: int
agent = Agent(
name="Data Extractor",
instructions=(
"Extract user information and return as JSON. "
"Required fields: name, email, and age."
),
)
result = Runner.run_sync(agent, "Extract user data from the file")
user = User.model_validate_json(result.final_output)
Java
import com.autohand.Agent;
import com.autohand.Runner;
Agent agent = new Agent.Builder()
.name("Data Extractor")
.instructions(
"Extract user information and return as JSON. " +
"Required fields: name, email, and age."
)
.build();
Go
package main
import "github.com/autohandai/agentsdk-go"
agent := agentsdk.NewAgent(
"Data Extractor",
"Extract user information and return JSON with name, email, and age.",
)
Swift
import AutohandAgents
let agent = Agent(
name: "Data Extractor",
instructions: """
Extract user information and return JSON.
Required fields: name, email, and age.
"""
)
Rust
use autohand_agents::Agent;
let agent = Agent::new(
"Data Extractor",
"Extract user information and return JSON with name, email, and age.",
);Use Cases
- API Integration: Extract data to send to external APIs
- Database Operations: Generate SQL queries or database records
- Configuration Files: Generate YAML, TOML, or JSON config files
- Test Data: Generate structured test data for testing
- Report Generation: Create structured reports from unstructured data