#### TypeScript SDK

# Responses and streaming

Stream output as it is generated, carry conversations across turns, send images, and work with the completed response. Examples use the `client` created in the [quickstart](/developers/sdk/typescript#quickstart).

## Streaming

Set `stream: true` to receive output as the model generates it. Listen for text chunks with `on('text')`, then `await stream.done()` for the final response:

```typescript
const stream = await client.responses.create({
  model: 'grok-4.7',
  input: 'Write a short story about a curious robot.',
  stream: true,
});

const response = await stream
  .on('text', text => process.stdout.write(text))
  .done();

console.log(`\n${response.usage.total_tokens} tokens`);
```

`done()` resolves to the same `ModelResponse` object returned by a non-streamed request, and rejects if the stream fails or closes before the response completes. An error partway through a stream ends the response and isn't retried because the model may already have produced output. That also applies to `responses.create()` without `stream`, which streams under the hood. To retry failures that occur before any output, set [`retryBeforeOutput`](/developers/sdk/typescript/configuration#timeouts-retries-and-cancellation).

Reasoning models think before they answer, and at the default effort a long response can take minutes before the first text token arrives. For text that streams to a UI, set `reasoning: { effort: 'low' }` or display `'reasoning'` events while the model thinks.

Besides `'text'`, `on()` provides helper events for the rest of a response:

* `'reasoning'` — each chunk of reasoning text or reasoning summary
* `'tool_call'` — each tool call once its arguments are complete, whether your code or SpaceXSI runs it (check `call.type` to tell them apart)
* `'client_tool_call'` — each call your code runs (function tools and shell commands)
* `'server_tool_call'` — each call SpaceXSI runs (such as web search or code execution)
* `'image'` — each finished image generation call, with base64 image data in `result`
* `'citation'` — each URL citation in the answer
* `'json'` — structured output parsed so far as text arrives (see [Streaming structured output](/developers/sdk/typescript/structured-outputs#streaming-structured-output))

Each tool call event fires once, when its arguments are complete. For function tools, that is the point to execute the function. To detect when a call starts before its arguments finish streaming, listen for `'response.output_item.added'`.

```typescript
const response = await stream
  .on('reasoning', text => process.stderr.write(text))
  .on('text', text => process.stdout.write(text))
  .on('tool_call', call => console.error(`\n${call.type} ${call.status}`))
  .done();
```

`on()` also accepts any server-sent event type, such as `'response.completed'`, and passes the typed event object to the listener. Unrecognized events arrive as `'unknown'` with the original payload in `event.raw`.

You can also iterate over the stream directly with `for await`. After the loop ends, `done()` resolves immediately with the final response:

```typescript
for await (const event of stream) {
  if (event.type === 'response.function_call_arguments.delta') {
    process.stdout.write(event.delta);
  }
}

const response = await stream.done();
console.log(response.toText());
```

`stream.http` exposes the HTTP status, headers, and request IDs as soon as `create()` resolves. If you stop consuming a stream early, call `await stream.close()` to cancel its response body. See the [Streaming guide](/developers/model-capabilities/text/streaming) for full event semantics.

## Multi-turn conversations

Responses are not stored on SpaceXSI servers by default. Use `response.toInput()` to carry model output, including encrypted reasoning content, into the next turn. Reuse a single `prompt_cache_key` across turns in the same conversation to improve prompt cache routing:

```typescript
import { randomUUID } from 'node:crypto';
import { type InputItem, Grok } from '@grok/sdk';

const client = new Grok();
const promptCacheKey = `conversation:${randomUUID()}`;
const input: Array<InputItem> = [
  { role: 'user', content: 'My name is Ada. Remember it.' },
];

const first = await client.responses.create({
  model: 'grok-4.7',
  input,
  prompt_cache_key: promptCacheKey,
});

const second = await client.responses.create({
  model: 'grok-4.7',
  input: [
    ...input,
    ...first.toInput(),
    { role: 'user', content: 'What is my name?' },
  ],
  prompt_cache_key: promptCacheKey,
});

console.log(second.toText());
```

Use a distinct `prompt_cache_key` for each unrelated conversation.

To continue a server-stored response by ID instead, opt in to storage with `store: true`:

```typescript
const first = await client.responses.create({
  model: 'grok-4.7',
  input: 'My name is Ada. Remember it.',
  store: true,
});

const second = await client.responses.create({
  model: 'grok-4.7',
  input: 'What is my name?',
  previous_response_id: first.id,
  store: true,
});
```

### Compacting long conversations

Every stateless turn resends the conversation history, so input token counts grow with length. Compact a conversation into an encrypted item with `client.responses.compact()`, then start the next input with `compacted.output`. Continuing the `toInput()` example above:

```typescript
const compacted = await client.responses.compact({
  model: 'grok-4.7',
  input: [
    ...input,
    ...first.toInput(),
    { role: 'user', content: 'What is my name?' },
    ...second.toInput(),
  ],
});

const third = await client.responses.create({
  model: 'grok-4.7',
  input: [
    ...compacted.output,
    { role: 'user', content: 'Spell my name backwards.' },
  ],
  prompt_cache_key: promptCacheKey,
});

console.log(third.toText());
```

Pass `compacted.output` unchanged and append new turns after it. The conversation must still fit within the model's context window when compacted. `compacted.usage` reports the tokens used by compaction, and `dropped_message_count` reports how many messages it replaced. See [Context Compaction](/developers/advanced-api-usage/context-compaction) for details.

## Image input

Pass a public image URL alongside text using an `input_image` content part:

```typescript
const response = await client.responses.create({
  model: 'grok-4.7',
  input: [
    {
      role: 'user',
      content: [
        { type: 'input_text', text: 'Describe this image.' },
        {
          type: 'input_image',
          image_url: 'https://example.com/image.jpg',
          detail: 'high',
        },
      ],
    },
  ],
});

console.log(response.toText());
```

For a local image, pass a `Blob` or `File` as `image`. The SDK converts it to a data URL before sending the request and detects JPEG, PNG, or WebP from the leading bytes when the `Blob` has no MIME type:

```typescript
import { readFile } from 'node:fs/promises';

const bytes = new Uint8Array(await readFile('./image.png'));
const image = new Blob([bytes], { type: 'image/png' });

const response = await client.responses.create({
  model: 'grok-4.7',
  input: [
    {
      role: 'user',
      content: [
        { type: 'input_text', text: 'What is in this image?' },
        { type: 'input_image', image },
      ],
    },
  ],
});
```

## Working with responses

Every completed `ModelResponse` exposes:

* `response.toText()` — concatenates all output text parts
* `response.toInput()` — returns output items formatted for a subsequent turn
* `response.toJson(schema?)` — parses completed JSON output and optionally validates it with a Standard Schema validator
* `response.parsed` — non-throwing JSON parse (`null` if incomplete or invalid)
* `response.output` — typed array of output items
* `response.usage` — token counts, server-side tool use, and `cost_usd` when available
* `response.http` — HTTP status, headers, SpaceXSI request ID (`requestId`), and client request ID (`clientRequestId`)
* `response.watermarked` — `true` when the API watermarked the text output (see [Watermarking](#watermarking))
* `response.raw` — raw response object from the API, including fields added after your SDK version

Use the exported type guards to inspect `response.output`:

```typescript
import { isFunctionCall, isMessage, isReasoning } from '@grok/sdk';

for (const item of response.output) {
  if (isMessage(item)) {
    console.log('message', item.content);
  } else if (isFunctionCall(item)) {
    console.log('function', item.name, item.arguments);
  } else if (isReasoning(item)) {
    console.log('reasoning item', item.id);
  }
}
```

### Watermarking

When [output watermarking](/developers/advanced-api-usage/watermarking) is enabled for a model, the API includes the `x-watermark: true` response header. `response.watermarked` returns `true` when that header is present and `false` otherwise:

```typescript
const response = await client.responses.create({
  model: 'grok-4.7',
  input: 'Write a haiku about the ocean.',
});

console.log(response.watermarked);
```

With `stream: true`, `stream.watermarked` is available as soon as `create()` resolves, alongside `stream.http`. See [Output Watermarking](/developers/advanced-api-usage/watermarking) for supported models and team configuration in the SpaceXSI Console.

## Response storage

The SDK defaults to `store: false` on `responses.create()`, which differs from the REST API wire default (`true`). With storage disabled, the SDK automatically requests `reasoning.encrypted_content` so `response.toInput()` preserves reasoning state across turns.

Encrypted reasoning items can be large: `grok-4.20-multi-agent` sends the state of all its agents in one stream event. Each stream event, like a buffered JSON response, is bounded by `maxResponseBodyBytes` (32 MiB by default).

Pass `store: true` when you want to retrieve, inspect, continue, or delete a response by ID:

```typescript
const stored = await client.responses.create({
  model: 'grok-4.7',
  input: 'Save this response.',
  store: true,
});

const fetched = await client.responses.get(stored.id);
const inputItems = await client.responses.inputItems.list(stored.id);
await client.responses.delete(stored.id);
```

## Priority processing

Set `service_tier` to `'priority'` or `'fast'` for lower latency at priority rates. Both values behave identically: models with a fast deployment use that deployment and its rates, and other models prioritize the request ahead of standard traffic. Check `response.service_tier` to confirm which tier served the request:

```typescript
const response = await client.responses.create({
  model: 'grok-4.7',
  input: 'Explain the Riemann hypothesis in one paragraph.',
  service_tier: 'fast',
});

console.log(response.service_tier);
```

See [Priority Processing](/developers/advanced-api-usage/priority-processing) for pricing and availability.
