Skip to main content
Modify charts using natural language. Send a GraphConfig and a prompt, receive an updated GraphConfig.

Methods

generateGraph

Processes the request and returns the final result. Internally handles streaming and collects the response.
async generateGraph(
  params: GenerateGraphParams,
  onProgress?: (event: ProgressEvent) => void,
  signal?: AbortSignal
): Promise<GenerateGraphResponse>

generateGraphStream

Returns an async iterator that yields events as they arrive.
async generateGraphStream(
  params: GenerateGraphParams,
  signal?: AbortSignal
): Promise<AsyncIterableIterator<SSEEvent<GenerateGraphResponse>>>

Parameters

interface GenerateGraphParams {
  config: GraphConfig;
  userPrompt: string;
  metadata?: Metadata;
}
FieldTypeRequiredDescription
configGraphConfigYesThe current chart configuration
userPromptstringYesNatural language instruction
metadataMetadataNoRequest tracking information

Metadata

interface Metadata {
  callId?: string;
  locale?: string;
}
FieldTypeDescription
callIdstringUnique identifier for tracking and debugging
localestringLocale for responses (e.g., en-US, fr-FR)

Response

interface GenerateGraphResponse {
  config: GraphConfig;
  response: {
    message: string;
    steps?: string[];
  };
}
FieldTypeDescription
configGraphConfigUpdated chart configuration
response.messagestringExplanation of changes made
response.stepsstring[]Breakdown of individual modifications
The response is validated with Zod. Invalid responses throw an error.

Basic Usage

import { GraphyAiSdk } from '@graphysdk/ai';
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: 'month', label: 'Month' },
      { key: 'sales', label: 'Sales' },
    ],
    rows: [
      { month: 'Jan', sales: 100 },
      { month: 'Feb', sales: 120 },
      { month: 'Mar', sales: 115 },
    ],
  },
};

const result = await ai.generateGraph({
  config,
  userPrompt: 'Change this to a bar chart and sort by sales descending',
});

console.log(result.config);           // Updated GraphConfig
console.log(result.response.message); // Explanation

With Progress Callback

Use the onProgress callback to show real-time progress without full streaming:
const result = await ai.generateGraph(
  {
    config,
    userPrompt: 'Add a trend line and change colors to blue',
  },
  (progress) => {
    console.log(`${progress.percentage}% - ${progress.message}`);
  }
);

ProgressEvent

interface ProgressEvent {
  type: 'progress';
  percentage: number;
  message?: string;
  metadata?: Record<string, unknown>;
}

With Abort Signal

Cancel a request mid-operation:
const controller = new AbortController();

// Cancel after 5 seconds
setTimeout(() => controller.abort(), 5000);

try {
  const result = await ai.generateGraph(
    { config, userPrompt: 'Create a complex visualization' },
    undefined,
    controller.signal
  );
} catch (error) {
  if (error.name === 'AbortError') {
    console.log('Request cancelled');
  }
}

Streaming

For full control over the event stream:
const stream = await ai.generateGraphStream({
  config,
  userPrompt: 'Add annotations for peak values',
});

for await (const event of stream) {
  switch (event.type) {
    case 'progress':
      console.log(`${event.percentage}%`);
      break;
    case 'complete':
      console.log('Result:', event.data.config);
      break;
    case 'error':
      console.error('Error:', event.error);
      break;
  }
}
See Streaming for cancellation and React patterns.

Error Handling

import { GraphyApiError } from '@graphysdk/ai';

try {
  const result = await ai.generateGraph({
    config,
    userPrompt: 'Change to a bar chart',
  });
} catch (error) {
  if (error instanceof GraphyApiError) {
    console.error('API error:', error.message);
  } else if (error.name === 'AbortError') {
    console.log('Request cancelled');
  } else {
    console.error('Unexpected error:', error);
  }
}
See Error Handling for retry behavior and error types.