# Brains

> Reference for onQuery, the framework adapters for OpenAI Agents, Claude Agent and LangGraph, and the brain helper types.

Source: https://docs.vlayers.ai/developers/sdks/reference/brains

Kind: Reference

A brain is your own model loop behind an agent. The simplest is `onQuery`, a function that returns the reply. For a framework, use an adapter from `@voicelayer/sdk/brain` with `defineAgent({ brain })`.

For a walk-through, see [Bring your own brain](https://docs.vlayers.ai/developers/sdks/brains).

### OnQuery

type · `import { OnQuery } from '@voicelayer/sdk'`

```ts
type OnQuery = ( text: string, ctx: OnQueryContext, ) => OnQueryResult | Promise<OnQueryResult>
```

Your own function as the model. It receives the latest utterance, and the full history in `ctx.messages`, and returns the reply as a string or an async iterable of string pieces for streaming.

### OnQueryContext

interface · `import { OnQueryContext } from '@voicelayer/sdk'`

```ts
interface OnQueryContext
```

What `onQuery` receives beside the latest utterance.

#### Fields

| Name | Type | Required | Description |
|---|---|---|---|
| `messages` | `readonly BrainTextMessage[]` | yes | The full conversation so far (system, earlier turns and the latest user message), as text. |
| `signal` | `AbortSignal` | yes | Aborts when the caller interrupts or the turn is cancelled. Pass it to whatever you call so cancelled work stops spending tokens. |

### OnQueryResult

type · `import { OnQueryResult } from '@voicelayer/sdk'`

```ts
type OnQueryResult = string | AsyncIterable<string>
```

What `onQuery` returns: the reply as a string, or an async iterable of string pieces that are spoken as they arrive.

### BrainTextMessage

interface · `import { BrainTextMessage } from '@voicelayer/sdk'`

```ts
interface BrainTextMessage
```

One message of the conversation, as text.

#### Fields

| Name | Type | Required | Description |
|---|---|---|---|
| `role` | `'system' \| 'user' \| 'assistant'` | yes | Who wrote it: `system`, `user` or `assistant`. |
| `content` | `string` | yes | The message text. |

### onQueryHandler

function · `import { onQueryHandler } from '@voicelayer/sdk'`

```ts
onQueryHandler(onQuery: OnQuery): BrainTurnHandler
```

Turn an `onQuery` function into a brain handler. It is handed the latest utterance and the text history with the turn's abort signal. A string reply is one delta, an async iterable is streamed piece by piece, and the signal stops it. A throw is reported as a `handler_error` and the platform speaks its fallback line; an abort ends the stream with nothing more.

##### Parameters

| Name | Type | Required | Description |
|---|---|---|---|
| `onQuery` | `OnQuery` | yes | Your function. |

##### Returns

`BrainTurnHandler`: A brain handler.

### BrainTurnHandler

type · `import { BrainTurnHandler } from '@voicelayer/sdk'`

```ts
type BrainTurnHandler = (turn: WorkerBrainTurn, ctx: BrainTurnContext) => AsyncIterable<BrainTurnEvent>
```

The function the runner calls once per turn: it receives the turn and a context and yields `BrainTurnEvent`s. The framework adapters build one for you.

### BrainTurnContext

interface · `import { BrainTurnContext } from '@voicelayer/sdk'`

```ts
interface BrainTurnContext
```

What a brain handler receives with each turn.

#### Fields

| Name | Type | Required | Description |
|---|---|---|---|
| `signal` | `AbortSignal` | yes | Aborts when the caller interrupts, a newer turn takes over, the call ends or the session goes away. Turn it into the framework's own cancel: a framework that keeps running keeps spending your tokens. |
| `tools` | `BrainToolCaller` | yes | Calls VoiceLayer's tools from the brain. |

### BrainTurnEvent

type · `import { BrainTurnEvent } from '@voicelayer/sdk'`

```ts
type BrainTurnEvent = | { readonly kind: 'delta'; readonly delta: BrainDeltaBody } | { readonly kind: 'done'; readonly finishReason: string; readonly usage?: Record<string, unknown> } | { readonly kind: 'error'; readonly code: 'handler_error' | 'deadline_exceeded'; readonly message: string }
```

What a brain handler yields: any number of `delta` events carrying text, then exactly one `done` (or `error`). A handler that just ends is `done` with `stop`.

### BrainToolCaller

interface · `import { BrainToolCaller } from '@voicelayer/sdk'`

```ts
interface BrainToolCaller
```

Calls a VoiceLayer tool from inside a brain. The call crosses to the platform and runs under the same checks as any tool call, then returns its result.

#### call

```ts
call(name: string, args?: Record<string, unknown>): Promise<unknown>
```

Run a tool by name.

##### Parameters

| Name | Type | Required | Description |
|---|---|---|---|
| `name` | `string` | yes | The tool's name. |
| `args` | `Record<string, unknown>` | no | The tool's arguments. |

##### Returns

`Promise<unknown>`: The tool's result.

##### Throws

- BrainToolError when the platform refuses or the tool fails.

### BrainToolError

class · `import { BrainToolError } from '@voicelayer/sdk'`

```ts
class BrainToolError extends Error
```

A tool call from a brain that the platform refused or that failed. `code` is the platform's, such as `guard_denied`, `scope_closed` or `invalid_args`.

```ts
new BrainToolError(code: string, message?: string)
```

#### Fields

| Name | Type | Required | Description |
|---|---|---|---|
| `code` | `string` | yes | Why the tool call failed. |

### turnHistory

function · `import { turnHistory } from '@voicelayer/sdk'`

```ts
turnHistory(turn: Pick<WorkerBrainTurn, 'request'>): BrainTextMessage[]
```

The turn's history as text messages: system, user and assistant text only, with tool calls and results left out.

##### Parameters

| Name | Type | Required | Description |
|---|---|---|---|
| `turn` | `Pick<WorkerBrainTurn, 'request'>` | yes | The turn the runner handed to the brain handler. |

##### Returns

`BrainTextMessage[]`: The text messages, oldest first.

### voicelayerTools

function · `import { voicelayerTools } from '@voicelayer/sdk'`

```ts
voicelayerTools(turn: Pick<WorkerBrainTurn, 'request'>, tools: BrainToolCaller): VoiceLayerTool[]
```

The turn's tools, call control and every tool the agent has, as `VoiceLayerTool`s bound to `tools`. The platform offers each only if the agent's definition declares its capability.

##### Parameters

| Name | Type | Required | Description |
|---|---|---|---|
| `turn` | `Pick<WorkerBrainTurn, 'request'>` | yes | The turn the runner handed to the brain handler. |
| `tools` | `BrainToolCaller` | yes | The tool caller from the brain context. |

##### Returns

`VoiceLayerTool[]`: The tools.

### VoiceLayerTool

interface · `import { VoiceLayerTool } from '@voicelayer/sdk'`

```ts
interface VoiceLayerTool
```

One tool of the turn, in the shape a framework adapter registers it: a name, a description, JSON Schema parameters and a body that runs the tool through the platform.

#### Fields

| Name | Type | Required | Description |
|---|---|---|---|
| `name` | `string` | yes | The tool's name. |
| `description` | `string` | yes | What the tool does. |
| `parameters` | `Record<string, unknown>` | yes | The tool's arguments as a JSON Schema object. |

#### execute

```ts
execute(args: Record<string, unknown>): Promise<unknown>
```

Run the tool through the platform and resolve with its result.

##### Parameters

| Name | Type | Required | Description |
|---|---|---|---|
| `args` | `Record<string, unknown>` | yes | The tool's arguments. |

##### Returns

`Promise<unknown>`

##### Throws

- BrainToolError when the platform refuses or the tool fails.

### openaiAgentsBrain

function · `import { openaiAgentsBrain } from '@voicelayer/sdk'`

```ts
openaiAgentsBrain<Agent>(options: OpenAIAgentsBrainOptions<Agent>): BrainTurnHandler
```

A brain handler that runs the OpenAI Agents SDK and streams its text to the caller. A barge-in cancels the run.

##### Parameters

| Name | Type | Required | Description |
|---|---|---|---|
| `options` | `OpenAIAgentsBrainOptions<Agent>` | yes | Your `run` and `agent`, and optionally the input. |

##### Returns

`BrainTurnHandler`: A brain handler for `defineAgent({ brain })`.

##### Example

```ts
import { openaiAgentsBrain } from '@voicelayer/sdk/brain';
import { Agent, run } from '@openai/agents';

brain: openaiAgentsBrain({
  run,
  agent: () => new Agent({ name: 'helper', instructions: 'Be brief.' }),
})
```

### OpenAIAgentsBrainOptions

interface · `import { OpenAIAgentsBrainOptions } from '@voicelayer/sdk'`

```ts
interface OpenAIAgentsBrainOptions<Agent>
```

How to connect the OpenAI Agents SDK as the brain.

#### Fields

| Name | Type | Required | Default | Description |
|---|---|---|---|---|
| `run` | `(agent: Agent, input: unknown, options: { stream: true; signal: AbortSignal }) => Promise<OpenAIAgentsStreamedRun>` | yes |  | Your `run` from `@openai/agents`, or a wrapper around it. |
| `agent` | `(tools: readonly VoiceLayerTool[], turn: WorkerBrainTurn) => Agent` | yes |  | Builds the Agent for this turn, with VoiceLayer's tools as its function tools: wrap each `VoiceLayerTool` with `tool(...)` and `execute: (args) => t.execute(args)`. Without VoiceLayer tools in play it can ignore the argument. |
| `input` | `(turn: WorkerBrainTurn) => unknown` | no | `the text history as '{ role, content }' items` | The run's input from the turn. |

### claudeAgentBrain

function · `import { claudeAgentBrain } from '@voicelayer/sdk'`

```ts
claudeAgentBrain(options: ClaudeAgentBrainOptions): BrainTurnHandler
```

A brain handler that runs the Claude Agent SDK and streams its text to the caller.

##### Parameters

| Name | Type | Required | Default | Description |
|---|---|---|---|---|
| `options` | `ClaudeAgentBrainOptions` | yes |  | Your `query`, and optionally the SDK options and prompt. |
| `options.query` | `(params: { prompt: string; options: Record<string, unknown> }) => AsyncIterable<ClaudeAgentMessage>` | yes |  | Your `query` from `@anthropic-ai/claude-agent-sdk`. |
| `options.options` | `(tools: readonly VoiceLayerTool[], turn: WorkerBrainTurn) => Record<string, unknown>` | no |  | The Claude Agent SDK's options for this turn. The adapter adds `includePartialMessages: true` and the turn's `abortController` after yours, because token deltas and cancel need them. Put the in-process MCP server of the VoiceLayer tools here (`mcpServers`, `allowedTools`). |
| `options.prompt` | `(turn: WorkerBrainTurn) => string` | no | `the latest user utterance (the Claude Agent SDK keeps its own session)` | The prompt from the turn. |

##### Returns

`BrainTurnHandler`: A brain handler for `defineAgent({ brain })`.

### langgraphBrain

function · `import { langgraphBrain } from '@voicelayer/sdk'`

```ts
langgraphBrain(options: LangGraphBrainOptions): BrainTurnHandler
```

A brain handler that streams a LangGraph graph's message chunks to the caller.

##### Parameters

| Name | Type | Required | Default | Description |
|---|---|---|---|---|
| `options` | `LangGraphBrainOptions` | yes |  | Your `graph`, and optionally the input and `configurable`. |
| `options.graph` | `(tools: readonly VoiceLayerTool[], turn: WorkerBrainTurn) => LangGraphLike` | yes |  | The compiled graph for this turn, with VoiceLayer's tools in its ToolNode. |
| `options.input` | `(turn: WorkerBrainTurn) => unknown` | no | `'{ messages: [{ role, content }…] }', the text history` | The graph's input from the turn. |
| `options.configurable` | `(turn: WorkerBrainTurn) => Record<string, unknown>` | no |  | `configurable` for the run. The call id is the natural `thread_id` of a checkpointed graph. |

##### Returns

`BrainTurnHandler`: A brain handler for `defineAgent({ brain })`.

### adaptStream

function · `import { adaptStream } from '@voicelayer/sdk'`

```ts
adaptStream<T>(opts: AdaptStreamOptions<T>): AsyncGenerator<BrainTurnEvent, any, any>
```

Adapt any streaming framework to a brain handler: it yields the text deltas, stops and cancels the framework on abort, and reports a failure as an error event. Use it to write an adapter for a framework that has none.

##### Parameters

| Name | Type | Required | Default | Description |
|---|---|---|---|---|
| `opts` | `AdaptStreamOptions<T>` | yes |  | How to start the stream, read its text and cancel it. |
| `opts.start` | `(signal: AbortSignal) => AsyncIterable<T> \| Promise<AsyncIterable<T>>` | yes |  | Start the framework's stream. Receives the turn's signal: pass it on where the framework takes one. |
| `opts.text` | `(item: T) => string \| null` | yes |  | The text an item carries, or null for a tool event, a usage event or a role marker. |
| `opts.cancel` | `() => void \| Promise<void>` | no |  | The framework's own cancel, run on abort. |
| `opts.drain` | `boolean` | no | `false` | Read the rest of the stream in the background after an abort, for frameworks that need it consumed for a cancel to complete. |
| `opts.signal` | `AbortSignal` | yes |  | The turn's abort signal. |

##### Returns

`AsyncGenerator<BrainTurnEvent, any, any>`: The brain turn events.
