# SDK

> The @sypnia/ai package for servers and browsers: every function, its options and what it returns.

Applies to: the Sypnia engine (open source, self-hosted) and Sypnia Cloud (paid service).  
Source: https://ai.docs.sypnia.com/tools/sdk/

For agents: @sypnia/ai (MIT, TypeScript, Node 20+, Bun, Deno, edge runtimes). @sypnia/ai/server createAI({apiKey, baseUrl?, project?, defaultCase?, timeoutMs (600000), retries (2 on network/429 with retry-after)}) → chat({task|model, case?, endUser?, messages, tools?, maxToolRounds (5), stream?, budget?, store?, params?}) → {text, message, toolCalls, usage{input_tokens, output_tokens, cached_input_tokens, credits}, model, callId, finishReason}; stream → async iterator + final(); extract({task, schema (zod or JSON Schema), input, case?}) → {data}; embed({task, input, dimensions?}) → {vectors, usage}; browserTokens.create({endUser, tasks, ttlSeconds ≤600}); usage({groupBy, since}); untrusted(text). @sypnia/ai/browser createAI({project, getToken, baseUrl?}) → chat, extract, embed (browser routes only). Errors: AIError {code, status, message, callId, retryAfter}. Reads the active Telemetry case and trace.

```bash
npm install @sypnia/ai
```

TypeScript, for Node 20 or newer, Bun, Deno and edge runtimes. MIT.

## On your server: `@sypnia/ai/server`

```ts
import { createAI } from '@sypnia/ai/server';
const ai = createAI({ apiKey: process.env.SYPNIA_SECRET_KEY! });
```

| Option        | Default                        | What it does                                              |
| ------------- | ------------------------------ | --------------------------------------------------------- |
| `apiKey`      | —                              | the project's secret key, or a key made for AI            |
| `baseUrl`     | `https://ai.api.sypnia.com/v1` | your gateway's `/v1` when self-hosted                     |
| `defaultCase` | —                              | the case used when a call names none and no trace says it |
| `timeoutMs`   | `600000`                       | the longest a call may take                               |
| `retries`     | `2`                            | retries on network errors and `429` (after `retry-after`) |

| Function                                                                                       | Returns                                                                                                                  |
| ---------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| `chat({ task, case, endUser, messages, tools, maxToolRounds, stream, budget, store, params })` | `{ text, message, toolCalls, usage, model, callId, finishReason }`; with `stream: true` an async iterator with `final()` |
| `extract({ task, case, schema, input })`                                                       | `{ data, usage, callId }`: `data` typed from a zod schema or JSON Schema                                                 |
| `embed({ task, case, input, dimensions })`                                                     | `{ vectors, usage }`                                                                                                     |
| `browserTokens.create({ endUser, tasks, ttlSeconds })`                                         | `{ token, expiresAt }`, at most 600 seconds                                                                              |
| `usage({ groupBy, since })`                                                                    | rows of usage                                                                                                            |
| `untrusted(text)`                                                                              | the text wrapped as data ([Prompt injection](https://ai.docs.sypnia.com/safety/prompt-injection))                        |

`usage` is always `{ input_tokens, output_tokens, cached_input_tokens, credits }`.

## In the browser: `@sypnia/ai/browser`

```ts
import { createAI } from '@sypnia/ai/browser';
const ai = createAI({ project: 'la-espiga', getToken: () => data.auth.session() });
```

`chat`, `extract` and `embed`, for tasks with `browser: true` only ([From the browser](https://ai.docs.sypnia.com/using/from-the-browser)). The SDK exchanges and refreshes the browser token by itself.

## Errors

Every failure is an `AIError` with `code` (as in the [API](https://ai.docs.sypnia.com/api)), `status`, `message`, `callId` and, for `429`, `retryAfter`.

```ts
try { await ai.chat({ … }); }
catch (e) { if (e instanceof AIError && e.code === 'end_user_limit') return tell('TooManyQuestions'); throw e; }
```

## With Telemetry

When `@sypnia/telemetry` traces the request, the SDK sends the trace along and reads the current case, so each call appears inside it.
