> ## Documentation Index
> Fetch the complete documentation index at: https://docs.graphy.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Mutation Agent

Transform a chart's dataset with natural language. Send a `GraphConfig` and a prompt, receive a `GraphConfig` with the dataset reshaped — filtered, grouped, aggregated, derived, and sorted.

## Methods

### generateMutation

Processes the request and returns the final result. Internally handles streaming and collects the response.

```typescript theme={null}
async generateMutation(
  params: GenerateMutationParams,
  onProgress?: (event: ProgressEvent) => void,
  signal?: AbortSignal
): Promise<GenerateMutationResponse>
```

### generateMutationStream

Returns an async iterator that yields events as they arrive.

```typescript theme={null}
async generateMutationStream(
  params: GenerateMutationParams,
  signal?: AbortSignal
): Promise<AsyncIterableIterator<SSEEvent<GenerateMutationResponse>>>
```

## Parameters

```typescript theme={null}
interface GenerateMutationParams {
  config: GraphConfig;
  userPrompt?: string;
  metadata?: Metadata;
}
```

| Field        | Type          | Required | Description                                                         |
| ------------ | ------------- | -------- | ------------------------------------------------------------------- |
| `config`     | `GraphConfig` | Yes      | The current chart configuration, including the dataset to transform |
| `userPrompt` | `string`      | No       | Natural language description of the transformation to apply         |
| `metadata`   | `Metadata`    | No       | Request tracking information                                        |

## Response

```typescript theme={null}
interface GenerateMutationResponse {
  response: {
    message: string;
    steps: string[];
  };
  config: GraphConfig;
}
```

| Field              | Type          | Description                                              |
| ------------------ | ------------- | -------------------------------------------------------- |
| `response.message` | `string`      | Explanation of the transformations applied               |
| `response.steps`   | `string[]`    | Ordered breakdown of each transformation step            |
| `config`           | `GraphConfig` | Updated chart configuration with the transformed dataset |

The response is validated with Zod. Invalid responses throw an error.

***

## Basic Usage

```typescript theme={null}
import { GraphyAiSdk } from '@graphysdk/agents-sdk';
import type { GraphConfig } from '@graphysdk/core';

const ai = new GraphyAiSdk({
  apiKey: process.env.GRAPHY_API_KEY,
  baseUrl: 'https://agents.graphy.dev',
});

const config: GraphConfig = {
  type: 'column',
  data: {
    columns: [
      { key: 'region', label: 'Region' },
      { key: 'sales', label: 'Sales' },
    ],
    rows: [
      { region: 'North', sales: 100 },
      { region: 'South', sales: 80 },
      { region: 'North', sales: 120 },
      { region: 'South', sales: 95 },
    ],
  },
};

const result = await ai.generateMutation({
  config,
  userPrompt: 'Total sales by region, sorted highest first',
});

console.log(result.config); // GraphConfig with the aggregated dataset
console.log(result.response.steps); // Ordered list of transformations applied
```

***

## With Progress Callback

Use the `onProgress` callback to show real-time progress without full streaming:

```typescript theme={null}
const result = await ai.generateMutation(
  {
    config,
    userPrompt: 'Keep only the last 12 months and add a 3-month moving average',
  },
  (progress) => {
    console.log(progress.message);
  }
);
```

***

## Streaming

For full control over the event stream:

```typescript theme={null}
import { isProgressEvent, isCompleteEvent, isErrorEvent } from '@graphysdk/agents-sdk';

const stream = await ai.generateMutationStream({
  config,
  userPrompt: 'Filter to the EMEA region and rank by revenue',
});

for await (const event of stream) {
  if (isProgressEvent(event)) {
    console.log(event.message);
  }

  if (isCompleteEvent(event)) {
    console.log('Result:', event.data.config);
  }

  if (isErrorEvent(event)) {
    console.error('Error:', event.error);
  }
}
```

See [Streaming](/agents/sdk/streaming) for cancellation and React patterns.

***

## Error Handling

```typescript theme={null}
import { isGraphyApiError } from '@graphysdk/agents-sdk';

try {
  const result = await ai.generateMutation({
    config,
    userPrompt: 'Group sales by region',
  });
} catch (error) {
  if (isGraphyApiError(error)) {
    console.error('API error:', error.message);
  }
}
```

See [Error Handling](/agents/sdk/errors) for retry behavior and error types.
