Skip to content

AI Chat in Editor

Starting from SDK 2.8.0, editor mode supports an AI Chat panel. Users can start AI requests inside the embedded editor. The host page listens for those requests, forwards them to the Dino-GSP backend through the host backend, and passes the streaming response back to the SDK.

You can first open the 13-ai-chat.html example to try the complete integration.

This capability is useful when you want to:

  • Let users generate or modify geometry with natural language inside a question bank, lesson-planning system, or courseware authoring tool.
  • Reuse the Dino-GSP editor inside an AI tutor while converting Dino-GSP backend results into interactive geometry.
  • Put AI generation and manual editing into the same content-production workflow.

How It Works

AI Chat is a host-managed bridge:

  1. The user enters a prompt in the embedded editor's AI Chat panel.
  2. The embedded editor sends an aiRequest to the SDK.
  3. The host page listens with editor.on('aiRequest', ...) and sends the request to the host backend.
  4. The host backend checks business permissions/quotas and calls the Dino-GSP embedded-mode AI drawing API.
  5. The host page passes the Dino-GSP backend streaming response to the editor through editor.ai.consumeStream().
  6. The editor displays the AI response and updates conversation/geometry state.

Prerequisites

  1. Use @dajiaoai/algeo-sdk@2.8.0 or later.
  2. Use editor mode through createEditor(...) with a valid auth.appId.
  3. Configure your application in the Open Platform console, including allowed domains and related access settings.
  4. Prepare a host backend endpoint that safely forwards requests to the Dino-GSP backend.

Do not put server-side API tokens or billing credentials in browser code. appId can be used on the frontend; server credentials should stay on your backend.

1. Create the Editor and Show AI Chat

typescript
import { createEditor } from '@dajiaoai/algeo-sdk';

const editor = await createEditor(document.getElementById('algeo-editor')!, {
  auth: {
    appId: 'YOUR_APP_ID',
  },
  ui: {
    navbar: true,
    aiChatPanel: true,
  },
});

You can also enable the AI Chat panel later:

typescript
await editor.mode.setUiConfig({
  aiChatPanel: true,
});

2. Listen for AI Requests

When the user starts an AI conversation in the editor, the SDK emits aiRequest:

typescript
editor.on('aiRequest', async ({ payload, signal }) => {
  const response = await fetch('/api/algeo-ai/chat', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(payload),
    signal,
  });

  if (!response.ok || !response.body) {
    throw new Error('AI service request failed');
  }

  await editor.ai.consumeStream({
    stream: response.body,
    signal,
  });
});

payload is the AI request context generated by the editor. Integrators usually do not need to understand or manually construct every field. The recommended flow is to send payload from the aiRequest callback to your host backend, then let the host backend forward it as-is to the Dino-GSP backend. Model selection, context parsing, and geometry instruction processing are handled by the Dino-GSP backend.

You only need to inspect its fields when debugging, recording audit logs, or coordinating with the Dino-GSP backend. For normal integrations, forward it as-is.

3. Host Backend Forwarding

The host backend does not need to implement model calls or streaming protocol details by itself. It usually does three things:

  1. Check whether the current user is allowed to use AI features for this app.
  2. Check the current application's quota, plan, or business usage rules.
  3. Call the Dino-GSP embedded-mode AI drawing API and pass the returned SSE response back to the frontend.

The /api/algeo-ai/chat endpoint in the frontend example is your host backend endpoint. The browser should not call the Dino-GSP backend directly:

typescript
const DINO_GSP_AI_RUN_ENDPOINT =
  'https://api.dajiaoai.com/api/v1/embedded/ai/run';

app.post('/api/algeo-ai/chat', async (req, res) => {
  await assertUserCanUseAi(req.user);

  const upstream = await fetch(DINO_GSP_AI_RUN_ENDPOINT, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${process.env.DAJIAOAI_API_TOKEN}`,
    },
    body: JSON.stringify(req.body),
    signal: req.signal,
  });

  res.status(upstream.status);
  upstream.body?.pipeTo(Writable.toWeb(res));
});

4. Dino-GSP AI Drawing API

The host backend calls the Dino-GSP Open Platform embedded-mode AI drawing API. The API returns a standard SSE stream that can be passed back to the frontend and then into editor.ai.consumeStream().

MethodPathDescription
POST/api/v1/embedded/ai/runCreate one AI drawing run and stream results through SSE
POST/api/v1/embedded/ai/cancelCancel frontend stream delivery for a specific run

Create a Run

  • Base URL: https://api.dajiaoai.com
  • Auth: Authorization: Bearer <API_KEY>
  • Content-Type: application/json
  • Request body: use the payload from the SDK aiRequest event directly
  • Response: text/event-stream

The host backend does not need to manually construct model parameters or message structure. Forward the payload received from the frontend as the request body:

typescript
const upstream = await fetch('https://api.dajiaoai.com/api/v1/embedded/ai/run', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    Authorization: `Bearer ${process.env.DAJIAOAI_API_TOKEN}`,
  },
  body: JSON.stringify(payload),
});

The API first returns a run.created event so the client can know the run_id:

text
event: run.created
data: {"run_id":"run_xxx"}

It then streams response.* events. Integrators do not need to parse those events to update the canvas. Pass the full response.body to the SDK:

typescript
await editor.ai.consumeStream({
  stream: response.body,
  signal,
});

Cancel a Run

When the user cancels generation, call the cancel endpoint:

http
POST https://api.dajiaoai.com/api/v1/embedded/ai/cancel
Authorization: Bearer djo_xxx
Content-Type: application/json
json
{
  "run_id": "run_xxx",
  "reason": "user_cancel"
}

The cancel endpoint stops the current SSE delivery. An AI request already submitted to the Dino-GSP backend may still produce token usage and be settled. Rely on the final usage shown by the console or backend records.

5. Cancellation and Errors

When the user cancels, a newer request supersedes the active request, or the SDK instance is destroyed, use the aiCancel event to observe cancellation state:

typescript
editor.on('aiCancel', ({ runId, reason }) => {
  console.log('AI request canceled', runId, reason);
});

reason values:

ValueDescription
userThe user canceled the request
supersededA newer request replaced the active one
destroyedThe SDK instance was destroyed

If the host does not register an aiRequest listener, the editor receives an error response indicating that no handler is configured.

Authentication Model

SDK Authentication

Editor mode requires auth.appId. The appId identifies your Open Platform application and is used to validate access origin and application configuration.

typescript
const editor = await createEditor(container, {
  auth: {
    appId: 'YOUR_APP_ID',
  },
});

appId is not a server secret and may appear in frontend code. Do not expose server API tokens, model keys, or billing credentials in the browser.

AI Service Authentication

The actual model request is handled by the Dino-GSP backend. The host backend should handle:

  • User login/session validation.
  • Application permission checks.
  • Quota or subscription checks.
  • Dino-GSP server-side API token management.
  • Risk control, audit logs, and request tracing.

The browser only sends payload to the host backend; it should not directly access the Dino-GSP server-side API token. The host backend should forward that payload to the Dino-GSP backend.

Billing Model

SDK AI Chat is a bridge capability. The SDK forwards AI requests from the editor to the host and forwards Dino-GSP backend streaming results, returned through the host, back to the editor.

Actual cost follows the Dino-GSP Open Platform AI billing rules. The host backend may additionally enforce its own user quota, plan, or business-side billing display.

Billing LayerNotes
Dino-GSP in-canvas AI capabilityCharged by actual token usage × model price; per-call point consumption is available in the application details page of the console
Host business quotaThe host may enforce user quota, plan, usage count, or risk rules, and can also calculate usage from the usage + model values returned by SSE
Browser frontendDoes not hold server billing credentials or call Dino-GSP backend directly

Billing is settled based on actual AI token usage produced by the Dino-GSP backend. /api/v1/embedded/ai/run shares the same point account with other Open Platform APIs, so embedded mode does not require separate top-up. Client-side cancellation or SSE disconnection only stops the current stream delivery and may not stop an AI request that has already started on the backend; if token usage is produced, it is charged by actual consumption.

We recommend recording user, application, latency, success/failure status, and usage returned by the Dino-GSP backend on the host backend for quota control, billing reconciliation, and debugging.

Minimal Integration Checklist

  • Upgrade to @dajiaoai/algeo-sdk@2.8.0 or later.
  • Use createEditor with auth.appId.
  • Enable aiChatPanel in ui.
  • Listen for aiRequest.
  • Handle user auth and quota checks on the host backend.
  • Call /api/v1/embedded/ai/run from the host backend and pass the SSE response back to the frontend.
  • Use consumeStream on the frontend to handle the Dino-GSP backend stream returned through the host backend.
  • Handle cancellation, timeouts, and errors.