# How to Use Structured Output Modes in Codebuff Agents: A Complete Guide

> Learn to use structured output modes in Codebuff agents with our complete guide. Easily generate JSON-compatible objects by defining output schemas and setting the correct output mode for your agent.

- Repository: [Codebuff/codebuff](https://github.com/CodebuffAI/codebuff)
- Tags: how-to-guide
- Published: 2026-03-08

---

**Set `outputMode` to `'structured_output'` and provide an `outputSchema` in your agent definition, then yield a `set_output` tool call with a payload matching that schema to receive a JSON-compatible object wrapped in `{ type: 'structuredOutput', value: ... }`.**

Codebuff agents support multiple output formats for different integration scenarios. When building programmatic pipelines or nested agent orchestration in the `CodebuffAI/codebuff` repository, utilizing **structured output modes in Codebuff agents** allows you to enforce type-safe, schema-validated JSON responses that downstream systems can parse reliably.

## Understanding the Three Output Modes

Codebuff agents can return results in three distinct formats, configured via the `outputMode` property:

- **`last_message`** – Returns the text content of the final assistant message. Best for simple conversational responses.
- **`all_messages`** – Returns the complete conversation transcript including all tool calls and results. Use this when you need full audit trails or debugging information.
- **`structured_output`** – Returns a JSON-compatible object validated against a **JSON Schema** you provide via `outputSchema`. This is the preferred mode for programmatic integration.

## Configuring Structured Output in Agent Definitions

### Setting outputMode and outputSchema

To enable structured output, declare `outputMode: 'structured_output'` and provide a valid JSON Schema in `outputSchema`. The schema supports standard JSON-Schema constructs including objects, arrays, primitives, and nested structures.

In [`packages/common/src/types/agent-template.ts`](https://github.com/CodebuffAI/codebuff/blob/main/packages/common/src/types/agent-template.ts), the `AgentTemplate` type declares these properties:

```typescript
// packages/common/src/types/agent-template.ts
export interface AgentTemplate {
  // ...
  outputMode?: 'last_message' | 'all_messages' | 'structured_output';
  outputSchema?: JSONSchema; // Required when outputMode is 'structured_output'
}

```

Here is a real-world example from [`.agents/file-explorer.ts`](https://github.com/CodebuffAI/codebuff/blob/main/.agents/file-explorer.ts):

```typescript
// .agents/file-explorer.ts
export const fileExplorer = {
  id: AgentTemplateTypes.file_explorer,
  displayName: 'Dora the File Explorer',
  model: 'anthropic/claude-4-sonnet-20250522',
  // 👉 Enable structured output mode
  outputMode: 'structured_output',
  // 👉 Define the expected JSON structure
  outputSchema: {
    type: 'object',
    properties: {
      results: { 
        type: 'string', 
        description: 'Aggregated file‑exploration results' 
      },
    },
    required: ['results'],
    additionalProperties: false,
  },
  // …
} satisfies AgentTemplate<string, z.infer<typeof paramsSchema>>

```

## Runtime Handling of Structured Output

### How the Runtime Processes Structured Results

When an agent executes, the runtime inspects `agentTemplate.outputMode`. If it equals `"structured_output"`, the system validates the final result against the provided schema and wraps it in a standardized envelope.

In [`packages/agent-runtime/src/util/agent-output.ts`](https://github.com/CodebuffAI/codebuff/blob/main/packages/agent-runtime/src/util/agent-output.ts), the logic appears as:

```typescript
// packages/agent-runtime/src/util/agent-output.ts
if (agentTemplate.outputMode === 'structured_output') {
  return { type: 'structuredOutput', value: structuredResult };
}

```

This ensures that consumers always receive a predictable structure: an object with `type: 'structuredOutput'` and a `value` property containing the validated JSON payload.

## Implementing Structured Output in handleSteps

### Yielding set_output with Schema-Compliant Payloads

Inside a generator-based `handleSteps` function, you typically yield tool calls for intermediate operations. To return structured data, yield the `set_output` tool (or any equivalent custom tool) with a payload that strictly matches your `outputSchema`.

From [`.agents/file-explorer.ts`](https://github.com/CodebuffAI/codebuff/blob/main/.agents/file-explorer.ts), the implementation looks like:

```typescript
// .agents/file-explorer.ts – handleSteps implementation
handleSteps: function* ({ prompt, params }) {
  const prompts = params?.prompts ?? [];

  // Spawn parallel file-picker agents
  const { toolResult: pickerResult } = yield {
    toolName: 'spawn_agents' as const,
    args: {
      agents: prompts.map(p => ({
        agent_type: 'file-picker' as const,
        prompt: `Find files for "${prompt}" – ${p}`,
      })),
    },
  };

  // 👉 Return structured JSON payload matching outputSchema
  yield {
    toolName: 'set_output' as const,
    args: {
      results: pickerResult,  // Must conform to the schema defined above
    },
  };
}

```

## Validation and Testing

Codebuff validates the output schema at **agent-load time** and during execution. The test suite ensures that agents cannot declare `structured_output` without a corresponding schema.

In [`sdk/src/__tests__/validate-agents.test.ts`](https://github.com/CodebuffAI/codebuff/blob/main/sdk/src/__tests__/validate-agents.test.ts), validation logic confirms:

```typescript
// sdk/src/__tests__/validate-agents.test.ts
it('should validate that structured_output mode requires outputSchema', () => {
  const agent = createAgent({ outputMode: 'structured_output' });
  expect(() => validateAgent(agent)).toThrow(/outputSchema is required/);
});

```

Similarly, [`sdk/src/__tests__/load-agents.test.ts`](https://github.com/CodebuffAI/codebuff/blob/main/sdk/src/__tests__/load-agents.test.ts) rejects agents with mismatched configurations:

```typescript
// sdk/src/__tests__/load-agents.test.ts
it('should reject agents with structured_output but no schema', () => {
  // Test implementation verifying schema presence
});

```

## Consuming Structured Output from Parent Agents

When spawning sub-agents that use structured output, parent agents receive the wrapped payload and can access the validated data via the `value` property.

Here is an example from [`.agents/aggregator.ts`](https://github.com/CodebuffAI/codebuff/blob/main/.agents/aggregator.ts) showing consumption:

```typescript
// .agents/aggregator.ts
handleSteps: function* ({ prompt }) {
  const { toolResult } = yield {
    toolName: 'spawn_agents' as const,
    args: { agents: [{ agent_type: 'file-explorer', prompt }] },
  };

  // toolResult is the structured payload from the explorer
  const { results } = toolResult.value;   // <-- matches the schema
  // Use `results` for further processing …
}

```

## When to Use Structured Output

| Use Case | Why `structured_output` is Ideal |
|----------|----------------------------------|
| **Programmatic pipelines** (CI checks, data feeds) | Guarantees a predictable JSON shape that downstream scripts can parse without fragile text-scraping. |
| **Nested agent orchestration** | Allows parent agents to inspect sub-agent results in a type-safe way via the `value` property. |
| **UI integration** | Web applications can directly map schema fields to form inputs, tables, or charts without parsing natural language. |
| **Validation and safety** | The JSON Schema is checked at both load time and runtime, catching mismatches before deployment. |

## Summary

- **Declare** structured output by setting `outputMode: 'structured_output'` and providing a valid `outputSchema` in your agent definition.
- **Implement** by yielding the `set_output` tool in `handleSteps` with a payload that strictly matches your schema.
- **Receive** results wrapped in `{ type: 'structuredOutput', value: <validated-json> }` at the runtime level.
- **Validate** configurations automatically through the SDK test suite, ensuring schema compliance at load time.
- **Consume** structured data in parent agents via `toolResult.value` for reliable, type-safe orchestration.

## Frequently Asked Questions

### What happens if my payload doesn't match the outputSchema?

The Codebuff runtime validates the payload against your JSON Schema at execution time. If the structure fails validation, the agent execution will throw an error indicating a schema mismatch, preventing invalid data from propagating to downstream consumers.

### Can I use structured output with any model?

Yes, structured output mode is model-agnostic within the Codebuff framework. While the example agents use Anthropic models like `claude-4-sonnet-20250522`, the `outputMode` and `outputSchema` configuration works across any model supported by the Codebuff runtime, as the schema validation happens at the framework level rather than the model level.

### How do I access structured output from a spawned sub-agent?

When a parent agent spawns a sub-agent using the `spawn_agents` tool, the `toolResult` returned contains the structured payload. Access the validated data via `toolResult.value`, which contains the JSON object matching the sub-agent's `outputSchema`. For example: `const { results } = toolResult.value;`.

### Is additionalProperties allowed in the outputSchema?

The JSON Schema validation in Codebuff respects standard JSON Schema constraints. If you set `additionalProperties: false` in your schema, the runtime will reject payloads containing properties not explicitly defined in `properties`. For strict type safety in agent orchestration, it is recommended to disable additional properties unless your use case specifically requires flexible, extensible objects.