# @standardagents/xai

xAI provider for Standard Agents.

This package integrates xAI Responses API language models and xAI image models through the Standard Agents provider interface. It uses the official `@ai-sdk/xai` integration under the hood and handles:

- text generation and streaming
- multimodal language requests with image inputs
- local function tools on supported Grok models
- provider-executed xAI Responses tools
- xAI reasoning controls where supported
- image generation and edit-style requests
- usage and cost extraction from xAI API responses

## Install

```bash
npm install @standardagents/xai @standardagents/spec
```

## Usage

```ts
import { xai } from '@standardagents/xai';

const provider = xai({
  apiKey: process.env.XAI_API_KEY!,
});

const result = await provider.generate({
  model: 'grok-4-0709',
  messages: [
    { role: 'user', content: 'Write a short tagline for a robotics startup.' },
  ],
});

console.log(result.content);
console.log(result.usage?.cost);
```

## Factory

The package exports:

- `xai(config)` - provider factory
- `XAIProvider` - provider class
- `xaiProviderOptions` - Zod schema for provider-specific options
- pricing helpers from `@standardagents/xai/pricing`

Factory config:

```ts
type ProviderFactoryConfig = {
  apiKey: string;
  baseUrl?: string;
  timeout?: number;
};
```

## Supported Features

Depending on the model, the provider supports:

- streaming Responses API output
- images in Responses input
- local function tool calling
- xAI provider tools (`web_search`, `x_search`, `code_execution`, plus `view_image`/`view_x_video` helpers)
- JSON mode
- reasoning controls
- image generation output

The package includes a curated static catalog for current xAI text and image models, including Grok aliases.
At runtime, `getModels()` fetches the live model list from `GET /v1/models` for
the configured xAI API key and falls back to the curated catalog if that request
is unavailable.

```ts
const models = await provider.getModels?.();
const capabilities = await provider.getModelCapabilities?.('grok-4.20-0309-reasoning');
```

## Provider Options

Common xAI-specific provider options:

- `reasoningEffort` (`low`, `medium`, `high`)
- `logprobs`
- `topLogprobs`
- `store`
- `previousResponseId`
- `include`
- `aspect_ratio`
- `output_format`
- `sync_mode`
- `resolution`
- `quality`
- `numberOfImages`

Example:

```ts
const result = await provider.generate({
  model: 'grok-4-0709',
  messages: [{ role: 'user', content: 'Search the web and summarize today in one paragraph.' }],
  providerOptions: { reasoningEffort: 'high' },
  tools: [
    {
      type: 'function',
      function: {
        name: 'web_search',
        description: 'Search the web',
        parameters: { type: 'object', properties: {}, required: [] },
      },
      executionMode: 'provider',
      executionProvider: 'xai',
    },
  ],
});
```

`view_image` and `view_x_video` are helper tool options in Standard Agents. The
xAI Responses API exposes image/video understanding through search-tool flags,
so this package folds `provider:view_image` into `enable_image_understanding` on
`web_search`/`x_search` and folds `provider:view_x_video` into
`enable_video_understanding` on `x_search`.

## Images

For language models, the provider translates Standard Agents image parts and image attachments into xAI Responses image inputs. For xAI image generation models, it routes image requests through the image generation path and returns generated image attachments in the Standard Agents response format.

Image edits preserve HTTP URLs from both `image` and `image_url` content parts.
Base64 image data uses a data URL in the request body.

## Cost Data

For xAI image generation, the package converts API-reported
`cost_in_usd_ticks` to USD and attaches the monetary value to `usage.cost`.
xAI defines 10,000,000,000 ticks as 1 USD.

The underlying `@ai-sdk/xai` language integration does not currently surface
`cost_in_usd_ticks` for Responses language calls, so language usage falls back
to the static token pricing helpers below.

Known xAI fallback pricing helpers are also exported from the package root and
the pure `@standardagents/xai/pricing` subpath. Unknown provider prices are not
guessed.

## Debugging

Use `inspectRequest()` to view the xAI-native Responses request body that will be sent to the provider:

```ts
const inspected = await provider.inspectRequest?.({
  model: 'grok-4.20-0309-non-reasoning',
  messages: [{ role: 'user', content: 'hello' }],
});

console.log(inspected?.metadata?.endpoint); // https://api.x.ai/v1/responses
console.log(inspected?.body);
```

## Notes

- xAI language models are sent through `/v1/responses`, not `/v1/chat/completions`.
- xAI tool choice translation is normalized to Responses API shapes.
- xAI image/video understanding helpers are not sent as top-level `tools[]` entries; they become search-tool options.
- xAI provider-executed tool calls are surfaced through the generic Standard Agents provider-tool result path, not local function calls.
- Non-image generic file parts are not supported in xAI Responses input; image parts are supported.
- Some moving aliases such as `grok-4` and `grok-4-latest` are resolved to the current snapshot IDs internally.

Tool-result HTTP image URLs appear as separated text links in the xAI request.
Data image URLs produce a short MIME placeholder.
The SDK omits binary tool image and file parts.

## Documentation

[Standard Agents Builder documentation](https://standardagents.ai/docs)
