@proveanything/smartlinks 2.1.39 → 2.1.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/README.md +754 -754
  2. package/dist/README.md +573 -573
  3. package/dist/adminCardsView.js +55 -55
  4. package/dist/adminViews.d.ts +1 -1
  5. package/dist/adminViews.js +3 -1
  6. package/dist/ai-tools.d.ts +2 -1
  7. package/dist/ai-tools.js +3 -0
  8. package/dist/api/ai.d.ts +2 -21
  9. package/dist/api/ai.js +0 -35
  10. package/dist/api/collection.d.ts +8 -1
  11. package/dist/api/collection.js +10 -0
  12. package/dist/api/index.d.ts +1 -0
  13. package/dist/api/index.js +1 -0
  14. package/dist/api/knowledge.d.ts +64 -0
  15. package/dist/api/knowledge.js +97 -0
  16. package/dist/baseline.css +194 -194
  17. package/dist/docs/API_SUMMARY.md +1046 -964
  18. package/dist/docs/admin-cards.md +189 -189
  19. package/dist/docs/admin-views.md +257 -255
  20. package/dist/docs/agent-tools.md +156 -156
  21. package/dist/docs/ai-tools-and-skills.md +180 -180
  22. package/dist/docs/ai.md +1721 -1834
  23. package/dist/docs/analytics.md +39 -39
  24. package/dist/docs/app-data-storage.md +277 -277
  25. package/dist/docs/app-docs.md +73 -73
  26. package/dist/docs/app-manifest.md +852 -852
  27. package/dist/docs/app-records-pattern.md +388 -388
  28. package/dist/docs/appConfig.md +550 -550
  29. package/dist/docs/assistant-apps.md +172 -172
  30. package/dist/docs/assistant-context.md +119 -119
  31. package/dist/docs/bookings.md +442 -442
  32. package/dist/docs/comms.md +686 -686
  33. package/dist/docs/connectors.md +340 -340
  34. package/dist/docs/css-baseline.md +133 -133
  35. package/dist/docs/customer-guide.md +70 -70
  36. package/dist/docs/deploying-apps.md +340 -340
  37. package/dist/docs/entitlements.md +90 -90
  38. package/dist/docs/files.md +69 -69
  39. package/dist/docs/host-dependency-contract.md +210 -210
  40. package/dist/docs/integrations.md +322 -322
  41. package/dist/docs/interactions.md +545 -545
  42. package/dist/docs/item-context.md +181 -181
  43. package/dist/docs/knowledge.md +102 -0
  44. package/dist/docs/lots.md +111 -111
  45. package/dist/docs/loyalty.md +352 -352
  46. package/dist/docs/members.md +182 -182
  47. package/dist/docs/mobile-admin-container.md +693 -693
  48. package/dist/docs/operations.md +281 -281
  49. package/dist/docs/overview.md +482 -482
  50. package/dist/docs/proof-comms-triggers.md +142 -142
  51. package/dist/docs/proof-ownership-transfer.md +155 -155
  52. package/dist/docs/proof-product-data-scoping.md +462 -462
  53. package/dist/docs/proof-share-grants.md +305 -305
  54. package/dist/docs/realtime.md +138 -138
  55. package/dist/docs/records-admin-pattern.md +304 -304
  56. package/dist/docs/standard-query.md +187 -187
  57. package/dist/docs/tag-codes.md +97 -97
  58. package/dist/docs/theme-tokens.md +252 -252
  59. package/dist/docs/wallet-passes.md +107 -107
  60. package/dist/docs/websites.md +123 -123
  61. package/dist/openapi.yaml +320 -306
  62. package/dist/theme-boot.js +78 -78
  63. package/dist/theme.css +75 -75
  64. package/dist/types/ai.d.ts +9 -91
  65. package/dist/types/appManifest.d.ts +21 -0
  66. package/dist/types/collection.d.ts +26 -0
  67. package/dist/types/index.d.ts +1 -0
  68. package/dist/types/index.js +1 -0
  69. package/dist/types/knowledge.d.ts +120 -0
  70. package/dist/types/knowledge.js +2 -0
  71. package/docs/API_SUMMARY.md +1046 -964
  72. package/docs/admin-cards.md +189 -189
  73. package/docs/admin-views.md +257 -255
  74. package/docs/agent-tools.md +156 -156
  75. package/docs/ai-tools-and-skills.md +180 -180
  76. package/docs/ai.md +1721 -1834
  77. package/docs/analytics.md +39 -39
  78. package/docs/app-data-storage.md +277 -277
  79. package/docs/app-docs.md +73 -73
  80. package/docs/app-manifest.md +852 -852
  81. package/docs/app-records-pattern.md +388 -388
  82. package/docs/appConfig.md +550 -550
  83. package/docs/assistant-apps.md +172 -172
  84. package/docs/assistant-context.md +119 -119
  85. package/docs/bookings.md +442 -442
  86. package/docs/comms.md +686 -686
  87. package/docs/connectors.md +340 -340
  88. package/docs/css-baseline.md +133 -133
  89. package/docs/customer-guide.md +70 -70
  90. package/docs/deploying-apps.md +340 -340
  91. package/docs/entitlements.md +90 -90
  92. package/docs/files.md +69 -69
  93. package/docs/host-dependency-contract.md +210 -210
  94. package/docs/integrations.md +322 -322
  95. package/docs/interactions.md +545 -545
  96. package/docs/item-context.md +181 -181
  97. package/docs/knowledge.md +102 -0
  98. package/docs/lots.md +111 -111
  99. package/docs/loyalty.md +352 -352
  100. package/docs/members.md +182 -182
  101. package/docs/mobile-admin-container.md +693 -693
  102. package/docs/operations.md +281 -281
  103. package/docs/overview.md +482 -482
  104. package/docs/proof-comms-triggers.md +142 -142
  105. package/docs/proof-ownership-transfer.md +155 -155
  106. package/docs/proof-product-data-scoping.md +462 -462
  107. package/docs/proof-share-grants.md +305 -305
  108. package/docs/realtime.md +138 -138
  109. package/docs/standard-query.md +187 -187
  110. package/docs/tag-codes.md +97 -97
  111. package/docs/theme-lookbook.v1.json +120 -120
  112. package/docs/theme-tokens.md +252 -252
  113. package/docs/wallet-passes.md +107 -107
  114. package/docs/websites.md +123 -123
  115. package/openapi.yaml +320 -306
  116. package/package.json +87 -87
  117. package/scripts/headless-check.mjs +87 -87
  118. package/scripts/lib/bare-imports.mjs +57 -57
  119. package/scripts/lib/keyed-app-data.mjs +21 -21
  120. package/scripts/publish.mjs +272 -272
  121. package/scripts/register-release.mjs +91 -91
package/docs/ai.md CHANGED
@@ -1,1834 +1,1721 @@
1
- # SmartLinks AI
2
-
3
- Build AI-powered SmartLinks experiences with a practical SDK guide for responses, chat, product assistants, streaming, voice, and real-world integration patterns.
4
-
5
- ---
6
-
7
- ## Table of Contents
8
-
9
- - [Overview](#overview)
10
- - [Quick Start](#quick-start)
11
- - [Authentication](#authentication)
12
- - [Responses API](#responses-api)
13
- - [Chat Completions](#chat-completions)
14
- - [RAG: Product Assistants](#rag-product-assistants)
15
- - [Voice Integration](#voice-integration)
16
- - [Podcast Generation](#podcast-generation)
17
- - [Types & API reference](#types--api-reference)
18
- - [Usage Examples](#usage-examples)
19
- - [Error Handling](#error-handling)
20
- - [Rate Limiting](#rate-limiting)
21
- - [Best Practices](#best-practices)
22
- - [Providing Content to the AI Assistant](#providing-content-to-the-ai-assistant)
23
-
24
- ---
25
-
26
- ## Overview
27
-
28
- This guide is written for SDK users building real products, not backend operators. It focuses on the public SDK surface, recommended starting points, and examples you can adapt directly.
29
-
30
- ### Start with the path that matches your job
31
-
32
- | If you want to... | Start here |
33
- |---|---|
34
- | Build a new AI workflow | Use [Responses API](#responses-api) |
35
- | Add compatibility with existing chat clients | Use [Chat Completions](#chat-completions) |
36
- | Build a product/manual assistant | Use [RAG: Product Assistants](#rag-product-assistants) |
37
- | Add spoken input/output | Use [Voice Integration](#voice-integration) |
38
- | Add progressive rendering | Use [Streaming Responses](#streaming-responses) or [Streaming Chat](#streaming-chat) |
39
-
40
- > **Which AI chat API? Three surfaces, three jobs — don't confuse them:**
41
- > - **`ai.chat.responses`** — the **default for new work**. Structured input, tool use, multi-agent, streaming; you manage any history. Reach for this first.
42
- > - **`ai.chat.completions`** — **OpenAI-compatible** (`messages[]`). Use it *only* to drop into existing OpenAI-style code; prefer Responses for anything new.
43
- > - **`ai.public.chat`** (+ `getSession` / `clearSession`) — the **public product assistant** with **server-managed conversation sessions** (RAG-grounded). This is the "ongoing conversation" surface, and it's public-facing.
44
- >
45
- > Responses and Completions are *generation* APIs (not single-shot vs conversation — both take history); `ai.public.chat` is the one that keeps a conversation for you.
46
-
47
- ### Recommended starting points
48
-
49
- - New AI features: start with `ai.chat.responses.create(...)`
50
- - Product/manual assistants: start with `ai.public.chat(...)`
51
- - Existing OpenAI-style clients: use `ai.chat.completions.create(...)`
52
- - Real-time voice: use `ai.public.getToken(...)` and your provider's live client
53
-
54
- SmartLinks AI provides five main capabilities:
55
-
56
- 1. **Responses API** - Preferred API for agentic workflows, multimodal inputs, and tool-driven responses
57
- 2. **Chat Completions** - OpenAI-compatible text generation with streaming and tool calling
58
- 3. **RAG (Retrieval-Augmented Generation)** - Document-grounded Q&A for product assistants
59
- 4. **Voice Integration** - Voice-to-text and text-to-voice for hands-free interaction
60
- 5. **Podcast Generation** - NotebookLM-style multi-voice conversational podcasts from documents
61
-
62
- ### Key Features
63
-
64
- - ✅ Full TypeScript support with type safety
65
- - ✅ Streaming responses with async iterators
66
- - ✅ Automatic rate limit handling
67
- - ✅ Session management for conversations
68
- - ✅ Voice input/output helpers
69
- - ✅ Tool/function calling support
70
- - ✅ OpenAI-style Responses API support
71
- - ✅ Document indexing and retrieval
72
- - ✅ Customizable assistant behavior
73
-
74
- ---
75
-
76
- ## Quick Start
77
-
78
- If you're only reading one section, start here. The three snippets below cover the most common public SDK use cases.
79
-
80
- ### 1. Generate a response
81
-
82
- ```typescript
83
- import { initializeApi, ai } from '@proveanything/smartlinks';
84
-
85
- // Initialize the SDK
86
- initializeApi({
87
- baseURL: 'https://smartlinks.app/api/v1',
88
- apiKey: process.env.SMARTLINKS_API_KEY // Required for admin endpoints
89
- });
90
-
91
- // Preferred: create a response
92
- const response = await ai.chat.responses.create('my-collection', {
93
- model: 'google/gemini-2.5-flash',
94
- input: 'Summarize the key safety steps for descaling a coffee maker.'
95
- });
96
-
97
- console.log(response.output_text);
98
- ```
99
-
100
- ### 2. Build a product assistant
101
-
102
- ```typescript
103
- import { initializeApi, ai } from '@proveanything/smartlinks';
104
-
105
- initializeApi({ baseURL: 'https://smartlinks.app/api/v1' });
106
-
107
- const answer = await ai.public.chat('my-collection', {
108
- productId: 'coffee-maker-deluxe',
109
- userId: 'user-123',
110
- message: 'How do I descale this machine?'
111
- });
112
-
113
- console.log(answer.message);
114
- ```
115
-
116
- ### 3. Stream output into your UI
117
-
118
- ```typescript
119
- const stream = await ai.chat.responses.create('my-collection', {
120
- input: 'Write a launch checklist for a new product page.',
121
- stream: true
122
- });
123
-
124
- for await (const event of stream) {
125
- if (event.type === 'response.output_text.delta') {
126
- updateUi(event.delta);
127
- }
128
- }
129
- ```
130
-
131
- ---
132
-
133
- ## Authentication
134
-
135
- ### Admin Endpoints
136
-
137
- Admin endpoints require an API key passed during initialization:
138
-
139
- ```typescript
140
- initializeApi({
141
- baseURL: 'https://smartlinks.app/api/v1',
142
- apiKey: process.env.SMARTLINKS_API_KEY
143
- });
144
- ```
145
-
146
- The SDK automatically includes the API key in the `Authorization: Bearer <token>` header.
147
-
148
- ### Public Endpoints
149
-
150
- Public endpoints don't require an API key but are rate-limited by `userId`:
151
-
152
- ```typescript
153
- // No API key needed
154
- const response = await ai.public.chat('my-collection', {
155
- productId: 'coffee-maker',
156
- userId: 'user-123',
157
- message: 'How do I clean this?'
158
- });
159
- ```
160
-
161
- ---
162
-
163
- ## Responses API
164
-
165
- The Responses API is the recommended starting point for new integrations. Use it when you want a single endpoint for structured input, tool use, and streaming output.
166
-
167
- ### Basic Response
168
-
169
- ```typescript
170
- const response = await ai.chat.responses.create('my-collection', {
171
- model: 'google/gemini-2.5-flash',
172
- input: 'Write a friendly two-sentence welcome for a product assistant.'
173
- });
174
-
175
- console.log(response.output_text);
176
- ```
177
-
178
- ### Multimessage Input
179
-
180
- ```typescript
181
- const response = await ai.chat.responses.create('my-collection', {
182
- model: 'google/gemini-2.5-flash',
183
- input: [
184
- {
185
- role: 'system',
186
- content: [
187
- { type: 'input_text', text: 'You are a concise support assistant.' }
188
- ]
189
- },
190
- {
191
- role: 'user',
192
- content: [
193
- { type: 'input_text', text: 'Give me three troubleshooting steps for a grinder that will not start.' }
194
- ]
195
- }
196
- ]
197
- });
198
-
199
- console.log(response.output_text);
200
- ```
201
-
202
- ### Streaming Responses
203
-
204
- When you pass `stream: true`, the SDK returns an `AsyncIterable` of SSE events instead of a final JSON object. You do not need to parse raw SSE frames yourself — just iterate with `for await...of`.
205
-
206
- ```typescript
207
- const result = await ai.chat.responses.create('my-collection', {
208
- input: 'Summarize the manual',
209
- stream: true
210
- });
211
-
212
- for await (const event of result) {
213
- if (event.type === 'response.output_text.delta') {
214
- process.stdout.write(event.delta);
215
- }
216
- }
217
- ```
218
-
219
- If you omit `stream: true`, the same method returns the final `ResponsesResult` object instead.
220
-
221
- ```typescript
222
- const stream = await ai.chat.responses.create('my-collection', {
223
- model: 'google/gemini-2.5-flash',
224
- input: 'Explain how to descale an espresso machine step by step.',
225
- stream: true
226
- });
227
-
228
- for await (const event of stream) {
229
- if (event.type === 'response.output_text.delta') {
230
- process.stdout.write(event.delta);
231
- }
232
- }
233
- ```
234
-
235
- ### Tool Calling
236
-
237
- ```typescript
238
- const response = await ai.chat.responses.create('my-collection', {
239
- model: 'google/gemini-2.5-flash',
240
- input: 'What is the weather in Paris?',
241
- tools: [
242
- {
243
- type: 'function',
244
- name: 'get_weather',
245
- description: 'Get the current weather for a city',
246
- parameters: {
247
- type: 'object',
248
- properties: {
249
- location: { type: 'string' }
250
- },
251
- required: ['location']
252
- }
253
- }
254
- ]
255
- });
256
-
257
- console.log(response.output);
258
- ```
259
-
260
- ### Server-side tools (built-in agent loop)
261
-
262
- The example above is **client-relayed** tool calling: you define the tools, the model returns
263
- `tool_call` requests, and *your app* executes them and sends results back. For the common tools —
264
- reading and searching the web, vision, reading documents, generating images — the platform ships a
265
- curated, tested **built-in toolset it runs itself**. Opt in with `server_tools` and the server
266
- executes each tool and feeds the result back automatically, looping until the model has its answer.
267
- You get one final response; no relay code.
268
-
269
- ```typescript
270
- // Enable the whole built-in toolset:
271
- const res = await ai.chat.responses.create('my-collection', {
272
- model: 'balanced',
273
- input: 'Research acme.com and summarise what they sell, with their brand colours.',
274
- server_tools: true
275
- });
276
- console.log(res.output_text);
277
- console.log(res._agent.toolResults); // trace: which tools ran, with what result
278
- ```
279
-
280
- Scope it to specific tools (recommended — smaller blast radius, faster), by name or capability:
281
-
282
- ```typescript
283
- import { AI_TOOL_NAMES } from '@proveanything/smartlinks';
284
-
285
- const res = await ai.chat.responses.create('my-collection', {
286
- input: 'Find the current price of this product and return it as JSON.',
287
- server_tools: [AI_TOOL_NAMES.WEB_SEARCH, AI_TOOL_NAMES.DATA_EXTRACT],
288
- // or: allowCapabilities: ['web:read'], exclude: ['image.generate'],
289
- maxSteps: 6 // cap model round-trips (1–12, default 8)
290
- });
291
- ```
292
-
293
- **Streaming** surfaces tool progress as it happens — ideal for a "thinking…" UI. You get
294
- `agent.tool_call` / `agent.tool_result` events, then a final `response.completed`:
295
-
296
- ```typescript
297
- const stream = await ai.chat.responses.create('my-collection', {
298
- input: 'Research acme.com', server_tools: true, stream: true
299
- });
300
- for await (const ev of stream) {
301
- if (ev.type === 'agent.tool_call') showStep(`Running ${ev.name}…`);
302
- if (ev.type === 'agent.tool_result') showStep(`${ev.name} done`);
303
- if (ev.type === 'response.completed') render(ev.response.output_text);
304
- }
305
- ```
306
-
307
- `server_tools` can't be combined with `previous_response_id`/`conversation` yet — pass prior turns
308
- in `input`.
309
-
310
- #### Built-in tools
311
-
312
- | Tool | Does |
313
- |------|------|
314
- | `web.search` | Live web search → candidate results (url/title/description). |
315
- | `web.fetchPage` | Fetch a page → clean markdown + metadata + schema.org JSON-LD. |
316
- | `web.extractSchema` | Return only a page's schema.org data of a given `@type` (deterministic). |
317
- | `document.read` | Read a document at a URL — **PDF, deck, doc**, or article — into markdown. |
318
- | `data.extract` | Page + JSON-schema/prompt → **typed JSON** (turn a page into UI data). |
319
- | `brand.assets` | Extract a site's logo, colours, and design. |
320
- | `web.screenshot` | Screenshot a page → hosted image URL (feed to `image.describe`). |
321
- | `image.describe` | Vision: describe an image / read its text. |
322
- | `image.generate` | Generate an image from a prompt → hosted URL. |
323
- | `image.fromReference` | Image-to-image: generate guided by reference image(s). |
324
- | `image.searchStock` | Search real stock photos (Unsplash). |
325
- | `image.transform` | Resize / crop / rotate / grayscale / format-convert / compress → hosted URL. |
326
- | `pdf.create` | Render HTML (or one fragment per page) → PDF, 1:1: exact `width`/`height`/`unit` for labels, `pages[]` for many pages in one render, no scripts, only SmartLinks/Google Fonts/data: resources. `return`: `url` (public), `signedUrl` (expiring), `base64`. Cached by input. |
327
- | `pdf.fill` | Fill an AcroForm PDF's fields (`{ field: value }`) → hosted URL. |
328
- | `pdf.merge` | Merge several PDFs into one, in order → hosted URL. |
329
- | `pdf.inspect` | Cheap, no-AI introspection: page count/sizes, which pages have a real text layer, raster present, and a routing hint (`text` vs `vision`). |
330
- | `pdf.render` | Rasterize one page — or just a region (`clip: { x0, y0, x1, y1 }`, 0–1 from top-left) — to a PNG at a chosen DPI → hosted image URL (permanent). Max 40 MP per call; larger requests return `code: "too_large"` + `suggestedDpi`. |
331
- | `image.ocr` | **Deterministic OCR** (Google Vision, no generative model): exact characters with per-word `confidence` (0–1) and pixel `bbox`, plus lines with spacing as printed. Input: `imageUrl`, or a PDF `url` + `page` + `dpi` + optional `clip`. Optional `languages` hints. Use for small print and text outlined to curves. |
332
- | `pdf.extract` | PDF → typed JSON in one call (schema and/or prompt). Auto-routes text vs vision. Optional per-field `confidence`/`source` (`includeConfidence`) and `bbox` (`includeBoxes`) in `fieldsMeta`. |
333
- | `pdf.decodeBarcodes` | Deterministically decode barcodes/QR on a page (WASM, no AI) → value + symbology + page + bbox + confidence. Use this for barcode digits, never vision. |
334
- | `pdf.inspectGraphics` | Prepress inspection: per-page path/image/outlined-text counts + colour spaces, plus named SPOT colours (e.g. "PANTONE 871 C"). No AI. |
335
- | `pdf.edit` | Edit an existing PDF: replace **live** text (glyph-exact removal, neighbours never move; original font when it has the glyphs, else an embedded fallback; CMYK/spot colour kept; matches may span lines), add text / images in boxes (`colorSpace: "cmyk"` converts images for print). Per-item `results` with `verified`. |
336
- | `pdf.preflight` | Prepress preflight, no changes: fonts, RGB/Lab, TrimBox/BleedBox + bleed, effective image dpi, transparency, white overprint, annotations, hidden layers, output intent. No AI. |
337
- | `pdf.printReady` | Text outlined to curves, RGB→CMYK with a press profile (spot colours kept), comments removed, layers merged as chosen, mark PDF/X-1a or PDF/X-4 with the output intent embedded, then preflight the result → `{ url, report }`. Options for grey, spot conversion, downsampling, pages, crop marks and more (below). |
338
- | `http.request` | SSRF-guarded outbound HTTP(S) to a public URL (call a REST API). |
339
- | `translate` | Translate text into one or more languages (generic, model-based). |
340
-
341
- **Working with PDFs.** The PDF tools split into *read/analyse* and *produce*:
342
-
343
- - **Read a whole PDF as text** → `document.read` (Firecrawl; good for prose/decks).
344
- - **Turn a PDF into structured fields** → `pdf.extract` (give it a JSON schema and/or a prompt; it
345
- returns typed JSON). It routes itself, but you can drive the route yourself: call `pdf.inspect`
346
- first (deterministic, no AI) to see whether each page has a real text layer, then `pdf.extract`
347
- (cheap text path) or `pdf.render` → `image.describe`/vision for curve-only or raster artwork.
348
- - **Read small print exactly** (INCI/allergen lists, net weight, text outlined to curves) → `image.ocr`
349
- with a PDF `url`, `page`, `dpi: 300–400` and a `clip` around the panel. It returns the characters it
350
- sees with a per-word confidence — it never "corrects" a misspelling the way a vision model can, so
351
- flag words below ~0.9 for human review rather than re-reading them with a model.
352
- - **Zoom in visually** (layout, artwork) → `pdf.render` with `clip` to rasterise just a region at a high
353
- DPI, instead of the whole sheet. Renders over 40 MP return `code: "too_large"` with `suggestedDpi`
354
- — retry at that dpi or with a smaller clip, don't blind-retry.
355
- - **Barcodes / QR** → `pdf.decodeBarcodes` (deterministic WASM decode) — never trust vision for barcode
356
- digits; it hallucinates them.
357
- - **Prepress / print QA** (spot colours, colour spaces, vector vs raster) → `pdf.inspectGraphics`.
358
- - **Change the artwork itself** → `pdf.edit`. `replaceText` edits only LIVE text: the matched glyphs are
359
- cut out with an exact-width gap (nothing else moves) and the new text is drawn at the same spot, in the
360
- same colour, in the original font if its embedded glyphs cover the new text (otherwise an embedded
361
- fallback, reported as `usedFallbackFont`). A replacement longer than the original is flagged in `note`
362
- — it may run into neighbouring text. Text outlined to curves can't be edited: the item fails with
363
- "not found as live text" — put it on the designer change list. `verified: true` means the new text
364
- reads back from the output.
365
- - **Is it print-ready?** → `pdf.preflight` (report only; `stats.layers` lists the file's layers).
366
- **Make it print-ready** → `pdf.printReady`. By default it outlines all text to curves, converts
367
- RGB/Lab to CMYK for the `outputIntent` (e.g. `FOGRA39`), keeps spot colours, removes comments and
368
- links, merges layers as the file shows them (hidden layers left out) and marks the file PDF/X-4.
369
- `report.changes` says what was done, measured on the output; `report.compliant` comes from
370
- preflighting the OUTPUT, so remaining issues (low-res images, missing bleed, white overprint) are
371
- reported rather than hidden. Options:
372
-
373
- | Option | Values |
374
- |---|---|
375
- | `profile` | `pdfx-4` (default), `pdfx-1a` (CMYK + spot only), `none` (convert, no PDF/X marking) |
376
- | `outputIntent` | `FOGRA39` (default), `FOGRA51`, `FOGRA52`, `FOGRA29`, `GRACoL2006`, `SWOP2006`, `JapanColor2011` |
377
- | `colour` | `cmyk` (default), `gray`, `keep` |
378
- | `spotColours` | `keep` (default) or `convert` to process colour |
379
- | `outlineFonts` | `true` (default) text → curves; `false` keeps live text (fonts embedded with `embedFonts`, default true) |
380
- | `layers` | `{ hide: ['Dieline'], show: [...] }` by name — e.g. print without the dieline |
381
- | `annotations` | `remove` (default), `flatten` (draw into the artwork), `keep` |
382
- | `pages` | `"1-3,5"` (default all) |
383
- | `downsample` | `{ dpi: 300 }` — resample images placed above 1.5× that; off by default |
384
- | `bleed` | `{ mm: 3 }` — required bleed, checked and reported, never added |
385
- | `bleedIncluded` | `{ mm: 3 }` — the artwork already includes its bleed: sets TrimBox/BleedBox |
386
- | `cropMarks` | `{}` or `{ offsetMm, lengthMm, weightPt }` — crop marks outside the bleed |
387
- | `flattenTransparency` | PDF/X-1a only: affected pages become images. Default false |
388
-
389
- Outlined text can't be edited or searched afterwards: keep the source PDF for changes and regenerate.
390
-
391
- ```ts
392
- const edited = await SL.ai.tools.run(collectionId, 'pdf.edit', {
393
- url: artworkUrl,
394
- replaceText: [{ id: 'f1', page: 1, find: 'Best before: see lid', replace: 'Best before: see base' }],
395
- })
396
- const ready = await SL.ai.tools.run(collectionId, 'pdf.printReady', {
397
- url: edited.result.url, profile: 'pdfx-4', outputIntent: 'FOGRA39', bleed: { mm: 3 },
398
- layers: { hide: ['Dieline'] }, cropMarks: {},
399
- })
400
- if (!ready.result.report.compliant) showFindings(ready.result.report.findings)
401
- ```
402
- - **A review UI that flags guessed fields** → `pdf.extract` with `includeConfidence` (per-field
403
- confidence + source) and `includeBoxes` (per-field bbox on text-native pages) in `fieldsMeta`.
404
- - **Produce a PDF** → `pdf.create` (HTML → PDF), `pdf.fill` (populate an AcroForm's fields),
405
- `pdf.merge` (combine several). `pdf.create` takes an exact page size (`width`, `height`, `unit`) or a
406
- `format`, `html` or `pages: [html, …]` (one per page, sharing `head`), and returns `url` (public),
407
- a `signedUrl` that expires, or `base64` (`return`). JavaScript doesn't run, and images, fonts and
408
- stylesheets load only from SmartLinks hosts, Google Fonts or `data:` URIs. From a server function:
409
- `ctx.sl.tools.run('pdf.create', …)` with the `tools:pdf.create` capability (server-functions.md).
410
-
411
- Every tool is also directly callable without the model loop via `ai.tools.run(collectionId, name,
412
- args)` — e.g. render a page or extract fields straight from a UI, no agent round-trip:
413
-
414
- ```ts
415
- // Read the ingredients panel of a sleeve exactly (deterministic OCR of a clipped region)
416
- const { result } = await SL.ai.tools.run(collectionId, 'image.ocr', {
417
- url: sleevePdfUrl, page: 1, dpi: 400,
418
- clip: { x0: 0.40, y0: 0.20, x1: 0.60, y1: 0.40 },
419
- languages: ['en', 'fr'],
420
- })
421
- // result.lines → [{ text: 'INGREDIENTS: Aqua, Glycerin, …', confidence: 0.97, bbox: {…} }]
422
- const toReview = result.words.filter((w) => w.confidence < 0.9)
423
- ```
424
-
425
- Discover tools two ways:
426
- - **Design time (typed):** import `BUILTIN_AI_TOOLS`, `AI_TOOL_NAMES`, and the per-tool arg types
427
- (`WebSearchArgs`, `DataExtractArgs`, `PdfExtractArgs`, …) from the SDK. This is the core set —
428
- stable, versioned, documented here.
429
- - **Runtime (live):** `await ai.catalog(collectionId)` returns the registry as the server sees it,
430
- including any future app-contributed tools. The built-in set above is always present.
431
-
432
- ### Recommended Models
433
-
434
- Pass either a full model id (`openai/gpt-6.1-sol`) or a tier alias (`'cheap'`, `'balanced'`,
435
- `'premium'`) as `model` — both resolve through the same server-side model registry. The tiers are the
436
- GPT-6 family (prices per 1M tokens, input / output, OpenAI list price):
437
-
438
- | Tier | Model | Alias | Price | Use for |
439
- |------|-------|-------|-------|---------|
440
- | Cheapest (default) | `openai/gpt-6-luna` | `'cheap'` / omit `model` | $0.10 / $0.50 | Everyday chat, high-volume/simple turns |
441
- | Balanced | `openai/gpt-6.1-sol` | `'balanced'` | $2 / $10 | Admin agent / tool-heavy workflows (the `v1/responses` default) |
442
- | Most capable | `openai/gpt-6-astra` | `'premium'` | $10 / $50 | The hardest reasoning, coding and long multi-step tool use |
443
-
444
- The previous generation stays available by id — `openai/gpt-5.6-luna` ($0.20 / $1.20),
445
- `openai/gpt-5.6-terra` ($2 / $12) and `openai/gpt-5.6-sol` ($4 / $20) — and `ai.models.list(collectionId)` returns
446
- the full current set. GPT-6.1 Sol is the same input price as GPT-5.6 Terra with cheaper output, so prefer
447
- the tiers. If OpenAI refuses a GPT-6 request for a model/option reason, SmartLinks retries it once on the
448
- GPT-5.6 equivalent, so a call never fails just because a GPT-6 model doesn't accept something yet.
449
-
450
- Every tier supports function/tool calling, Programmatic Tool Calling, and Multi-agent (see below), and all
451
- three accept `service_tier: 'flex'` (≈50% cheaper, Batch-API rates, slower) or `'priority'` (premium, guaranteed
452
- throughput) alongside the default `'standard'` tier. Pass it straight through in the request body:
453
-
454
- ```typescript
455
- const response = await ai.chat.responses.create('my-collection', {
456
- model: 'balanced',
457
- input: 'Summarize this week\'s ingested documents.',
458
- service_tier: 'flex' // non-interactive/background work: cheaper, but can take minutes
459
- });
460
- ```
461
-
462
- Flex requests run noticeably slower — reserve `flex` for non-production/background work (batch enrichment,
463
- evaluations, async jobs), not user-facing chat turns. The server already raises its own timeout to 15
464
- minutes for any request with `service_tier: 'flex'`, matching OpenAI's guidance — nothing to configure on
465
- the client. On a `429` ("resource unavailable") the request wasn't charged; retry with backoff or drop
466
- `service_tier` (or set it to `'auto'`) to fall back to standard processing.
467
-
468
- ### Programmatic Tool Calling
469
-
470
- Lets the model write a short in-memory program that orchestrates several tool calls (filtering,
471
- looping, aggregating) before handing back one result, instead of a full message round-trip per
472
- call. Add the hosted `programmatic_tool_calling` tool, and mark each function tool the program is
473
- allowed to invoke with `allowed_callers: ['programmatic']`:
474
-
475
- ```typescript
476
- const response = await ai.chat.responses.create('my-collection', {
477
- model: 'balanced',
478
- input: 'Compare inventory with demand for every SKU in this collection.',
479
- tools: [
480
- {
481
- type: 'function',
482
- name: 'get_inventory',
483
- description: 'Return available_units for a sku',
484
- parameters: { type: 'object', properties: { sku: { type: 'string' } }, required: ['sku'] },
485
- output_schema: { type: 'object', properties: { sku: { type: 'string' }, available_units: { type: 'number' } } },
486
- allowed_callers: ['programmatic']
487
- },
488
- {
489
- type: 'function',
490
- name: 'get_demand',
491
- description: 'Return requested_units for a sku',
492
- parameters: { type: 'object', properties: { sku: { type: 'string' } }, required: ['sku'] },
493
- output_schema: { type: 'object', properties: { sku: { type: 'string' }, requested_units: { type: 'number' } } },
494
- allowed_callers: ['programmatic']
495
- },
496
- { type: 'programmatic_tool_calling' }
497
- ]
498
- });
499
- ```
500
-
501
- The response's `output` array can include a `program` item (the generated code), one
502
- `function_call` item per program-issued call (tagged with `caller: { type: 'program', caller_id }`),
503
- and a `program_output` item with the program's final `result`/`status`. Execute the `function_call`
504
- items as normal and send results back keyed by their `call_id` on the next turn.
505
-
506
- ### Multi-agent (subagents)
507
-
508
- Lets the root agent spawn a tree of subagents that run in parallel and get synthesized back into
509
- one response — useful for tasks that split cleanly into independent workstreams (e.g. research +
510
- draft + review). Enable it by setting `multi_agent.enabled: true` — that's the entire contract on
511
- your end; nothing else to configure or pass.
512
-
513
- This is upstream beta functionality (OpenAI may still be limiting it to certain accounts/rollout),
514
- so treat behavior and availability as subject to change until it's GA.
515
-
516
- ```typescript
517
- const response = await ai.chat.responses.create('my-collection', {
518
- model: 'premium', // Sol recommended for the root agent when spawning subagents
519
- input: 'Research three competitor loyalty programs, then draft a comparison summary.',
520
- multi_agent: { enabled: true, max_concurrent_subagents: 3 }
521
- });
522
- ```
523
-
524
- Subagent output arrives as additional items in `output`, each tagged `agent: { agent_name: '/root/<name>' }`
525
- (root agent output uses `/root`). Notes/limits carried over from OpenAI's beta:
526
-
527
- - `max_concurrent_subagents` defaults to `3`
528
- - `reasoning.summary` and `max_tool_calls` are not supported while multi-agent is enabled
529
- - Streaming is not supported while multi-agent is enabled — the SDK throws if you pass both
530
- `stream: true` and `multi_agent.enabled: true`
531
-
532
- ---
533
-
534
- ## Chat Completions
535
-
536
- OpenAI-compatible chat completions with streaming and tool calling support. Use this for compatibility with existing Chat Completions integrations; prefer the Responses API for new agentic features.
537
-
538
- ### Basic Chat
539
-
540
- ```typescript
541
- const response = await ai.chat.completions.create('my-collection', {
542
- model: 'google/gemini-2.5-flash',
543
- messages: [
544
- { role: 'system', content: 'You are a helpful assistant.' },
545
- { role: 'user', content: 'What is the capital of France?' }
546
- ]
547
- });
548
-
549
- console.log(response.choices[0].message.content);
550
- // Output: "The capital of France is Paris."
551
- ```
552
-
553
- ### Streaming Chat
554
-
555
- Stream responses in real-time for better UX:
556
-
557
- - Set `stream: true`
558
- - The SDK returns an `AsyncIterable<ChatCompletionChunk>`
559
- - Iterate over chunks with `for await...of`
560
- - Read incremental text from `chunk.choices[0]?.delta?.content`
561
- - If `stream` is omitted or `false`, the method returns the normal `ChatCompletionResponse`
562
-
563
- ```typescript
564
- const stream = await ai.chat.completions.create('my-collection', {
565
- model: 'google/gemini-2.5-flash',
566
- messages: [
567
- { role: 'user', content: 'Write a short poem about coding' }
568
- ],
569
- stream: true
570
- });
571
-
572
- for await (const chunk of stream) {
573
- const content = chunk.choices[0]?.delta?.content || '';
574
- process.stdout.write(content);
575
- }
576
- ```
577
-
578
- ### Tool/Function Calling
579
-
580
- Define tools (functions) that the AI can call:
581
-
582
- ```typescript
583
- const tools = [
584
- {
585
- type: 'function',
586
- function: {
587
- name: 'get_weather',
588
- description: 'Get the current weather for a location',
589
- parameters: {
590
- type: 'object',
591
- properties: {
592
- location: {
593
- type: 'string',
594
- description: 'City name'
595
- },
596
- unit: {
597
- type: 'string',
598
- enum: ['celsius', 'fahrenheit']
599
- }
600
- },
601
- required: ['location']
602
- }
603
- }
604
- }
605
- ];
606
-
607
- const response = await ai.chat.completions.create('my-collection', {
608
- model: 'google/gemini-2.5-flash',
609
- messages: [
610
- { role: 'user', content: 'What\'s the weather in Paris?' }
611
- ],
612
- tools
613
- });
614
-
615
- const toolCall = response.choices[0].message.tool_calls?.[0];
616
- if (toolCall) {
617
- console.log('Function:', toolCall.function.name);
618
- console.log('Arguments:', JSON.parse(toolCall.function.arguments));
619
- // { location: "Paris", unit: "celsius" }
620
- }
621
- ```
622
-
623
- ### Available Models
624
-
625
- ```typescript
626
- // List all available models
627
- const models = await ai.models.list('my-collection');
628
-
629
- // Or filter by provider / capability
630
- const openAiModels = await ai.models.list('my-collection', {
631
- provider: 'openai'
632
- });
633
-
634
- const visionModels = await ai.models.list('my-collection', {
635
- capability: 'vision'
636
- });
637
-
638
- models.data.forEach(model => {
639
- console.log(`${model.name}`);
640
- console.log(` Provider: ${model.provider}`);
641
- console.log(` Context: ${model.contextWindow} tokens`);
642
- console.log(` Pricing: $${model.pricing.input}/1M input tokens`);
643
- });
644
-
645
- // Get specific model info
646
- const model = await ai.models.get('my-collection', 'google/gemini-2.5-flash');
647
- console.log(model.capabilities); // ['text', 'vision', 'audio', 'code']
648
- ```
649
-
650
- Use `ai.models.list(collectionId)` as the source of truth for what your collection can use at runtime. The public docs provide recommendations, but actual availability depends on the SmartLinks model catalog exposed to that collection.
651
-
652
- **Recommended Models:**
653
-
654
- | Model | Use Case | Speed | Cost |
655
- |-------|----------|-------|------|
656
- | `openai/gpt-5.4` | Default for new agentic and structured-output workflows | Balanced | Medium |
657
- | `openai/gpt-5-mini` | Lower-cost general purpose and JSON tasks | Fast | Low |
658
- | `google/gemini-2.5-flash` | Fast multimodal and cost-sensitive general use | Fast | Low |
659
- | `google/gemini-2.5-pro` | Complex reasoning and heavier multimodal tasks | Slower | Higher |
660
-
661
- If you want a safe default for most new work, start with `openai/gpt-5.4`. If you want a lower-cost fallback, use `openai/gpt-5-mini` or `google/gemini-2.5-flash` depending on your latency and pricing goals.
662
-
663
- ---
664
-
665
- ## RAG: Product Assistants
666
-
667
- Create intelligent product assistants that answer questions based on product documentation.
668
-
669
- ### Setup: Index Documents
670
-
671
- First, index your product documentation:
672
-
673
- ```typescript
674
- // Index a product manual from URL
675
- const result = await ai.rag.indexDocument('my-collection', {
676
- productId: 'coffee-maker-deluxe',
677
- documentUrl: 'https://example.com/manuals/coffee-maker.pdf',
678
- chunkSize: 500, // Tokens per chunk
679
- overlap: 50, // Token overlap between chunks
680
- provider: 'openai' // Embedding provider
681
- });
682
-
683
- console.log(`Indexed ${result.chunks} chunks`);
684
- console.log(`Dimensions: ${result.metadata.embeddingDimensions}`);
685
-
686
- // Or index from text directly
687
- await ai.rag.indexDocument('my-collection', {
688
- productId: 'coffee-maker-deluxe',
689
- text: 'Your product manual content here...',
690
- metadata: {
691
- source: 'manual',
692
- version: '2.0'
693
- }
694
- });
695
- ```
696
-
697
- ### Configure Assistant
698
-
699
- Customize the assistant's behavior:
700
-
701
- ```typescript
702
- await ai.rag.configureAssistant('my-collection', {
703
- productId: 'coffee-maker-deluxe',
704
- systemPrompt: 'You are a helpful coffee maker assistant. Be concise and friendly.',
705
- model: 'google/gemini-2.5-flash',
706
- temperature: 0.7,
707
- maxTokensPerResponse: 500,
708
- rateLimitPerUser: 20,
709
- allowedTopics: ['usage', 'cleaning', 'troubleshooting'],
710
- customInstructions: {
711
- tone: 'friendly',
712
- additionalRules: 'Always include safety warnings when relevant.'
713
- }
714
- });
715
- ```
716
-
717
- ### Public Chat
718
-
719
- Users can chat with the product assistant without authentication:
720
-
721
- ```typescript
722
- // First question
723
- const response = await ai.public.chat('my-collection', {
724
- productId: 'coffee-maker-deluxe',
725
- userId: 'user-123',
726
- message: 'How do I descale my coffee maker?'
727
- });
728
-
729
- console.log('Answer:', response.message);
730
- console.log('Used', response.context.chunksUsed, 'document sections');
731
- console.log('Top similarity:', response.context.topSimilarity);
732
- ```
733
-
734
- ### Conversation History
735
-
736
- Maintain conversation context with sessions:
737
-
738
- ```typescript
739
- const sessionId = `session-${Date.now()}`;
740
-
741
- // First question
742
- const q1 = await ai.public.chat('my-collection', {
743
- productId: 'coffee-maker-deluxe',
744
- userId: 'user-123',
745
- message: 'How do I clean it?',
746
- sessionId
747
- });
748
-
749
- // Follow-up question (uses history)
750
- const q2 = await ai.public.chat('my-collection', {
751
- productId: 'coffee-maker-deluxe',
752
- userId: 'user-123',
753
- message: 'How often should I do that?',
754
- sessionId
755
- });
756
-
757
- // Get full conversation history
758
- const session = await ai.public.getSession('my-collection', sessionId);
759
- console.log('Messages:', session.messages);
760
- console.log('Total messages:', session.messageCount);
761
-
762
- // Clear session when done
763
- await ai.public.clearSession('my-collection', sessionId);
764
- ```
765
-
766
- ### Session Management
767
-
768
- ```typescript
769
- // Get session statistics (admin)
770
- const stats = await ai.sessions.stats('my-collection');
771
- console.log('Total sessions:', stats.totalSessions);
772
- console.log('Active sessions:', stats.activeSessions);
773
- console.log('Total messages:', stats.totalMessages);
774
- console.log('Rate-limited users:', stats.rateLimitedUsers);
775
- ```
776
-
777
- ---
778
-
779
- ## Voice Integration
780
-
781
- Enable voice input and output for hands-free interaction.
782
-
783
- ### Voice Patterns
784
-
785
- The SDK supports three practical voice patterns:
786
-
787
- | Pattern | Best For | SDK Building Blocks |
788
- |---------|----------|---------------------|
789
- | Voice → Text → AI → Text | Manual helper Q&A, troubleshooting steps | `ai.voice.listen()` + `ai.public.chat()` |
790
- | Voice → Text → AI → Voice | Hands-free assistants, accessibility | `ai.voice.listen()` + `ai.public.chat()` + `ai.voice.speak()` or `ai.tts.generate()` |
791
- | Real-time Voice | Low-latency spoken conversation | `ai.public.getToken()` + Gemini Live client |
792
-
793
- ### Current SDK Support
794
-
795
- - `ai.voice.listen()` and `ai.voice.speak()` are browser helpers built on the Web Speech APIs.
796
- - `ai.public.getToken()` generates ephemeral tokens for Gemini Live sessions.
797
- - `ai.tts.generate()` supports server-side text-to-speech generation.
798
- - The SDK does not currently expose a first-class transcription endpoint like Whisper; if you need that flow, implement it as your own backend endpoint and feed the transcribed text into `ai.public.chat()` or `ai.chat.responses.create()`.
799
-
800
- ### Recommended Approach
801
-
802
- For product assistants and RAG-backed support, start with Voice → Text → AI → Text/Voice. It gives you the best control over retrieval, session history, and cost. Use Gemini Live when low-latency spoken conversation matters more than deep document grounding.
803
-
804
- ### Browser Voice Helpers
805
-
806
- These helpers are browser-only and rely on native speech recognition / speech synthesis support.
807
-
808
- ```typescript
809
- // Check if voice is supported
810
- if (ai.voice.isSupported()) {
811
- // Listen for voice input
812
- const question = await ai.voice.listen('en-US');
813
- console.log('User said:', question);
814
-
815
- // Get answer from AI
816
- const response = await ai.public.chat('my-collection', {
817
- productId: 'coffee-maker-deluxe',
818
- userId: 'user-123',
819
- message: question
820
- });
821
-
822
- // Speak the answer
823
- await ai.voice.speak(response.message, {
824
- voice: 'alloy',
825
- rate: 1.0
826
- });
827
- }
828
- ```
829
-
830
- ### Voice Assistant Class
831
-
832
- Create a complete voice assistant:
833
-
834
- ```typescript
835
- class ProductVoiceAssistant {
836
- private collectionId: string;
837
- private productId: string;
838
- private userId: string;
839
- private sessionId: string;
840
-
841
- constructor(config: {
842
- collectionId: string;
843
- productId: string;
844
- userId: string;
845
- }) {
846
- this.collectionId = config.collectionId;
847
- this.productId = config.productId;
848
- this.userId = config.userId;
849
- this.sessionId = `voice-${Date.now()}`;
850
- }
851
-
852
- async ask(): Promise<string> {
853
- // Listen for question
854
- console.log('Listening...');
855
- const question = await ai.voice.listen();
856
-
857
- // Get answer
858
- console.log('Processing...');
859
- const response = await ai.public.chat(this.collectionId, {
860
- productId: this.productId,
861
- userId: this.userId,
862
- message: question,
863
- sessionId: this.sessionId
864
- });
865
-
866
- // Speak answer
867
- console.log('Speaking...');
868
- await ai.voice.speak(response.message);
869
-
870
- return response.message;
871
- }
872
-
873
- async getRemainingQuestions(): Promise<number> {
874
- const status = await ai.public.getRateLimit(this.collectionId, this.userId);
875
- return status.remaining;
876
- }
877
- }
878
-
879
- // Usage
880
- const assistant = new ProductVoiceAssistant({
881
- collectionId: 'my-collection',
882
- productId: 'coffee-maker-deluxe',
883
- userId: 'user-123'
884
- });
885
-
886
- await assistant.ask(); // Voice question → Voice answer
887
- const remaining = await assistant.getRemainingQuestions();
888
- console.log(`${remaining} questions remaining`);
889
- ```
890
-
891
- ### Gemini Live Integration
892
-
893
- Generate ephemeral tokens for Gemini Live (multimodal voice):
894
-
895
- Use this path for real-time voice sessions. The SDK only issues the short-lived token; the actual live connection is made with the provider client.
896
-
897
- ```typescript
898
- // Generate token for voice session
899
- const token = await ai.public.getToken('my-collection', {
900
- settings: {
901
- ttl: 3600, // 1 hour
902
- voice: 'alloy',
903
- language: 'en-US'
904
- }
905
- });
906
-
907
- console.log('Token:', token.token);
908
- console.log('Expires at:', new Date(token.expiresAt));
909
-
910
- // Use token with Gemini Live API
911
- // (See Google's Gemini documentation)
912
- ```
913
-
914
- ### Voice + RAG Guidance
915
-
916
- For document-grounded assistants, prefer this pattern:
917
-
918
- 1. Capture voice with `ai.voice.listen()` or your own transcription flow.
919
- 2. Send the transcribed text to `ai.public.chat()`.
920
- 3. Render the text response for readability.
921
- 4. Optionally speak the answer with `ai.voice.speak()` or `ai.tts.generate()`.
922
-
923
- This is usually a better fit for manuals and procedural guidance than trying to use a live voice session as the primary retrieval layer.
924
-
925
- ---
926
-
927
- ## Podcast Generation
928
-
929
- Generate NotebookLM-style multi-voice conversational podcasts from product documentation.
930
-
931
- ### Generate a Podcast
932
-
933
- ```typescript
934
- const podcast = await ai.podcast.generate('my-collection', {
935
- productId: 'coffee-maker-deluxe',
936
- duration: 5, // Target 5 minutes
937
- style: 'casual', // 'casual' | 'professional' | 'educational' | 'entertaining'
938
- voices: {
939
- host1: 'nova', // Female voice
940
- host2: 'onyx' // Male voice
941
- },
942
- includeAudio: true // Generate audio files
943
- });
944
-
945
- console.log('Podcast Title:', podcast.script.title);
946
- console.log('Duration:', podcast.metadata.duration, 'seconds');
947
- console.log('Download:', podcast.audio?.mixedUrl);
948
- ```
949
-
950
- ### Available Voices
951
-
952
- | Voice | Gender | Personality | Best For |
953
- |-------|--------|-------------|----------|
954
- | `alloy` | Neutral | Balanced, neutral | Professional podcasts |
955
- | `echo` | Male | Clear, authoritative | Expert/teacher role |
956
- | `fable` | Neutral | Warm, storytelling | Narrative content |
957
- | `onyx` | Male | Deep, engaging | Main host, discussions |
958
- | `nova` | Female | Friendly, enthusiastic | Co-host, questions |
959
- | `shimmer` | Female | Bright, energetic | Entertaining content |
960
-
961
- **Recommended Combinations:**
962
- - **Casual**: Nova + Onyx - Friendly and engaging
963
- - **Professional**: Alloy + Echo - Authoritative and clear
964
- - **Educational**: Fable + Echo - Teaching style
965
- - **Entertaining**: Shimmer + Onyx - High energy
966
-
967
- ### Access the Script
968
-
969
- ```typescript
970
- // View the generated script
971
- podcast.script.segments.forEach((segment, i) => {
972
- const speaker = segment.speaker === 'host1' ? 'Host 1' : 'Host 2';
973
- console.log(`${speaker}: ${segment.text}`);
974
- });
975
- ```
976
-
977
- ### Check Generation Status
978
-
979
- For long-running podcast generation, poll for status:
980
-
981
- ```typescript
982
- // Start generation
983
- const podcast = await ai.podcast.generate('my-collection', {
984
- productId: 'coffee-maker-deluxe',
985
- duration: 10,
986
- includeAudio: true
987
- });
988
-
989
- // Poll for status
990
- const checkStatus = async () => {
991
- const status = await ai.podcast.getStatus('my-collection', podcast.podcastId);
992
-
993
- console.log(`Status: ${status.status} (${status.progress}%)`);
994
-
995
- if (status.status === 'completed' && status.result) {
996
- console.log('Podcast ready!');
997
- console.log('Listen:', status.result.audio?.mixedUrl);
998
- return true;
999
- } else if (status.status === 'failed') {
1000
- console.error('Generation failed:', status.error);
1001
- return true;
1002
- }
1003
-
1004
- return false;
1005
- };
1006
-
1007
- // Check every 5 seconds
1008
- const interval = setInterval(async () => {
1009
- const done = await checkStatus();
1010
- if (done) clearInterval(interval);
1011
- }, 5000);
1012
- ```
1013
-
1014
- ### Text-to-Speech (TTS)
1015
-
1016
- Generate custom audio from text:
1017
-
1018
- ```typescript
1019
- const audioBlob = await ai.tts.generate('my-collection', {
1020
- text: 'Welcome to our podcast about coffee makers!',
1021
- voice: 'nova',
1022
- speed: 1.0,
1023
- format: 'mp3'
1024
- });
1025
-
1026
- // Create audio URL for playback
1027
- const audioUrl = URL.createObjectURL(audioBlob);
1028
- ```
1029
-
1030
- ---
1031
-
1032
-
1033
- ## Types & API reference
1034
-
1035
- Full TypeScript types and the per-endpoint HTTP reference for every `SL.ai.*` method live in the
1036
- **generated** references — they're not duplicated here so they can't drift:
1037
-
1038
- - **[`API_SUMMARY.md`](API_SUMMARY.md)** — every function signature + type (search `ai.`).
1039
- - **[`openapi.yaml`](../openapi.yaml)** — the raw HTTP endpoints.
1040
-
1041
- For inline types, use LSP hover / go-to-definition on `SL.ai.*`.
1042
-
1043
- ## Usage Examples
1044
-
1045
- ### Example 1: Product FAQ Bot
1046
-
1047
- ```typescript
1048
- async function createProductFAQ() {
1049
- const collectionId = 'my-collection';
1050
- const productId = 'coffee-maker-deluxe';
1051
-
1052
- // 1. Index product documentation
1053
- await ai.rag.indexDocument(collectionId, {
1054
- productId,
1055
- documentUrl: 'https://example.com/manual.pdf'
1056
- });
1057
-
1058
- // 2. Configure assistant
1059
- await ai.rag.configureAssistant(collectionId, {
1060
- productId,
1061
- systemPrompt: 'You are a coffee maker expert. Provide clear, step-by-step instructions.',
1062
- rateLimitPerUser: 30
1063
- });
1064
-
1065
- // 3. Answer user questions
1066
- const answer = await ai.public.chat(collectionId, {
1067
- productId,
1068
- userId: 'user-123',
1069
- message: 'How do I make espresso?'
1070
- });
1071
-
1072
- console.log(answer.message);
1073
- }
1074
- ```
1075
-
1076
- ### Example 2: Streaming Chatbot UI
1077
-
1078
- ```typescript
1079
- async function streamingChatbot(userMessage: string) {
1080
- const stream = await ai.chat.completions.create('my-collection', {
1081
- model: 'google/gemini-2.5-flash',
1082
- messages: [
1083
- { role: 'system', content: 'You are a helpful assistant.' },
1084
- { role: 'user', content: userMessage }
1085
- ],
1086
- stream: true
1087
- });
1088
-
1089
- let fullResponse = '';
1090
-
1091
- for await (const chunk of stream) {
1092
- const content = chunk.choices[0]?.delta?.content || '';
1093
- fullResponse += content;
1094
-
1095
- // Update UI in real-time
1096
- updateChatUI(content);
1097
- }
1098
-
1099
- return fullResponse;
1100
- }
1101
- ```
1102
-
1103
- ### Example 3: Multi-Turn Conversation
1104
-
1105
- ```typescript
1106
- async function chatConversation() {
1107
- const collectionId = 'my-collection';
1108
- const sessionId = `chat-${Date.now()}`;
1109
- const userId = 'user-123';
1110
- const productId = 'coffee-maker-deluxe';
1111
-
1112
- // Question 1
1113
- const a1 = await ai.public.chat(collectionId, {
1114
- productId,
1115
- userId,
1116
- message: 'How do I clean the machine?',
1117
- sessionId
1118
- });
1119
- console.log('A1:', a1.message);
1120
-
1121
- // Question 2 (references previous context)
1122
- const a2 = await ai.public.chat(collectionId, {
1123
- productId,
1124
- userId,
1125
- message: 'How often should I do that?',
1126
- sessionId
1127
- });
1128
- console.log('A2:', a2.message);
1129
-
1130
- // Get full history
1131
- const session = await ai.public.getSession(collectionId, sessionId);
1132
- console.log('Full conversation:', session.messages);
1133
- }
1134
- ```
1135
-
1136
- ### Example 4: React Hook for Product Assistant
1137
-
1138
- ```typescript
1139
- import { useState, useCallback } from 'react';
1140
- import { ai } from '@proveanything/smartlinks';
1141
-
1142
- export function useProductAssistant(
1143
- collectionId: string,
1144
- productId: string,
1145
- userId: string
1146
- ) {
1147
- const [loading, setLoading] = useState(false);
1148
- const [error, setError] = useState<string | null>(null);
1149
- const [rateLimit, setRateLimit] = useState({ remaining: 20, limit: 20 });
1150
-
1151
- const ask = useCallback(async (message: string) => {
1152
- setLoading(true);
1153
- setError(null);
1154
-
1155
- try {
1156
- const response = await ai.public.chat(collectionId, {
1157
- productId,
1158
- userId,
1159
- message
1160
- });
1161
-
1162
- setRateLimit(prev => ({
1163
- ...prev,
1164
- remaining: prev.remaining - 1
1165
- }));
1166
-
1167
- return response.message;
1168
- } catch (err: any) {
1169
- setError(err.message);
1170
- throw err;
1171
- } finally {
1172
- setLoading(false);
1173
- }
1174
- }, [collectionId, productId, userId]);
1175
-
1176
- return { ask, loading, error, rateLimit };
1177
- }
1178
-
1179
- // Usage in component
1180
- function ProductHelp() {
1181
- const { ask, loading, rateLimit } = useProductAssistant(
1182
- 'my-collection',
1183
- 'coffee-maker',
1184
- 'user-123'
1185
- );
1186
- const [answer, setAnswer] = useState('');
1187
-
1188
- const handleAsk = async () => {
1189
- const response = await ask('How do I clean this?');
1190
- setAnswer(response);
1191
- };
1192
-
1193
- return (
1194
- <div>
1195
- <button onClick={handleAsk} disabled={loading}>
1196
- {loading ? 'Asking...' : 'Ask Question'}
1197
- </button>
1198
- {answer && <p>{answer}</p>}
1199
- <p>{rateLimit.remaining} questions remaining</p>
1200
- </div>
1201
- );
1202
- }
1203
- ```
1204
-
1205
-
1206
- ---
1207
-
1208
- ## Error Handling
1209
-
1210
- ### Error Codes
1211
-
1212
- | Code | Type | HTTP Status | Description |
1213
- |------|------|-------------|-------------|
1214
- | `rate_limit_exceeded` | `rate_limit_error` | 429 | User exceeded rate limit |
1215
- | `invalid_request` | `invalid_request_error` | 400 | Invalid parameters |
1216
- | `authentication_error` | `authentication_error` | 401 | Invalid/missing API key |
1217
- | `permission_denied` | `permission_error` | 403 | Insufficient permissions |
1218
- | `not_found` | `not_found_error` | 404 | Resource not found |
1219
- | `document_not_found` | `not_found_error` | 404 | Product document not indexed |
1220
- | `server_error` | `server_error` | 500 | Internal server error |
1221
- | `service_unavailable` | `server_error` | 503 | Service temporarily unavailable |
1222
-
1223
- ### Error Handling Pattern
1224
-
1225
- ```typescript
1226
- import { SmartLinksAIError } from '@proveanything/smartlinks';
1227
-
1228
- async function robustChat() {
1229
- try {
1230
- const response = await ai.public.chat('my-collection', {
1231
- productId: 'coffee-maker',
1232
- userId: 'user-123',
1233
- message: 'Help!'
1234
- });
1235
- return response.message;
1236
- } catch (error) {
1237
- if (error instanceof SmartLinksAIError) {
1238
- switch (error.code) {
1239
- case 'rate_limit_exceeded':
1240
- console.error('Rate limit exceeded');
1241
- console.log('Try again at:', new Date(error.resetAt!));
1242
- break;
1243
- case 'document_not_found':
1244
- console.error('Product manual not indexed yet');
1245
- break;
1246
- case 'authentication_error':
1247
- console.error('Invalid API key');
1248
- break;
1249
- case 'invalid_request':
1250
- console.error('Invalid request:', error.message);
1251
- break;
1252
- default:
1253
- console.error('API error:', error.message);
1254
- }
1255
- } else {
1256
- console.error('Unexpected error:', error);
1257
- }
1258
- throw error;
1259
- }
1260
- }
1261
- ```
1262
-
1263
- ### Rate Limit Retry
1264
-
1265
- ```typescript
1266
- async function chatWithRetry(
1267
- request: PublicChatRequest,
1268
- maxRetries = 3
1269
- ) {
1270
- let retries = 0;
1271
-
1272
- while (retries < maxRetries) {
1273
- try {
1274
- return await ai.public.chat('my-collection', request);
1275
- } catch (error) {
1276
- if (error instanceof SmartLinksAIError && error.isRateLimitError()) {
1277
- if (retries === maxRetries - 1) throw error;
1278
-
1279
- const resetTime = new Date(error.resetAt!).getTime();
1280
- const waitTime = resetTime - Date.now();
1281
-
1282
- console.log(`Rate limited. Waiting ${waitTime}ms...`);
1283
- await new Promise(resolve => setTimeout(resolve, waitTime));
1284
-
1285
- retries++;
1286
- } else {
1287
- throw error;
1288
- }
1289
- }
1290
- }
1291
- }
1292
- ```
1293
-
1294
- ---
1295
-
1296
- ## Rate Limiting
1297
-
1298
- ### Rate Limit Overview
1299
-
1300
- Public endpoints are rate-limited per `userId`:
1301
-
1302
- | Endpoint Type | Default Limit | Window |
1303
- |--------------|---------------|--------|
1304
- | Public Chat | 20 requests | 1 hour |
1305
- | Token Generation | 10 requests | 1 hour |
1306
- | Admin Endpoints | Unlimited* | - |
1307
-
1308
- *Admin endpoints use API key authentication and are not rate-limited by default.
1309
-
1310
- ### Rate Limit Headers
1311
-
1312
- All API responses include rate limit information:
1313
-
1314
- ```
1315
- X-RateLimit-Limit: 20
1316
- X-RateLimit-Remaining: 15
1317
- X-RateLimit-Reset: 1707300000000
1318
- ```
1319
-
1320
- ### Checking Rate Limit
1321
-
1322
- ```typescript
1323
- // Check rate limit status before making requests
1324
- const status = await ai.public.getRateLimit('my-collection', 'user-123');
1325
-
1326
- console.log('Used:', status.used);
1327
- console.log('Remaining:', status.remaining);
1328
- console.log('Resets at:', new Date(status.resetAt));
1329
-
1330
- if (status.remaining > 0) {
1331
- // Safe to make request
1332
- await ai.public.chat(/* ... */);
1333
- } else {
1334
- // Show user when they can ask again
1335
- console.log('Rate limit reached. Try again at:', status.resetAt);
1336
- }
1337
- ```
1338
-
1339
- ### Resetting Rate Limits (Admin)
1340
-
1341
- ```typescript
1342
- // Reset rate limit for a specific user
1343
- await ai.rateLimit.reset('my-collection', 'user-123');
1344
- console.log('Rate limit reset for user-123');
1345
- ```
1346
-
1347
- ---
1348
-
1349
- ## Best Practices
1350
-
1351
- ### 1. Choose the Right Model
1352
-
1353
- ```typescript
1354
- // For most new workflows (recommended default)
1355
- await ai.chat.responses.create('my-collection', {
1356
- model: 'openai/gpt-5.4',
1357
- input: 'Create a concise onboarding checklist.'
1358
- });
1359
-
1360
- // For lower-cost structured or JSON-oriented work
1361
- await ai.chat.responses.create('my-collection', {
1362
- model: 'openai/gpt-5-mini',
1363
- input: 'Return a color palette as JSON.'
1364
- });
1365
-
1366
- // For fast multimodal or cost-sensitive general use
1367
- await ai.chat.completions.create('my-collection', {
1368
- model: 'google/gemini-2.5-flash',
1369
- messages: [...]
1370
- });
1371
-
1372
- // When you need the actual available catalog for this collection
1373
- const available = await ai.models.list('my-collection');
1374
- console.log(available.data.map(model => model.id));
1375
- ```
1376
-
1377
- ### 2. Use Streaming for Long Responses
1378
-
1379
- Improve perceived performance with streaming:
1380
-
1381
- ```typescript
1382
- // Non-streaming: User waits for full response
1383
- const response = await ai.chat.completions.create('my-collection', {
1384
- messages: [...]
1385
- });
1386
-
1387
- // Streaming: User sees progress immediately
1388
- const stream = await ai.chat.completions.create('my-collection', {
1389
- stream: true,
1390
- messages: [...]
1391
- });
1392
-
1393
- for await (const chunk of stream) {
1394
- updateUI(chunk.choices[0]?.delta?.content);
1395
- }
1396
- ```
1397
-
1398
- ### 3. Maintain Session Context
1399
-
1400
- Keep conversations coherent with session IDs:
1401
-
1402
- ```typescript
1403
- // Generate unique session ID per conversation
1404
- const sessionId = `user-${userId}-product-${productId}`;
1405
-
1406
- // All questions in same conversation use same sessionId
1407
- await ai.public.chat('my-collection', {
1408
- sessionId,
1409
- message: 'First question',
1410
- ...
1411
- });
1412
-
1413
- await ai.public.chat('my-collection', {
1414
- sessionId,
1415
- message: 'Follow-up question',
1416
- ...
1417
- });
1418
- ```
1419
-
1420
- ### 4. Handle Rate Limits Gracefully
1421
-
1422
- Show clear feedback to users:
1423
-
1424
- ```typescript
1425
- try {
1426
- await ai.public.chat('my-collection', {...});
1427
- } catch (error) {
1428
- if (error instanceof SmartLinksAIError && error.isRateLimitError()) {
1429
- const resetTime = new Date(error.resetAt!);
1430
- showNotification(
1431
- `You've reached your question limit. ` +
1432
- `Try again at ${resetTime.toLocaleTimeString()}`
1433
- );
1434
- }
1435
- }
1436
- ```
1437
-
1438
- ### 5. Optimize Voice UX
1439
-
1440
- Provide clear status updates:
1441
-
1442
- ```typescript
1443
- async function voiceAssistant() {
1444
- try {
1445
- showStatus('Listening...');
1446
- const question = await ai.voice.listen();
1447
-
1448
- showStatus('Processing...');
1449
- const answer = await ai.public.chat('my-collection', {
1450
- message: question,
1451
- ...
1452
- });
1453
-
1454
- showStatus('Speaking...');
1455
- await ai.voice.speak(answer.message);
1456
-
1457
- showStatus('Ready');
1458
- } catch (error) {
1459
- showStatus('Error', error.message);
1460
- }
1461
- }
1462
- ```
1463
-
1464
- ### 6. Chunk Large Documents
1465
-
1466
- For better RAG performance, chunk documents appropriately:
1467
-
1468
- ```typescript
1469
- // For technical manuals
1470
- await ai.rag.indexDocument('my-collection', {
1471
- productId: 'coffee-maker',
1472
- documentUrl: '...',
1473
- chunkSize: 500, // Smaller chunks for precise answers
1474
- overlap: 50 // Overlap maintains context
1475
- });
1476
-
1477
- // For narrative content
1478
- await ai.rag.indexDocument('my-collection', {
1479
- productId: 'coffee-maker',
1480
- documentUrl: '...',
1481
- chunkSize: 1000, // Larger chunks for coherent responses
1482
- overlap: 100
1483
- });
1484
- ```
1485
-
1486
- ### 7. Use System Prompts Effectively
1487
-
1488
- Provide clear instructions:
1489
-
1490
- ```typescript
1491
- await ai.chat.completions.create('my-collection', {
1492
- messages: [
1493
- {
1494
- role: 'system',
1495
- content: `You are a coffee maker expert assistant.
1496
- - Be concise and clear
1497
- - Use numbered lists for steps
1498
- - Always mention safety precautions
1499
- - If unsure, ask for clarification`
1500
- },
1501
- { role: 'user', content: 'How do I descale?' }
1502
- ]
1503
- });
1504
- ```
1505
-
1506
- ### 8. Monitor Usage and Costs
1507
-
1508
- Track usage for cost management:
1509
-
1510
- ```typescript
1511
- const response = await ai.chat.completions.create('my-collection', {
1512
- messages: [...]
1513
- });
1514
-
1515
- // Log token usage
1516
- console.log('Usage:', response.usage);
1517
- console.log('Prompt tokens:', response.usage.prompt_tokens);
1518
- console.log('Completion tokens:', response.usage.completion_tokens);
1519
- console.log('Total tokens:', response.usage.total_tokens);
1520
-
1521
- // Calculate estimated cost
1522
- const model = await ai.models.get('my-collection', response.model);
1523
- const cost =
1524
- (response.usage.prompt_tokens * model.pricing.input / 1_000_000) +
1525
- (response.usage.completion_tokens * model.pricing.output / 1_000_000);
1526
- console.log('Estimated cost: $', cost.toFixed(4));
1527
- ```
1528
-
1529
- ---
1530
-
1531
- ## Providing Content to the AI Assistant
1532
-
1533
- The portal's built-in AI assistant can discuss the content currently visible to the user. To make this work, your app must supply contextual content when the assistant requests it. There are three extraction methods, tried in priority order:
1534
-
1535
- | Priority | Method | When Used |
1536
- |----------|--------|-----------|
1537
- | 1 | **Direct prop callback** | Container/widget rendered in the parent React context |
1538
- | 2 | **PostMessage protocol** | App rendered in an iframe |
1539
- | 3 | **DOM text fallback** | Neither of the above responded |
1540
-
1541
- This section covers **methods 1 and 2** — the ones you implement in your app.
1542
-
1543
- ### Method 1: Direct Prop (`onRequestAIContent`)
1544
-
1545
- When your app is rendered as a **container** (a direct component in the parent's React tree), the framework passes an `onRequestAIContent` prop to your exported component. You do **not** call this prop yourself — the framework calls it when the AI assistant needs context.
1546
-
1547
- Structure your component to make current state accessible when the callback fires:
1548
-
1549
- ```tsx
1550
- import { useEffect, useRef } from 'react';
1551
-
1552
- export function PublicContainer(props) {
1553
- const { onRequestAIContent, appId, ...rest } = props;
1554
-
1555
- // Keep a ref to the latest content so the callback always returns fresh data
1556
- const currentContentRef = useRef(null);
1557
-
1558
- useEffect(() => {
1559
- currentContentRef.current = buildCurrentContent();
1560
- }, [relevantState]);
1561
-
1562
- return <div data-app-container={appId}>{/* your UI */}</div>;
1563
- }
1564
- ```
1565
-
1566
- The framework registers the content provider internally via `useAIContentExtraction.registerContentProvider()`. Your component just needs to respond when the callback is invoked.
1567
-
1568
- ### Method 2: PostMessage Protocol (Iframes)
1569
-
1570
- For iframe-embedded apps the framework sends a `postMessage` request and expects a response within **500 ms**. If your app doesn't reply in time the framework falls back to DOM text extraction.
1571
-
1572
- **Request sent by the framework to your iframe:**
1573
-
1574
- ```typescript
1575
- {
1576
- type: 'smartlinks:request-ai-content',
1577
- requestId: 'ai-content-1709834567890-abc123' // unique per request
1578
- }
1579
- ```
1580
-
1581
- **Response your app must send back:**
1582
-
1583
- ```typescript
1584
- {
1585
- type: 'smartlinks:ai-content-response',
1586
- requestId: 'ai-content-1709834567890-abc123', // echo back the requestId
1587
- content: AIContentResponse
1588
- }
1589
- ```
1590
-
1591
- **Minimal implementation:**
1592
-
1593
- ```typescript
1594
- window.addEventListener('message', async (event) => {
1595
- if (event.data?.type === 'smartlinks:request-ai-content') {
1596
- const content = await gatherAIContent();
1597
-
1598
- window.parent.postMessage({
1599
- type: 'smartlinks:ai-content-response',
1600
- requestId: event.data.requestId,
1601
- content,
1602
- }, '*');
1603
- }
1604
- });
1605
-
1606
- async function gatherAIContent(): Promise<AIContentResponse> {
1607
- return {
1608
- text: 'The user is viewing the warranty registration form...',
1609
- contentLabel: 'Warranty Registration',
1610
- };
1611
- }
1612
- ```
1613
-
1614
- ### The `AIContentResponse` Interface
1615
-
1616
- ```typescript
1617
- interface AIContentResponse {
1618
- /**
1619
- * Plain text or markdown for the AI to use as context.
1620
- * Injected into the system prompt. Max recommended: ~4000 characters.
1621
- */
1622
- text: string;
1623
-
1624
- /**
1625
- * Optional structured metadata (key-value pairs).
1626
- * Not used directly in prompts but available for custom providers.
1627
- */
1628
- metadata?: Record<string, unknown>;
1629
-
1630
- /**
1631
- * Pre-built RAG configuration. When provided, the assistant can use
1632
- * SL.ai.public.chat() to ground answers in indexed product documents.
1633
- */
1634
- ragHint?: {
1635
- /** The product ID whose indexed documents should be queried */
1636
- productId: string;
1637
- /** Optional session ID for multi-turn RAG conversations */
1638
- sessionId?: string;
1639
- /** Optional context hint to help scope the RAG query */
1640
- context?: string;
1641
- };
1642
-
1643
- /**
1644
- * Human-readable label shown in context-update messages
1645
- * (e.g. "Product Manual", "FAQ").
1646
- */
1647
- contentLabel?: string;
1648
-
1649
- /**
1650
- * How the assistant should use this content:
1651
- * - 'context' (default): inject text into the system prompt
1652
- * - 'rag': use ragHint to query indexed docs via SL.ai.public.chat()
1653
- * - 'hybrid': inject text as context AND ground answers via RAG
1654
- */
1655
- strategy?: 'context' | 'rag' | 'hybrid';
1656
- }
1657
- ```
1658
-
1659
- ### Response Strategies
1660
-
1661
- #### `context` (Default)
1662
-
1663
- Return readable text. The assistant injects it into the system prompt as background knowledge. Good for descriptions, summaries, structured data, and FAQs.
1664
-
1665
- ```typescript
1666
- return {
1667
- text: `
1668
- ## Wine Details
1669
- - **Name**: 2023 Château Margaux
1670
- - **Region**: Bordeaux, France
1671
- - **Tasting Notes**: Dark fruit, cedar, tobacco
1672
- - **Food Pairing**: Lamb, aged cheese
1673
- `,
1674
- contentLabel: 'Wine Information',
1675
- strategy: 'context',
1676
- };
1677
- ```
1678
-
1679
- #### `rag`
1680
-
1681
- Tell the assistant to query pre-indexed documents via SmartLinks RAG. The `text` field is minimal — the real knowledge comes from the indexed docs. Good for product manuals, large document sets, and technical specs.
1682
-
1683
- ```typescript
1684
- return {
1685
- text: 'The user is viewing the espresso machine product page.',
1686
- contentLabel: 'Product Assistant',
1687
- strategy: 'rag',
1688
- ragHint: {
1689
- productId: 'espresso-machine-pro',
1690
- sessionId: `rag-session-${userId}`,
1691
- context: 'User is on the troubleshooting section',
1692
- },
1693
- };
1694
- ```
1695
-
1696
- When the assistant receives a `rag` strategy it routes the question through `SL.ai.public.chat()`:
1697
-
1698
- ```typescript
1699
- const response = await SL.ai.public.chat(collectionId, {
1700
- productId: ragHint.productId,
1701
- userId: currentUserId,
1702
- message: userQuestion,
1703
- sessionId: ragHint.sessionId,
1704
- });
1705
- ```
1706
-
1707
- #### `hybrid`
1708
-
1709
- Combines both — the `text` is injected as additional context **and** the user's questions are also grounded via RAG. Good for museum exhibits, guided experiences, or any scenario with rich metadata alongside large document sets.
1710
-
1711
- ```typescript
1712
- return {
1713
- text: `
1714
- ## Exhibit: The Starry Night
1715
- - **Artist**: Vincent van Gogh
1716
- - **Year**: 1889
1717
- - **Current Location**: Gallery 3, East Wing
1718
- - **Audio Guide**: Available in 12 languages
1719
- `,
1720
- contentLabel: 'Museum Exhibit',
1721
- strategy: 'hybrid',
1722
- ragHint: {
1723
- productId: 'starry-night-exhibit',
1724
- context: 'Art history and technique questions',
1725
- },
1726
- };
1727
- ```
1728
-
1729
- ### Content Extraction Examples
1730
-
1731
- #### Museum Guide App
1732
-
1733
- ```typescript
1734
- async function gatherAIContent(): Promise<AIContentResponse> {
1735
- const exhibit = getCurrentExhibit();
1736
-
1737
- return {
1738
- text: `
1739
- Exhibit: "${exhibit.title}" by ${exhibit.artist}
1740
- Period: ${exhibit.period}
1741
- Medium: ${exhibit.medium}
1742
- Description: ${exhibit.curatorNotes}
1743
- Related works in this gallery: ${exhibit.relatedWorks.join(', ')}
1744
- `.trim(),
1745
- contentLabel: `Exhibit: ${exhibit.title}`,
1746
- strategy: 'hybrid',
1747
- ragHint: {
1748
- productId: exhibit.smartlinksProductId,
1749
- context: `Art history, technique, and visitor information for ${exhibit.title}`,
1750
- },
1751
- metadata: {
1752
- exhibitId: exhibit.id,
1753
- gallery: exhibit.gallery,
1754
- audioGuideAvailable: exhibit.hasAudioGuide,
1755
- },
1756
- };
1757
- }
1758
- ```
1759
-
1760
- #### Wine Product App
1761
-
1762
- ```typescript
1763
- async function gatherAIContent(): Promise<AIContentResponse> {
1764
- const wine = getCurrentWine();
1765
- const reviews = await fetchRecentReviews(wine.id, 5);
1766
-
1767
- return {
1768
- text: `
1769
- Wine: ${wine.name} (${wine.vintage})
1770
- Winery: ${wine.winery}
1771
- Region: ${wine.region}, ${wine.country}
1772
- Grape: ${wine.grape}
1773
- ABV: ${wine.abv}%
1774
- Price: ${wine.price}
1775
- Tasting Notes: ${wine.tastingNotes}
1776
-
1777
- Recent Reviews:
1778
- ${reviews.map(r => `- "${r.text}" (${r.rating}/5)`).join('\n')}
1779
- `.trim(),
1780
- contentLabel: 'Wine Details',
1781
- strategy: 'context',
1782
- };
1783
- }
1784
- ```
1785
-
1786
- #### Equipment Manual App (RAG-only)
1787
-
1788
- ```typescript
1789
- async function gatherAIContent(): Promise<AIContentResponse> {
1790
- const equipment = getCurrentEquipment();
1791
-
1792
- return {
1793
- text: `User is viewing: ${equipment.name} (Model: ${equipment.modelNumber})`,
1794
- contentLabel: `${equipment.name} Assistant`,
1795
- strategy: 'rag',
1796
- ragHint: {
1797
- productId: equipment.smartlinksProductId,
1798
- sessionId: `manual-${equipment.id}-${Date.now()}`,
1799
- context: 'Technical manual, troubleshooting, and maintenance',
1800
- },
1801
- };
1802
- }
1803
- ```
1804
-
1805
- ### Timing & Lifecycle
1806
-
1807
- - **On navigation**: When the user navigates to a new product/proof/app, the assistant automatically requests fresh content and injects a context-update system message.
1808
- - **On first message**: If no content has been gathered yet, the assistant requests it before the first AI call.
1809
- - **On manual refresh**: The assistant can re-request content at any time (e.g. if the user's view within the app has changed).
1810
-
1811
- Content is requested **lazily** — your handler is only called when the AI assistant is active and needs context. If the user never opens the assistant, your handler is never called.
1812
-
1813
- ### Method 3: DOM Fallback (Automatic)
1814
-
1815
- If your app doesn't implement either of the above, the framework extracts `innerText` from the DOM element with `data-app-container="{appId}"`, truncated to ~4000 characters. This is a **last resort** — content quality is much lower than a structured response. Implementing Method 1 or 2 is strongly recommended.
1816
-
1817
- ---
1818
-
1819
- ## Related Documentation
1820
-
1821
- - [API Summary](./API_SUMMARY.md) - Complete API reference
1822
- - [Widgets](./widgets.md) - Embedding SmartLinks components
1823
- - [Realtime](./realtime.md) - Realtime data updates
1824
- - [iframe Responder](./iframe-responder.md) - iframe integration
1825
-
1826
- ---
1827
-
1828
- ## Support
1829
-
1830
- For questions or issues:
1831
-
1832
- - **Documentation:** https://smartlinks.app/docs
1833
- - **GitHub:** https://github.com/Prove-Anything/smartlinks
1834
- - **Email:** support@smartlinks.app
1
+ # SmartLinks AI
2
+
3
+ Build AI-powered SmartLinks experiences with a practical SDK guide for responses, chat, product assistants, streaming, voice, and real-world integration patterns.
4
+
5
+ ---
6
+
7
+ ## Table of Contents
8
+
9
+ - [Overview](#overview)
10
+ - [Quick Start](#quick-start)
11
+ - [Authentication](#authentication)
12
+ - [Responses API](#responses-api)
13
+ - [Chat Completions](#chat-completions)
14
+ - [Knowledge: answers from your own content](#knowledge-answers-from-your-own-content)
15
+ - [Voice Integration](#voice-integration)
16
+ - [Podcast Generation](#podcast-generation)
17
+ - [Types & API reference](#types--api-reference)
18
+ - [Usage Examples](#usage-examples)
19
+ - [Error Handling](#error-handling)
20
+ - [Rate Limiting](#rate-limiting)
21
+ - [Best Practices](#best-practices)
22
+ - [Providing Content to the AI Assistant](#providing-content-to-the-ai-assistant)
23
+
24
+ ---
25
+
26
+ ## Overview
27
+
28
+ This guide is written for SDK users building real products, not backend operators. It focuses on the public SDK surface, recommended starting points, and examples you can adapt directly.
29
+
30
+ ### Start with the path that matches your job
31
+
32
+ | If you want to... | Start here |
33
+ |---|---|
34
+ | Build a new AI workflow | Use [Responses API](#responses-api) |
35
+ | Add compatibility with existing chat clients | Use [Chat Completions](#chat-completions) |
36
+ | Answer questions from manuals, help articles or product pages | Use [Knowledge: answers from your own content](#knowledge-answers-from-your-own-content) |
37
+ | Add spoken input/output | Use [Voice Integration](#voice-integration) |
38
+ | Add progressive rendering | Use [Streaming Responses](#streaming-responses) or [Streaming Chat](#streaming-chat) |
39
+
40
+ > **Which API for which job:**
41
+ > - **`ai.chat.responses`**: the default for new work. Structured input, tool use, multi-agent, streaming. You keep any conversation history yourself and send it with each call.
42
+ > - **`ai.chat.completions`**: OpenAI-compatible (`messages[]`). Use it only to drop into existing OpenAI-style code.
43
+ > - **`knowledge.publicSearch`**: finds the passages in your own content (manuals, help articles) that answer a question. Works from a website, Portal or Hub without an API key.
44
+ > - **`ai.agent.run`**: an admin-side agent loop that can call built-in tools such as `knowledge.search` and write an answer from what it finds.
45
+ >
46
+ > Responses and Completions are generation APIs; both take history, neither stores it for you.
47
+
48
+ ### Recommended starting points
49
+
50
+ - New AI features: start with `ai.chat.responses.create(...)`
51
+ - Product/manual Q&A: start with `knowledge.publicSearch(...)`; for an AI-written answer, run `ai.agent.run(...)` with the `knowledge.search` tool on your own server
52
+ - Existing OpenAI-style clients: use `ai.chat.completions.create(...)`
53
+ - Real-time voice: use `ai.live.start(...)` or your provider's live client
54
+
55
+ SmartLinks AI provides five main capabilities:
56
+
57
+ 1. **Responses API** - Preferred API for agentic workflows, multimodal inputs, and tool-driven responses
58
+ 2. **Chat Completions** - OpenAI-compatible text generation with streaming and tool calling
59
+ 3. **Knowledge search** - Find the right passage in your manuals and help content, for people and for AI agents
60
+ 4. **Voice Integration** - Voice-to-text and text-to-voice for hands-free interaction
61
+ 5. **Podcast Generation** - NotebookLM-style multi-voice conversational podcasts from documents
62
+
63
+ ### Key Features
64
+
65
+ - ✅ Full TypeScript support with type safety
66
+ - ✅ Streaming responses with async iterators
67
+ - ✅ Automatic rate limit handling
68
+ - ✅ Voice input/output helpers
69
+ - ✅ Tool/function calling support
70
+ - ✅ OpenAI-style Responses API support
71
+ - ✅ Knowledge search over your own content (meaning and keywords together)
72
+
73
+ ---
74
+
75
+ ## Quick Start
76
+
77
+ If you're only reading one section, start here. The three snippets below cover the most common public SDK use cases.
78
+
79
+ ### 1. Generate a response
80
+
81
+ ```typescript
82
+ import { initializeApi, ai } from '@proveanything/smartlinks';
83
+
84
+ // Initialize the SDK
85
+ initializeApi({
86
+ baseURL: 'https://smartlinks.app/api/v1',
87
+ apiKey: process.env.SMARTLINKS_API_KEY // Required for admin endpoints
88
+ });
89
+
90
+ // Preferred: create a response
91
+ const response = await ai.chat.responses.create('my-collection', {
92
+ model: 'google/gemini-2.5-flash',
93
+ input: 'Summarize the key safety steps for descaling a coffee maker.'
94
+ });
95
+
96
+ console.log(response.output_text);
97
+ ```
98
+
99
+ ### 2. Answer a product question from your manuals
100
+
101
+ ```typescript
102
+ import { initializeApi, knowledge } from '@proveanything/smartlinks';
103
+
104
+ initializeApi({ baseURL: 'https://smartlinks.app/api/v1' });
105
+
106
+ const { results } = await knowledge.publicSearch('my-collection', {
107
+ query: 'How do I descale this machine?',
108
+ filters: { productId: 'coffee-maker-deluxe' },
109
+ k: 3
110
+ });
111
+
112
+ for (const r of results) {
113
+ console.log(r.title, r.heading, r.url);
114
+ console.log(r.snippet);
115
+ }
116
+ ```
117
+
118
+ This needs a knowledge set with content in it; see [Knowledge: answers from your own content](#knowledge-answers-from-your-own-content).
119
+
120
+ ### 3. Stream output into your UI
121
+
122
+ ```typescript
123
+ const stream = await ai.chat.responses.create('my-collection', {
124
+ input: 'Write a launch checklist for a new product page.',
125
+ stream: true
126
+ });
127
+
128
+ for await (const event of stream) {
129
+ if (event.type === 'response.output_text.delta') {
130
+ updateUi(event.delta);
131
+ }
132
+ }
133
+ ```
134
+
135
+ ---
136
+
137
+ ## Authentication
138
+
139
+ ### Admin Endpoints
140
+
141
+ Admin endpoints require an API key passed during initialization:
142
+
143
+ ```typescript
144
+ initializeApi({
145
+ baseURL: 'https://smartlinks.app/api/v1',
146
+ apiKey: process.env.SMARTLINKS_API_KEY
147
+ });
148
+ ```
149
+
150
+ The SDK automatically includes the API key in the `Authorization: Bearer <token>` header.
151
+
152
+ ### Public Endpoints
153
+
154
+ Public endpoints don't require an API key. Anonymous callers see public content only; a signed-in person (Portal or Hub sign-in) also sees content meant for customers:
155
+
156
+ ```typescript
157
+ // No API key needed
158
+ const { results } = await knowledge.publicSearch('my-collection', {
159
+ query: 'How do I clean this?'
160
+ });
161
+ ```
162
+
163
+ Public AI calls such as `ai.public.agentRun` are rate-limited per user (see [Rate Limiting](#rate-limiting)).
164
+
165
+ ---
166
+
167
+ ## Responses API
168
+
169
+ The Responses API is the recommended starting point for new integrations. Use it when you want a single endpoint for structured input, tool use, and streaming output.
170
+
171
+ ### Basic Response
172
+
173
+ ```typescript
174
+ const response = await ai.chat.responses.create('my-collection', {
175
+ model: 'google/gemini-2.5-flash',
176
+ input: 'Write a friendly two-sentence welcome for a product assistant.'
177
+ });
178
+
179
+ console.log(response.output_text);
180
+ ```
181
+
182
+ ### Multimessage Input
183
+
184
+ ```typescript
185
+ const response = await ai.chat.responses.create('my-collection', {
186
+ model: 'google/gemini-2.5-flash',
187
+ input: [
188
+ {
189
+ role: 'system',
190
+ content: [
191
+ { type: 'input_text', text: 'You are a concise support assistant.' }
192
+ ]
193
+ },
194
+ {
195
+ role: 'user',
196
+ content: [
197
+ { type: 'input_text', text: 'Give me three troubleshooting steps for a grinder that will not start.' }
198
+ ]
199
+ }
200
+ ]
201
+ });
202
+
203
+ console.log(response.output_text);
204
+ ```
205
+
206
+ ### Streaming Responses
207
+
208
+ When you pass `stream: true`, the SDK returns an `AsyncIterable` of SSE events instead of a final JSON object. You do not need to parse raw SSE frames yourself — just iterate with `for await...of`.
209
+
210
+ ```typescript
211
+ const result = await ai.chat.responses.create('my-collection', {
212
+ input: 'Summarize the manual',
213
+ stream: true
214
+ });
215
+
216
+ for await (const event of result) {
217
+ if (event.type === 'response.output_text.delta') {
218
+ process.stdout.write(event.delta);
219
+ }
220
+ }
221
+ ```
222
+
223
+ If you omit `stream: true`, the same method returns the final `ResponsesResult` object instead.
224
+
225
+ ```typescript
226
+ const stream = await ai.chat.responses.create('my-collection', {
227
+ model: 'google/gemini-2.5-flash',
228
+ input: 'Explain how to descale an espresso machine step by step.',
229
+ stream: true
230
+ });
231
+
232
+ for await (const event of stream) {
233
+ if (event.type === 'response.output_text.delta') {
234
+ process.stdout.write(event.delta);
235
+ }
236
+ }
237
+ ```
238
+
239
+ ### Tool Calling
240
+
241
+ ```typescript
242
+ const response = await ai.chat.responses.create('my-collection', {
243
+ model: 'google/gemini-2.5-flash',
244
+ input: 'What is the weather in Paris?',
245
+ tools: [
246
+ {
247
+ type: 'function',
248
+ name: 'get_weather',
249
+ description: 'Get the current weather for a city',
250
+ parameters: {
251
+ type: 'object',
252
+ properties: {
253
+ location: { type: 'string' }
254
+ },
255
+ required: ['location']
256
+ }
257
+ }
258
+ ]
259
+ });
260
+
261
+ console.log(response.output);
262
+ ```
263
+
264
+ ### Server-side tools (built-in agent loop)
265
+
266
+ The example above is **client-relayed** tool calling: you define the tools, the model returns
267
+ `tool_call` requests, and *your app* executes them and sends results back. For the common tools —
268
+ reading and searching the web, vision, reading documents, generating images — the platform ships a
269
+ curated, tested **built-in toolset it runs itself**. Opt in with `server_tools` and the server
270
+ executes each tool and feeds the result back automatically, looping until the model has its answer.
271
+ You get one final response; no relay code.
272
+
273
+ ```typescript
274
+ // Enable the whole built-in toolset:
275
+ const res = await ai.chat.responses.create('my-collection', {
276
+ model: 'balanced',
277
+ input: 'Research acme.com and summarise what they sell, with their brand colours.',
278
+ server_tools: true
279
+ });
280
+ console.log(res.output_text);
281
+ console.log(res._agent.toolResults); // trace: which tools ran, with what result
282
+ ```
283
+
284
+ Scope it to specific tools (recommended — smaller blast radius, faster), by name or capability:
285
+
286
+ ```typescript
287
+ import { AI_TOOL_NAMES } from '@proveanything/smartlinks';
288
+
289
+ const res = await ai.chat.responses.create('my-collection', {
290
+ input: 'Find the current price of this product and return it as JSON.',
291
+ server_tools: [AI_TOOL_NAMES.WEB_SEARCH, AI_TOOL_NAMES.DATA_EXTRACT],
292
+ // or: allowCapabilities: ['web:read'], exclude: ['image.generate'],
293
+ maxSteps: 6 // cap model round-trips (1–12, default 8)
294
+ });
295
+ ```
296
+
297
+ **Streaming** surfaces tool progress as it happens — ideal for a "thinking…" UI. You get
298
+ `agent.tool_call` / `agent.tool_result` events, then a final `response.completed`:
299
+
300
+ ```typescript
301
+ const stream = await ai.chat.responses.create('my-collection', {
302
+ input: 'Research acme.com', server_tools: true, stream: true
303
+ });
304
+ for await (const ev of stream) {
305
+ if (ev.type === 'agent.tool_call') showStep(`Running ${ev.name}…`);
306
+ if (ev.type === 'agent.tool_result') showStep(`${ev.name} done`);
307
+ if (ev.type === 'response.completed') render(ev.response.output_text);
308
+ }
309
+ ```
310
+
311
+ `server_tools` can't be combined with `previous_response_id`/`conversation` yet — pass prior turns
312
+ in `input`.
313
+
314
+ #### Built-in tools
315
+
316
+ | Tool | Does |
317
+ |------|------|
318
+ | `web.search` | Live web search → candidate results (url/title/description). |
319
+ | `web.fetchPage` | Fetch a page → clean markdown + metadata + schema.org JSON-LD. |
320
+ | `web.extractSchema` | Return only a page's schema.org data of a given `@type` (deterministic). |
321
+ | `document.read` | Read a document at a URL — **PDF, deck, doc**, or article — into markdown. |
322
+ | `data.extract` | Page + JSON-schema/prompt → **typed JSON** (turn a page into UI data). |
323
+ | `brand.assets` | Extract a site's logo, colours, and design. |
324
+ | `web.screenshot` | Screenshot a page → hosted image URL (feed to `image.describe`). |
325
+ | `image.describe` | Vision: describe an image / read its text. |
326
+ | `image.generate` | Generate an image from a prompt → hosted URL. |
327
+ | `image.fromReference` | Image-to-image: generate guided by reference image(s). |
328
+ | `image.searchStock` | Search real stock photos (Unsplash). |
329
+ | `image.transform` | Resize / crop / rotate / grayscale / format-convert / compress → hosted URL. |
330
+ | `pdf.create` | Render HTML (or one fragment per page) → PDF, 1:1: exact `width`/`height`/`unit` for labels, `pages[]` for many pages in one render, no scripts, only SmartLinks/Google Fonts/data: resources. `return`: `url` (public), `signedUrl` (expiring), `base64`. Cached by input. |
331
+ | `pdf.fill` | Fill an AcroForm PDF's fields (`{ field: value }`) → hosted URL. |
332
+ | `pdf.merge` | Merge several PDFs into one, in order → hosted URL. |
333
+ | `pdf.inspect` | Cheap, no-AI introspection: page count/sizes, which pages have a real text layer, raster present, and a routing hint (`text` vs `vision`). |
334
+ | `pdf.render` | Rasterize one page — or just a region (`clip: { x0, y0, x1, y1 }`, 0–1 from top-left) — to a PNG at a chosen DPI → hosted image URL (permanent). Max 40 MP per call; larger requests return `code: "too_large"` + `suggestedDpi`. |
335
+ | `image.ocr` | **Deterministic OCR** (Google Vision, no generative model): exact characters with per-word `confidence` (0–1) and pixel `bbox`, plus lines with spacing as printed. Input: `imageUrl`, or a PDF `url` + `page` + `dpi` + optional `clip`. Optional `languages` hints. Use for small print and text outlined to curves. |
336
+ | `pdf.extract` | PDF → typed JSON in one call (schema and/or prompt). Auto-routes text vs vision. Optional per-field `confidence`/`source` (`includeConfidence`) and `bbox` (`includeBoxes`) in `fieldsMeta`. |
337
+ | `pdf.decodeBarcodes` | Deterministically decode barcodes/QR on a page (WASM, no AI) → value + symbology + page + bbox + confidence. Use this for barcode digits, never vision. |
338
+ | `pdf.inspectGraphics` | Prepress inspection: per-page path/image/outlined-text counts + colour spaces, plus named SPOT colours (e.g. "PANTONE 871 C"). No AI. |
339
+ | `pdf.edit` | Edit an existing PDF: replace **live** text (glyph-exact removal, neighbours never move; original font when it has the glyphs, else an embedded fallback; CMYK/spot colour kept; matches may span lines), add text / images in boxes (`colorSpace: "cmyk"` converts images for print). Per-item `results` with `verified`. |
340
+ | `pdf.preflight` | Prepress preflight, no changes: fonts, RGB/Lab, TrimBox/BleedBox + bleed, effective image dpi, transparency, white overprint, annotations, hidden layers, output intent. No AI. |
341
+ | `pdf.printReady` | Text outlined to curves, RGB→CMYK with a press profile (spot colours kept), comments removed, layers merged as chosen, mark PDF/X-1a or PDF/X-4 with the output intent embedded, then preflight the result → `{ url, report }`. Options for grey, spot conversion, downsampling, pages, crop marks and more (below). |
342
+ | `http.request` | SSRF-guarded outbound HTTP(S) to a public URL (call a REST API). |
343
+ | `translate` | Translate text into one or more languages (generic, model-based). |
344
+
345
+ **Working with PDFs.** The PDF tools split into *read/analyse* and *produce*:
346
+
347
+ - **Read a whole PDF as text** → `document.read` (Firecrawl; good for prose/decks).
348
+ - **Turn a PDF into structured fields** → `pdf.extract` (give it a JSON schema and/or a prompt; it
349
+ returns typed JSON). It routes itself, but you can drive the route yourself: call `pdf.inspect`
350
+ first (deterministic, no AI) to see whether each page has a real text layer, then `pdf.extract`
351
+ (cheap text path) or `pdf.render` → `image.describe`/vision for curve-only or raster artwork.
352
+ - **Read small print exactly** (INCI/allergen lists, net weight, text outlined to curves) → `image.ocr`
353
+ with a PDF `url`, `page`, `dpi: 300–400` and a `clip` around the panel. It returns the characters it
354
+ sees with a per-word confidence — it never "corrects" a misspelling the way a vision model can, so
355
+ flag words below ~0.9 for human review rather than re-reading them with a model.
356
+ - **Zoom in visually** (layout, artwork) → `pdf.render` with `clip` to rasterise just a region at a high
357
+ DPI, instead of the whole sheet. Renders over 40 MP return `code: "too_large"` with `suggestedDpi`
358
+ — retry at that dpi or with a smaller clip, don't blind-retry.
359
+ - **Barcodes / QR** → `pdf.decodeBarcodes` (deterministic WASM decode) — never trust vision for barcode
360
+ digits; it hallucinates them.
361
+ - **Prepress / print QA** (spot colours, colour spaces, vector vs raster) → `pdf.inspectGraphics`.
362
+ - **Change the artwork itself** → `pdf.edit`. `replaceText` edits only LIVE text: the matched glyphs are
363
+ cut out with an exact-width gap (nothing else moves) and the new text is drawn at the same spot, in the
364
+ same colour, in the original font if its embedded glyphs cover the new text (otherwise an embedded
365
+ fallback, reported as `usedFallbackFont`). A replacement longer than the original is flagged in `note`
366
+ — it may run into neighbouring text. Text outlined to curves can't be edited: the item fails with
367
+ "not found as live text" — put it on the designer change list. `verified: true` means the new text
368
+ reads back from the output.
369
+ - **Is it print-ready?** → `pdf.preflight` (report only; `stats.layers` lists the file's layers).
370
+ **Make it print-ready** → `pdf.printReady`. By default it outlines all text to curves, converts
371
+ RGB/Lab to CMYK for the `outputIntent` (e.g. `FOGRA39`), keeps spot colours, removes comments and
372
+ links, merges layers as the file shows them (hidden layers left out) and marks the file PDF/X-4.
373
+ `report.changes` says what was done, measured on the output; `report.compliant` comes from
374
+ preflighting the OUTPUT, so remaining issues (low-res images, missing bleed, white overprint) are
375
+ reported rather than hidden. Options:
376
+
377
+ | Option | Values |
378
+ |---|---|
379
+ | `profile` | `pdfx-4` (default), `pdfx-1a` (CMYK + spot only), `none` (convert, no PDF/X marking) |
380
+ | `outputIntent` | `FOGRA39` (default), `FOGRA51`, `FOGRA52`, `FOGRA29`, `GRACoL2006`, `SWOP2006`, `JapanColor2011` |
381
+ | `colour` | `cmyk` (default), `gray`, `keep` |
382
+ | `spotColours` | `keep` (default) or `convert` to process colour |
383
+ | `outlineFonts` | `true` (default) text → curves; `false` keeps live text (fonts embedded with `embedFonts`, default true) |
384
+ | `layers` | `{ hide: ['Dieline'], show: [...] }` by name — e.g. print without the dieline |
385
+ | `annotations` | `remove` (default), `flatten` (draw into the artwork), `keep` |
386
+ | `pages` | `"1-3,5"` (default all) |
387
+ | `downsample` | `{ dpi: 300 }` — resample images placed above 1.5× that; off by default |
388
+ | `bleed` | `{ mm: 3 }` — required bleed, checked and reported, never added |
389
+ | `bleedIncluded` | `{ mm: 3 }` — the artwork already includes its bleed: sets TrimBox/BleedBox |
390
+ | `cropMarks` | `{}` or `{ offsetMm, lengthMm, weightPt }` — crop marks outside the bleed |
391
+ | `flattenTransparency` | PDF/X-1a only: affected pages become images. Default false |
392
+
393
+ Outlined text can't be edited or searched afterwards: keep the source PDF for changes and regenerate.
394
+
395
+ ```ts
396
+ const edited = await SL.ai.tools.run(collectionId, 'pdf.edit', {
397
+ url: artworkUrl,
398
+ replaceText: [{ id: 'f1', page: 1, find: 'Best before: see lid', replace: 'Best before: see base' }],
399
+ })
400
+ const ready = await SL.ai.tools.run(collectionId, 'pdf.printReady', {
401
+ url: edited.result.url, profile: 'pdfx-4', outputIntent: 'FOGRA39', bleed: { mm: 3 },
402
+ layers: { hide: ['Dieline'] }, cropMarks: {},
403
+ })
404
+ if (!ready.result.report.compliant) showFindings(ready.result.report.findings)
405
+ ```
406
+ - **A review UI that flags guessed fields** → `pdf.extract` with `includeConfidence` (per-field
407
+ confidence + source) and `includeBoxes` (per-field bbox on text-native pages) in `fieldsMeta`.
408
+ - **Produce a PDF** → `pdf.create` (HTML → PDF), `pdf.fill` (populate an AcroForm's fields),
409
+ `pdf.merge` (combine several). `pdf.create` takes an exact page size (`width`, `height`, `unit`) or a
410
+ `format`, `html` or `pages: [html, …]` (one per page, sharing `head`), and returns `url` (public),
411
+ a `signedUrl` that expires, or `base64` (`return`). JavaScript doesn't run, and images, fonts and
412
+ stylesheets load only from SmartLinks hosts, Google Fonts or `data:` URIs. From a server function:
413
+ `ctx.sl.tools.run('pdf.create', …)` with the `tools:pdf.create` capability (server-functions.md).
414
+
415
+ Every tool is also directly callable without the model loop via `ai.tools.run(collectionId, name,
416
+ args)` — e.g. render a page or extract fields straight from a UI, no agent round-trip:
417
+
418
+ ```ts
419
+ // Read the ingredients panel of a sleeve exactly (deterministic OCR of a clipped region)
420
+ const { result } = await SL.ai.tools.run(collectionId, 'image.ocr', {
421
+ url: sleevePdfUrl, page: 1, dpi: 400,
422
+ clip: { x0: 0.40, y0: 0.20, x1: 0.60, y1: 0.40 },
423
+ languages: ['en', 'fr'],
424
+ })
425
+ // result.lines → [{ text: 'INGREDIENTS: Aqua, Glycerin, …', confidence: 0.97, bbox: {…} }]
426
+ const toReview = result.words.filter((w) => w.confidence < 0.9)
427
+ ```
428
+
429
+ Discover tools two ways:
430
+ - **Design time (typed):** import `BUILTIN_AI_TOOLS`, `AI_TOOL_NAMES`, and the per-tool arg types
431
+ (`WebSearchArgs`, `DataExtractArgs`, `PdfExtractArgs`, …) from the SDK. This is the core set —
432
+ stable, versioned, documented here.
433
+ - **Runtime (live):** `await ai.catalog(collectionId)` returns the registry as the server sees it,
434
+ including any future app-contributed tools. The built-in set above is always present.
435
+
436
+ ### Recommended Models
437
+
438
+ Pass either a full model id (`openai/gpt-6.1-sol`) or a tier alias (`'cheap'`, `'balanced'`,
439
+ `'premium'`) as `model` — both resolve through the same server-side model registry. The tiers are the
440
+ GPT-6 family (prices per 1M tokens, input / output, OpenAI list price):
441
+
442
+ | Tier | Model | Alias | Price | Use for |
443
+ |------|-------|-------|-------|---------|
444
+ | Cheapest (default) | `openai/gpt-6-luna` | `'cheap'` / omit `model` | $0.10 / $0.50 | Everyday chat, high-volume/simple turns |
445
+ | Balanced | `openai/gpt-6.1-sol` | `'balanced'` | $2 / $10 | Admin agent / tool-heavy workflows (the `v1/responses` default) |
446
+ | Most capable | `openai/gpt-6-astra` | `'premium'` | $10 / $50 | The hardest reasoning, coding and long multi-step tool use |
447
+
448
+ The previous generation stays available by id — `openai/gpt-5.6-luna` ($0.20 / $1.20),
449
+ `openai/gpt-5.6-terra` ($2 / $12) and `openai/gpt-5.6-sol` ($4 / $20) — and `ai.models.list(collectionId)` returns
450
+ the full current set. GPT-6.1 Sol is the same input price as GPT-5.6 Terra with cheaper output, so prefer
451
+ the tiers. If OpenAI refuses a GPT-6 request for a model/option reason, SmartLinks retries it once on the
452
+ GPT-5.6 equivalent, so a call never fails just because a GPT-6 model doesn't accept something yet.
453
+
454
+ Every tier supports function/tool calling, Programmatic Tool Calling, and Multi-agent (see below), and all
455
+ three accept `service_tier: 'flex'` (≈50% cheaper, Batch-API rates, slower) or `'priority'` (premium, guaranteed
456
+ throughput) alongside the default `'standard'` tier. Pass it straight through in the request body:
457
+
458
+ ```typescript
459
+ const response = await ai.chat.responses.create('my-collection', {
460
+ model: 'balanced',
461
+ input: 'Summarize this week\'s ingested documents.',
462
+ service_tier: 'flex' // non-interactive/background work: cheaper, but can take minutes
463
+ });
464
+ ```
465
+
466
+ Flex requests run noticeably slower — reserve `flex` for non-production/background work (batch enrichment,
467
+ evaluations, async jobs), not user-facing chat turns. The server already raises its own timeout to 15
468
+ minutes for any request with `service_tier: 'flex'`, matching OpenAI's guidance — nothing to configure on
469
+ the client. On a `429` ("resource unavailable") the request wasn't charged; retry with backoff or drop
470
+ `service_tier` (or set it to `'auto'`) to fall back to standard processing.
471
+
472
+ ### Programmatic Tool Calling
473
+
474
+ Lets the model write a short in-memory program that orchestrates several tool calls (filtering,
475
+ looping, aggregating) before handing back one result, instead of a full message round-trip per
476
+ call. Add the hosted `programmatic_tool_calling` tool, and mark each function tool the program is
477
+ allowed to invoke with `allowed_callers: ['programmatic']`:
478
+
479
+ ```typescript
480
+ const response = await ai.chat.responses.create('my-collection', {
481
+ model: 'balanced',
482
+ input: 'Compare inventory with demand for every SKU in this collection.',
483
+ tools: [
484
+ {
485
+ type: 'function',
486
+ name: 'get_inventory',
487
+ description: 'Return available_units for a sku',
488
+ parameters: { type: 'object', properties: { sku: { type: 'string' } }, required: ['sku'] },
489
+ output_schema: { type: 'object', properties: { sku: { type: 'string' }, available_units: { type: 'number' } } },
490
+ allowed_callers: ['programmatic']
491
+ },
492
+ {
493
+ type: 'function',
494
+ name: 'get_demand',
495
+ description: 'Return requested_units for a sku',
496
+ parameters: { type: 'object', properties: { sku: { type: 'string' } }, required: ['sku'] },
497
+ output_schema: { type: 'object', properties: { sku: { type: 'string' }, requested_units: { type: 'number' } } },
498
+ allowed_callers: ['programmatic']
499
+ },
500
+ { type: 'programmatic_tool_calling' }
501
+ ]
502
+ });
503
+ ```
504
+
505
+ The response's `output` array can include a `program` item (the generated code), one
506
+ `function_call` item per program-issued call (tagged with `caller: { type: 'program', caller_id }`),
507
+ and a `program_output` item with the program's final `result`/`status`. Execute the `function_call`
508
+ items as normal and send results back keyed by their `call_id` on the next turn.
509
+
510
+ ### Multi-agent (subagents)
511
+
512
+ Lets the root agent spawn a tree of subagents that run in parallel and get synthesized back into
513
+ one response — useful for tasks that split cleanly into independent workstreams (e.g. research +
514
+ draft + review). Enable it by setting `multi_agent.enabled: true` — that's the entire contract on
515
+ your end; nothing else to configure or pass.
516
+
517
+ This is upstream beta functionality (OpenAI may still be limiting it to certain accounts/rollout),
518
+ so treat behavior and availability as subject to change until it's GA.
519
+
520
+ ```typescript
521
+ const response = await ai.chat.responses.create('my-collection', {
522
+ model: 'premium', // Sol recommended for the root agent when spawning subagents
523
+ input: 'Research three competitor loyalty programs, then draft a comparison summary.',
524
+ multi_agent: { enabled: true, max_concurrent_subagents: 3 }
525
+ });
526
+ ```
527
+
528
+ Subagent output arrives as additional items in `output`, each tagged `agent: { agent_name: '/root/<name>' }`
529
+ (root agent output uses `/root`). Notes/limits carried over from OpenAI's beta:
530
+
531
+ - `max_concurrent_subagents` defaults to `3`
532
+ - `reasoning.summary` and `max_tool_calls` are not supported while multi-agent is enabled
533
+ - Streaming is not supported while multi-agent is enabled — the SDK throws if you pass both
534
+ `stream: true` and `multi_agent.enabled: true`
535
+
536
+ ---
537
+
538
+ ## Chat Completions
539
+
540
+ OpenAI-compatible chat completions with streaming and tool calling support. Use this for compatibility with existing Chat Completions integrations; prefer the Responses API for new agentic features.
541
+
542
+ ### Basic Chat
543
+
544
+ ```typescript
545
+ const response = await ai.chat.completions.create('my-collection', {
546
+ model: 'google/gemini-2.5-flash',
547
+ messages: [
548
+ { role: 'system', content: 'You are a helpful assistant.' },
549
+ { role: 'user', content: 'What is the capital of France?' }
550
+ ]
551
+ });
552
+
553
+ console.log(response.choices[0].message.content);
554
+ // Output: "The capital of France is Paris."
555
+ ```
556
+
557
+ ### Streaming Chat
558
+
559
+ Stream responses in real-time for better UX:
560
+
561
+ - Set `stream: true`
562
+ - The SDK returns an `AsyncIterable<ChatCompletionChunk>`
563
+ - Iterate over chunks with `for await...of`
564
+ - Read incremental text from `chunk.choices[0]?.delta?.content`
565
+ - If `stream` is omitted or `false`, the method returns the normal `ChatCompletionResponse`
566
+
567
+ ```typescript
568
+ const stream = await ai.chat.completions.create('my-collection', {
569
+ model: 'google/gemini-2.5-flash',
570
+ messages: [
571
+ { role: 'user', content: 'Write a short poem about coding' }
572
+ ],
573
+ stream: true
574
+ });
575
+
576
+ for await (const chunk of stream) {
577
+ const content = chunk.choices[0]?.delta?.content || '';
578
+ process.stdout.write(content);
579
+ }
580
+ ```
581
+
582
+ ### Tool/Function Calling
583
+
584
+ Define tools (functions) that the AI can call:
585
+
586
+ ```typescript
587
+ const tools = [
588
+ {
589
+ type: 'function',
590
+ function: {
591
+ name: 'get_weather',
592
+ description: 'Get the current weather for a location',
593
+ parameters: {
594
+ type: 'object',
595
+ properties: {
596
+ location: {
597
+ type: 'string',
598
+ description: 'City name'
599
+ },
600
+ unit: {
601
+ type: 'string',
602
+ enum: ['celsius', 'fahrenheit']
603
+ }
604
+ },
605
+ required: ['location']
606
+ }
607
+ }
608
+ }
609
+ ];
610
+
611
+ const response = await ai.chat.completions.create('my-collection', {
612
+ model: 'google/gemini-2.5-flash',
613
+ messages: [
614
+ { role: 'user', content: 'What\'s the weather in Paris?' }
615
+ ],
616
+ tools
617
+ });
618
+
619
+ const toolCall = response.choices[0].message.tool_calls?.[0];
620
+ if (toolCall) {
621
+ console.log('Function:', toolCall.function.name);
622
+ console.log('Arguments:', JSON.parse(toolCall.function.arguments));
623
+ // { location: "Paris", unit: "celsius" }
624
+ }
625
+ ```
626
+
627
+ ### Available Models
628
+
629
+ ```typescript
630
+ // List all available models
631
+ const models = await ai.models.list('my-collection');
632
+
633
+ // Or filter by provider / capability
634
+ const openAiModels = await ai.models.list('my-collection', {
635
+ provider: 'openai'
636
+ });
637
+
638
+ const visionModels = await ai.models.list('my-collection', {
639
+ capability: 'vision'
640
+ });
641
+
642
+ models.data.forEach(model => {
643
+ console.log(`${model.name}`);
644
+ console.log(` Provider: ${model.provider}`);
645
+ console.log(` Context: ${model.contextWindow} tokens`);
646
+ console.log(` Pricing: $${model.pricing.input}/1M input tokens`);
647
+ });
648
+
649
+ // Get specific model info
650
+ const model = await ai.models.get('my-collection', 'google/gemini-2.5-flash');
651
+ console.log(model.capabilities); // ['text', 'vision', 'audio', 'code']
652
+ ```
653
+
654
+ Use `ai.models.list(collectionId)` as the source of truth for what your collection can use at runtime. The public docs provide recommendations, but actual availability depends on the SmartLinks model catalog exposed to that collection.
655
+
656
+ **Recommended Models:**
657
+
658
+ | Model | Use Case | Speed | Cost |
659
+ |-------|----------|-------|------|
660
+ | `openai/gpt-5.4` | Default for new agentic and structured-output workflows | Balanced | Medium |
661
+ | `openai/gpt-5-mini` | Lower-cost general purpose and JSON tasks | Fast | Low |
662
+ | `google/gemini-2.5-flash` | Fast multimodal and cost-sensitive general use | Fast | Low |
663
+ | `google/gemini-2.5-pro` | Complex reasoning and heavier multimodal tasks | Slower | Higher |
664
+
665
+ If you want a safe default for most new work, start with `openai/gpt-5.4`. If you want a lower-cost fallback, use `openai/gpt-5-mini` or `google/gemini-2.5-flash` depending on your latency and pricing goals.
666
+
667
+ ---
668
+
669
+ ## Knowledge: answers from your own content
670
+
671
+ Knowledge search makes a collection's own content (product manuals, help articles, web pages) searchable by meaning and keywords together, so a question like "how do I descale it" finds the right section, and exact terms such as model numbers and error codes are found too. People can search it from a website, Portal or Hub, and AI agents can search it with the `knowledge.search` tool.
672
+
673
+ ### How it fits together
674
+
675
+ - A collection has **knowledge sets**, such as "Product manuals" or "Help articles". Each set has a visibility:
676
+ - `public`: anyone can search it.
677
+ - `customer`: signed-in people can search it.
678
+ - `staff`: only the business's own admins and admin-side agents (the default).
679
+ - A set has **sources**:
680
+ - `markdown_feed`: a Markdown bundle at an https address (documents separated by `---`, each with a `Source: <url>` line).
681
+ - `url`: one web page or document at an address.
682
+ - `documents`: documents your app pushes itself with `knowledge.upsertDocuments`.
683
+ - The platform splits each document into passages along its headings and keeps them up to date: feeds and pages are re-read every 24 hours by default, and pushing a document with the same `ref` replaces its earlier version.
684
+
685
+ ### Set up a set and its sources (admin)
686
+
687
+ ```typescript
688
+ import { knowledge } from '@proveanything/smartlinks';
689
+
690
+ // Create the set (or update the one with this key)
691
+ await knowledge.saveSet('my-collection', {
692
+ key: 'manuals',
693
+ name: 'Product manuals',
694
+ visibility: 'public'
695
+ });
696
+
697
+ // A web page or Markdown feed, read in the background
698
+ await knowledge.addSource('my-collection', 'manuals', {
699
+ kind: 'url',
700
+ config: { url: 'https://example.com/manuals/coffee-maker' }
701
+ });
702
+
703
+ // Or documents your app pushes itself (up to 500 at a time)
704
+ const source = await knowledge.addSource('my-collection', 'manuals', { kind: 'documents' });
705
+
706
+ await knowledge.upsertDocuments('my-collection', source.id, [
707
+ {
708
+ ref: 'coffee-maker-deluxe',
709
+ title: 'Coffee Maker Deluxe manual',
710
+ body: '## Descaling\n\nDescale once a month. Fill the tank with descaler...',
711
+ url: 'https://example.com/manuals/coffee-maker-deluxe',
712
+ meta: { productId: 'coffee-maker-deluxe' }
713
+ }
714
+ ]);
715
+
716
+ // Check progress: status is 'pending' | 'indexing' | 'ready' | 'failed'
717
+ const sources = await knowledge.listSources('my-collection', 'manuals');
718
+ ```
719
+
720
+ ### Search from a website, Portal or Hub
721
+
722
+ `knowledge.publicSearch` needs no API key. Anyone sees `public` sets; a signed-in person sees `customer` sets too. `staff` sets are never searchable here.
723
+
724
+ ```typescript
725
+ const { results, mode } = await knowledge.publicSearch('my-collection', {
726
+ query: 'How do I descale my coffee maker?',
727
+ sets: ['manuals'], // optional: ids or keys
728
+ filters: { productId: 'coffee-maker-deluxe' }, // optional: exact matches on a document's meta
729
+ k: 5 // optional: default 8, at most 25
730
+ });
731
+
732
+ for (const r of results) {
733
+ // title: the document; heading: its section ("Cleaning › Descaling"); url: a link to it
734
+ console.log(r.title, r.heading, r.url);
735
+ console.log(r.snippet); // a short piece around the match, for a results list
736
+ // r.text is the whole passage, for reading out or passing to an AI
737
+ }
738
+ ```
739
+
740
+ `mode` says how the search ran: `hybrid` (meaning and keywords), `keywords`, or `none` (there were no sets to search). Admins can search every set, staff ones included, with `knowledge.search(collectionId, { query })`.
741
+
742
+ ### AI-written answers (admin agent with `knowledge.search`)
743
+
744
+ When you want the AI to write an answer from the passages, run an admin-side agent with the `knowledge.search` built-in tool. This needs admin credentials, so for a public website call it from your own server, behind your own endpoint:
745
+
746
+ ```typescript
747
+ // On your server (initialised with an admin API key)
748
+ const result = await ai.agent.run('my-collection', {
749
+ input: 'How do I descale the Coffee Maker Deluxe?',
750
+ instructions: 'Answer from the knowledge base only. Cite the page for each step. If nothing is found, say so.',
751
+ toolbelt: { builtins: ['knowledge.search'] }
752
+ });
753
+
754
+ console.log(result.finalText);
755
+ ```
756
+
757
+ The same `toolbelt` works with `ai.chat.responses.create`.
758
+
759
+ > **Not available yet on the public surface.** Built-in tools are off for `ai.public.agentRun`, so a public agent can't call `knowledge.search` yet. A cited-answer call for websites is planned. Until then, show passages from `knowledge.publicSearch`, or call an admin agent from your own server as above.
760
+
761
+ ### Conversations
762
+
763
+ Knowledge search answers one question at a time; it doesn't keep a conversation. If you need follow-up questions ("how often should I do that?"), keep the history yourself and send it with each `ai.chat.responses.create` call (see [Multimessage Input](#multimessage-input)), searching the knowledge base on your server for each new question.
764
+
765
+ ---
766
+
767
+ ## Voice Integration
768
+
769
+ Enable voice input and output for hands-free interaction.
770
+
771
+ ### Voice Patterns
772
+
773
+ The SDK supports three practical voice patterns:
774
+
775
+ | Pattern | Best For | SDK Building Blocks |
776
+ |---------|----------|---------------------|
777
+ | Voice → Text → Answer → Text | Manual helper Q&A, troubleshooting steps | `ai.voice.listen()` + `knowledge.publicSearch()` |
778
+ | Voice → Text → Answer → Voice | Hands-free assistants, accessibility | `ai.voice.listen()` + `knowledge.publicSearch()` + `ai.voice.speak()` or `ai.tts.generate()` |
779
+ | Real-time Voice | Low-latency spoken conversation | `ai.live.start()` with your own endpoints |
780
+
781
+ ### Current SDK Support
782
+
783
+ - `ai.voice.listen()` and `ai.voice.speak()` are browser helpers built on the Web Speech APIs.
784
+ - `ai.live.start()` runs a live voice (or text) conversation in the browser; you supply the endpoints that start the session and run server tools.
785
+ - `ai.tts.generate()` supports server-side text-to-speech generation.
786
+ - The SDK does not currently expose a first-class transcription endpoint like Whisper; if you need that flow, implement it as your own backend endpoint and feed the transcribed text into `knowledge.publicSearch()` or your own backend.
787
+
788
+ ### Recommended Approach
789
+
790
+ For product help and manuals, start with Voice → Text → Answer → Text/Voice. The text step is either `knowledge.publicSearch` (read out the best passage) or your own backend calling an admin agent with the `knowledge.search` tool (see [AI-written answers](#ai-written-answers-admin-agent-with-knowledgesearch)). Use a live session when low-latency spoken conversation matters more than answers grounded in your documents.
791
+
792
+ ### Browser Voice Helpers
793
+
794
+ These helpers are browser-only and rely on native speech recognition / speech synthesis support.
795
+
796
+ ```typescript
797
+ // Check if voice is supported
798
+ if (ai.voice.isSupported()) {
799
+ // Listen for voice input
800
+ const question = await ai.voice.listen('en-US');
801
+ console.log('User said:', question);
802
+
803
+ // Find the best passage in the manuals
804
+ const { results } = await knowledge.publicSearch('my-collection', {
805
+ query: question,
806
+ filters: { productId: 'coffee-maker-deluxe' },
807
+ k: 1
808
+ });
809
+
810
+ // Speak it
811
+ const answer = results[0]?.text ?? "Sorry, I couldn't find that in the manual.";
812
+ await ai.voice.speak(answer, { rate: 1.0 });
813
+ }
814
+ ```
815
+
816
+ ### Voice Assistant Class
817
+
818
+ Create a complete voice assistant:
819
+
820
+ ```typescript
821
+ class ProductVoiceAssistant {
822
+ constructor(private collectionId: string, private productId: string) {}
823
+
824
+ async ask(): Promise<string> {
825
+ // Listen for the question
826
+ const question = await ai.voice.listen();
827
+
828
+ // Find the best passage
829
+ const { results } = await knowledge.publicSearch(this.collectionId, {
830
+ query: question,
831
+ filters: { productId: this.productId },
832
+ k: 1
833
+ });
834
+ const answer = results[0]?.text ?? "Sorry, I couldn't find that in the manual.";
835
+
836
+ // Speak it
837
+ await ai.voice.speak(answer);
838
+ return answer;
839
+ }
840
+ }
841
+
842
+ // Usage
843
+ const assistant = new ProductVoiceAssistant('my-collection', 'coffee-maker-deluxe');
844
+ await assistant.ask(); // Voice question → spoken passage
845
+ ```
846
+
847
+ For an AI-written answer instead of a passage, replace the search with a call to your own endpoint that runs `ai.agent.run` with `toolbelt: { builtins: ['knowledge.search'] }`.
848
+
849
+ ### Live Voice Sessions
850
+
851
+ `ai.live.start()` runs a live conversation in the browser. SmartLinks mints a short-lived key with the assistant's instructions and tools fixed on it, and the browser connects straight to the provider, so audio never passes through SmartLinks. You supply the endpoints: `mint` (start the session) and `tool` (run a server tool).
852
+
853
+ ```typescript
854
+ const live = await ai.live.start({
855
+ endpoints: {
856
+ mint: () => fetch('/api/assistant/session', { method: 'POST' }).then(r => r.json()),
857
+ tool: (name, args, sessionId) =>
858
+ fetch('/api/assistant/tool', { method: 'POST', body: JSON.stringify({ name, args, sessionId }) }).then(r => r.json())
859
+ },
860
+ onCaption: (text) => showCaption(text)
861
+ });
862
+
863
+ // Later
864
+ live.stop();
865
+ ```
866
+
867
+ ### Voice + Knowledge Guidance
868
+
869
+ For answers grounded in your documents, prefer this pattern:
870
+
871
+ 1. Capture voice with `ai.voice.listen()` or your own transcription flow.
872
+ 2. Search with `knowledge.publicSearch()`, or send the text to your own backend, which runs an admin agent with `knowledge.search`.
873
+ 3. Render the text response for readability.
874
+ 4. Optionally speak the answer with `ai.voice.speak()` or `ai.tts.generate()`.
875
+
876
+ This is usually a better fit for manuals and procedural guidance than trying to use a live voice session as the primary search layer.
877
+
878
+ ---
879
+
880
+ ## Podcast Generation
881
+
882
+ Generate NotebookLM-style multi-voice conversational podcasts from product documentation.
883
+
884
+ ### Generate a Podcast
885
+
886
+ ```typescript
887
+ const podcast = await ai.podcast.generate('my-collection', {
888
+ productId: 'coffee-maker-deluxe',
889
+ duration: 5, // Target 5 minutes
890
+ style: 'casual', // 'casual' | 'professional' | 'educational' | 'entertaining'
891
+ voices: {
892
+ host1: 'nova', // Female voice
893
+ host2: 'onyx' // Male voice
894
+ },
895
+ includeAudio: true // Generate audio files
896
+ });
897
+
898
+ console.log('Podcast Title:', podcast.script.title);
899
+ console.log('Duration:', podcast.metadata.duration, 'seconds');
900
+ console.log('Download:', podcast.audio?.mixedUrl);
901
+ ```
902
+
903
+ ### Available Voices
904
+
905
+ | Voice | Gender | Personality | Best For |
906
+ |-------|--------|-------------|----------|
907
+ | `alloy` | Neutral | Balanced, neutral | Professional podcasts |
908
+ | `echo` | Male | Clear, authoritative | Expert/teacher role |
909
+ | `fable` | Neutral | Warm, storytelling | Narrative content |
910
+ | `onyx` | Male | Deep, engaging | Main host, discussions |
911
+ | `nova` | Female | Friendly, enthusiastic | Co-host, questions |
912
+ | `shimmer` | Female | Bright, energetic | Entertaining content |
913
+
914
+ **Recommended Combinations:**
915
+ - **Casual**: Nova + Onyx - Friendly and engaging
916
+ - **Professional**: Alloy + Echo - Authoritative and clear
917
+ - **Educational**: Fable + Echo - Teaching style
918
+ - **Entertaining**: Shimmer + Onyx - High energy
919
+
920
+ ### Access the Script
921
+
922
+ ```typescript
923
+ // View the generated script
924
+ podcast.script.segments.forEach((segment, i) => {
925
+ const speaker = segment.speaker === 'host1' ? 'Host 1' : 'Host 2';
926
+ console.log(`${speaker}: ${segment.text}`);
927
+ });
928
+ ```
929
+
930
+ ### Check Generation Status
931
+
932
+ For long-running podcast generation, poll for status:
933
+
934
+ ```typescript
935
+ // Start generation
936
+ const podcast = await ai.podcast.generate('my-collection', {
937
+ productId: 'coffee-maker-deluxe',
938
+ duration: 10,
939
+ includeAudio: true
940
+ });
941
+
942
+ // Poll for status
943
+ const checkStatus = async () => {
944
+ const status = await ai.podcast.getStatus('my-collection', podcast.podcastId);
945
+
946
+ console.log(`Status: ${status.status} (${status.progress}%)`);
947
+
948
+ if (status.status === 'completed' && status.result) {
949
+ console.log('Podcast ready!');
950
+ console.log('Listen:', status.result.audio?.mixedUrl);
951
+ return true;
952
+ } else if (status.status === 'failed') {
953
+ console.error('Generation failed:', status.error);
954
+ return true;
955
+ }
956
+
957
+ return false;
958
+ };
959
+
960
+ // Check every 5 seconds
961
+ const interval = setInterval(async () => {
962
+ const done = await checkStatus();
963
+ if (done) clearInterval(interval);
964
+ }, 5000);
965
+ ```
966
+
967
+ ### Text-to-Speech (TTS)
968
+
969
+ Generate custom audio from text:
970
+
971
+ ```typescript
972
+ const audioBlob = await ai.tts.generate('my-collection', {
973
+ text: 'Welcome to our podcast about coffee makers!',
974
+ voice: 'nova',
975
+ speed: 1.0,
976
+ format: 'mp3'
977
+ });
978
+
979
+ // Create audio URL for playback
980
+ const audioUrl = URL.createObjectURL(audioBlob);
981
+ ```
982
+
983
+ ---
984
+
985
+
986
+ ## Types & API reference
987
+
988
+ Full TypeScript types and the per-endpoint HTTP reference for every `SL.ai.*` method live in the
989
+ **generated** references — they're not duplicated here so they can't drift:
990
+
991
+ - **[`API_SUMMARY.md`](API_SUMMARY.md)** — every function signature + type (search `ai.`).
992
+ - **[`openapi.yaml`](../openapi.yaml)** — the raw HTTP endpoints.
993
+
994
+ For inline types, use LSP hover / go-to-definition on `SL.ai.*`.
995
+
996
+ ## Usage Examples
997
+
998
+ ### Example 1: Product FAQ
999
+
1000
+ ```typescript
1001
+ import { knowledge } from '@proveanything/smartlinks';
1002
+
1003
+ // Admin, once: a public set with the manual pushed into it
1004
+ async function setUpManual(collectionId: string) {
1005
+ await knowledge.saveSet(collectionId, { key: 'manuals', name: 'Product manuals', visibility: 'public' });
1006
+ const source = await knowledge.addSource(collectionId, 'manuals', { kind: 'documents' });
1007
+ await knowledge.upsertDocuments(collectionId, source.id, [{
1008
+ ref: 'coffee-maker-deluxe',
1009
+ title: 'Coffee Maker Deluxe manual',
1010
+ body: '## Making espresso
1011
+
1012
+ Fill the basket, tamp firmly, press the espresso button...',
1013
+ meta: { productId: 'coffee-maker-deluxe' }
1014
+ }]);
1015
+ }
1016
+
1017
+ // Website, any time: show the matching sections
1018
+ async function answerQuestion(collectionId: string, question: string) {
1019
+ const { results } = await knowledge.publicSearch(collectionId, {
1020
+ query: question,
1021
+ filters: { productId: 'coffee-maker-deluxe' },
1022
+ k: 3
1023
+ });
1024
+ return results.map(r => ({ title: r.heading ?? r.title, snippet: r.snippet, url: r.url }));
1025
+ }
1026
+ ```
1027
+
1028
+ ### Example 2: Streaming Chatbot UI
1029
+
1030
+ ```typescript
1031
+ async function streamingChatbot(userMessage: string) {
1032
+ const stream = await ai.chat.completions.create('my-collection', {
1033
+ model: 'google/gemini-2.5-flash',
1034
+ messages: [
1035
+ { role: 'system', content: 'You are a helpful assistant.' },
1036
+ { role: 'user', content: userMessage }
1037
+ ],
1038
+ stream: true
1039
+ });
1040
+
1041
+ let fullResponse = '';
1042
+
1043
+ for await (const chunk of stream) {
1044
+ const content = chunk.choices[0]?.delta?.content || '';
1045
+ fullResponse += content;
1046
+
1047
+ // Update UI in real-time
1048
+ updateChatUI(content);
1049
+ }
1050
+
1051
+ return fullResponse;
1052
+ }
1053
+ ```
1054
+
1055
+ ### Example 3: Multi-Turn Conversation
1056
+
1057
+ With the Responses API you keep the history yourself and send it with each call:
1058
+
1059
+ ```typescript
1060
+ async function chatConversation() {
1061
+ const collectionId = 'my-collection';
1062
+ const history: Array<{ role: 'user' | 'assistant'; content: string }> = [];
1063
+
1064
+ async function say(text: string) {
1065
+ history.push({ role: 'user', content: text });
1066
+ const response = await ai.chat.responses.create(collectionId, { input: history });
1067
+ history.push({ role: 'assistant', content: response.output_text });
1068
+ return response.output_text;
1069
+ }
1070
+
1071
+ console.log('A1:', await say('How do I clean the machine?'));
1072
+ console.log('A2:', await say('How often should I do that?')); // sees the first answer
1073
+ }
1074
+ ```
1075
+
1076
+ ### Example 4: React Hook for Product Help
1077
+
1078
+ ```typescript
1079
+ import { useState, useCallback } from 'react';
1080
+ import { knowledge } from '@proveanything/smartlinks';
1081
+ import type { KnowledgeSearchResult } from '@proveanything/smartlinks';
1082
+
1083
+ export function useProductHelp(collectionId: string, productId: string) {
1084
+ const [loading, setLoading] = useState(false);
1085
+ const [error, setError] = useState<string | null>(null);
1086
+ const [results, setResults] = useState<KnowledgeSearchResult[]>([]);
1087
+
1088
+ const ask = useCallback(async (query: string) => {
1089
+ setLoading(true);
1090
+ setError(null);
1091
+ try {
1092
+ const res = await knowledge.publicSearch(collectionId, { query, filters: { productId }, k: 3 });
1093
+ setResults(res.results);
1094
+ } catch (err: any) {
1095
+ setError(err.message);
1096
+ } finally {
1097
+ setLoading(false);
1098
+ }
1099
+ }, [collectionId, productId]);
1100
+
1101
+ return { ask, loading, error, results };
1102
+ }
1103
+
1104
+ // Usage in component
1105
+ function ProductHelp() {
1106
+ const { ask, loading, results } = useProductHelp('my-collection', 'coffee-maker');
1107
+
1108
+ return (
1109
+ <div>
1110
+ <button onClick={() => ask('How do I clean this?')} disabled={loading}>
1111
+ {loading ? 'Searching...' : 'Ask Question'}
1112
+ </button>
1113
+ {results.map(r => (
1114
+ <p key={r.id}>
1115
+ <strong>{r.heading ?? r.title}</strong> {r.snippet} {r.url && <a href={r.url}>Read more</a>}
1116
+ </p>
1117
+ ))}
1118
+ </div>
1119
+ );
1120
+ }
1121
+ ```
1122
+
1123
+
1124
+ ---
1125
+
1126
+ ## Error Handling
1127
+
1128
+ ### Error Codes
1129
+
1130
+ | Code | Type | HTTP Status | Description |
1131
+ |------|------|-------------|-------------|
1132
+ | `rate_limit_exceeded` | `rate_limit_error` | 429 | User exceeded rate limit |
1133
+ | `invalid_request` | `invalid_request_error` | 400 | Invalid parameters |
1134
+ | `authentication_error` | `authentication_error` | 401 | Invalid/missing API key |
1135
+ | `permission_denied` | `permission_error` | 403 | Insufficient permissions |
1136
+ | `not_found` | `not_found_error` | 404 | Resource not found |
1137
+ | `server_error` | `server_error` | 500 | Internal server error |
1138
+ | `service_unavailable` | `server_error` | 503 | Service temporarily unavailable |
1139
+
1140
+ ### Error Handling Pattern
1141
+
1142
+ ```typescript
1143
+ import { SmartLinksAIError } from '@proveanything/smartlinks';
1144
+
1145
+ async function robustChat() {
1146
+ try {
1147
+ const response = await ai.chat.responses.create('my-collection', {
1148
+ input: 'Help!'
1149
+ });
1150
+ return response.output_text;
1151
+ } catch (error) {
1152
+ if (error instanceof SmartLinksAIError) {
1153
+ switch (error.code) {
1154
+ case 'rate_limit_exceeded':
1155
+ console.error('Rate limit exceeded');
1156
+ console.log('Try again at:', new Date(error.resetAt!));
1157
+ break;
1158
+ case 'authentication_error':
1159
+ console.error('Invalid API key');
1160
+ break;
1161
+ case 'invalid_request':
1162
+ console.error('Invalid request:', error.message);
1163
+ break;
1164
+ default:
1165
+ console.error('API error:', error.message);
1166
+ }
1167
+ } else {
1168
+ console.error('Unexpected error:', error);
1169
+ }
1170
+ throw error;
1171
+ }
1172
+ }
1173
+ ```
1174
+
1175
+ ### Rate Limit Retry
1176
+
1177
+ ```typescript
1178
+ async function chatWithRetry(
1179
+ request: ResponsesRequest,
1180
+ maxRetries = 3
1181
+ ) {
1182
+ let retries = 0;
1183
+
1184
+ while (retries < maxRetries) {
1185
+ try {
1186
+ return await ai.chat.responses.create('my-collection', request);
1187
+ } catch (error) {
1188
+ if (error instanceof SmartLinksAIError && error.isRateLimitError()) {
1189
+ if (retries === maxRetries - 1) throw error;
1190
+
1191
+ const resetTime = new Date(error.resetAt!).getTime();
1192
+ const waitTime = resetTime - Date.now();
1193
+
1194
+ console.log(`Rate limited. Waiting ${waitTime}ms...`);
1195
+ await new Promise(resolve => setTimeout(resolve, waitTime));
1196
+
1197
+ retries++;
1198
+ } else {
1199
+ throw error;
1200
+ }
1201
+ }
1202
+ }
1203
+ }
1204
+ ```
1205
+
1206
+ ---
1207
+
1208
+ ## Rate Limiting
1209
+
1210
+ ### Rate Limit Overview
1211
+
1212
+ Public AI calls (such as `ai.public.agentRun`) are rate-limited per user: the signed-in person, or the `userId` you pass for an anonymous caller. Admin endpoints use API key authentication and are not rate-limited per user by default.
1213
+
1214
+ ### Rate Limit Headers
1215
+
1216
+ All API responses include rate limit information:
1217
+
1218
+ ```
1219
+ X-RateLimit-Limit: 20
1220
+ X-RateLimit-Remaining: 15
1221
+ X-RateLimit-Reset: 1707300000000
1222
+ ```
1223
+
1224
+ ### Checking Rate Limit
1225
+
1226
+ ```typescript
1227
+ // Check rate limit status before making requests
1228
+ const status = await ai.public.getRateLimit('my-collection', 'user-123');
1229
+
1230
+ console.log('Used:', status.used);
1231
+ console.log('Remaining:', status.remaining);
1232
+ console.log('Resets at:', new Date(status.resetAt));
1233
+
1234
+ if (status.remaining > 0) {
1235
+ // Safe to make request
1236
+ await ai.public.agentRun('my-collection', { input: question, userId: 'user-123' });
1237
+ } else {
1238
+ // Show user when they can ask again
1239
+ console.log('Rate limit reached. Try again at:', status.resetAt);
1240
+ }
1241
+ ```
1242
+
1243
+ ### Resetting Rate Limits (Admin)
1244
+
1245
+ ```typescript
1246
+ // Reset rate limit for a specific user
1247
+ await ai.rateLimit.reset('my-collection', 'user-123');
1248
+ console.log('Rate limit reset for user-123');
1249
+ ```
1250
+
1251
+ ---
1252
+
1253
+ ## Best Practices
1254
+
1255
+ ### 1. Choose the Right Model
1256
+
1257
+ ```typescript
1258
+ // For most new workflows (recommended default)
1259
+ await ai.chat.responses.create('my-collection', {
1260
+ model: 'openai/gpt-5.4',
1261
+ input: 'Create a concise onboarding checklist.'
1262
+ });
1263
+
1264
+ // For lower-cost structured or JSON-oriented work
1265
+ await ai.chat.responses.create('my-collection', {
1266
+ model: 'openai/gpt-5-mini',
1267
+ input: 'Return a color palette as JSON.'
1268
+ });
1269
+
1270
+ // For fast multimodal or cost-sensitive general use
1271
+ await ai.chat.completions.create('my-collection', {
1272
+ model: 'google/gemini-2.5-flash',
1273
+ messages: [...]
1274
+ });
1275
+
1276
+ // When you need the actual available catalog for this collection
1277
+ const available = await ai.models.list('my-collection');
1278
+ console.log(available.data.map(model => model.id));
1279
+ ```
1280
+
1281
+ ### 2. Use Streaming for Long Responses
1282
+
1283
+ Improve perceived performance with streaming:
1284
+
1285
+ ```typescript
1286
+ // Non-streaming: User waits for full response
1287
+ const response = await ai.chat.completions.create('my-collection', {
1288
+ messages: [...]
1289
+ });
1290
+
1291
+ // Streaming: User sees progress immediately
1292
+ const stream = await ai.chat.completions.create('my-collection', {
1293
+ stream: true,
1294
+ messages: [...]
1295
+ });
1296
+
1297
+ for await (const chunk of stream) {
1298
+ updateUI(chunk.choices[0]?.delta?.content);
1299
+ }
1300
+ ```
1301
+
1302
+ ### 3. Keep Conversation History Yourself
1303
+
1304
+ The Responses API doesn't store a conversation for you. Keep the turns and send them with each call:
1305
+
1306
+ ```typescript
1307
+ const history: ResponseInputItem[] = [];
1308
+
1309
+ history.push({ role: 'user', content: 'First question' });
1310
+ const first = await ai.chat.responses.create('my-collection', { input: history });
1311
+ history.push({ role: 'assistant', content: first.output_text });
1312
+
1313
+ history.push({ role: 'user', content: 'Follow-up question' });
1314
+ const second = await ai.chat.responses.create('my-collection', { input: history });
1315
+ ```
1316
+
1317
+ ### 4. Handle Rate Limits Gracefully
1318
+
1319
+ Show clear feedback to users:
1320
+
1321
+ ```typescript
1322
+ try {
1323
+ await ai.public.agentRun('my-collection', { input: question, userId });
1324
+ } catch (error) {
1325
+ if (error instanceof SmartLinksAIError && error.isRateLimitError()) {
1326
+ const resetTime = new Date(error.resetAt!);
1327
+ showNotification(
1328
+ `You've reached your question limit. ` +
1329
+ `Try again at ${resetTime.toLocaleTimeString()}`
1330
+ );
1331
+ }
1332
+ }
1333
+ ```
1334
+
1335
+ ### 5. Optimize Voice UX
1336
+
1337
+ Provide clear status updates:
1338
+
1339
+ ```typescript
1340
+ async function voiceAssistant() {
1341
+ try {
1342
+ showStatus('Listening...');
1343
+ const question = await ai.voice.listen();
1344
+
1345
+ showStatus('Searching...');
1346
+ const { results } = await knowledge.publicSearch('my-collection', { query: question, k: 1 });
1347
+ const answer = results[0]?.text ?? "Sorry, I couldn't find that.";
1348
+
1349
+ showStatus('Speaking...');
1350
+ await ai.voice.speak(answer);
1351
+
1352
+ showStatus('Ready');
1353
+ } catch (error) {
1354
+ showStatus('Error', error.message);
1355
+ }
1356
+ }
1357
+ ```
1358
+
1359
+ ### 6. Give Documents Clear Headings
1360
+
1361
+ Knowledge search splits each document into passages along its headings, and each result carries its section (`heading`, such as "Cleaning › Descaling"). Clear, specific headings give tighter passages and better results:
1362
+
1363
+ ```markdown
1364
+ ## Descaling
1365
+
1366
+ Descale once a month...
1367
+
1368
+ ## Cleaning the milk frother
1369
+
1370
+ Rinse after every use...
1371
+ ```
1372
+
1373
+ Put details you want to filter on (such as `productId`) in a pushed document's `meta`, then pass them as `filters` when searching.
1374
+
1375
+ ### 7. Use System Prompts Effectively
1376
+
1377
+ Provide clear instructions:
1378
+
1379
+ ```typescript
1380
+ await ai.chat.completions.create('my-collection', {
1381
+ messages: [
1382
+ {
1383
+ role: 'system',
1384
+ content: `You are a coffee maker expert assistant.
1385
+ - Be concise and clear
1386
+ - Use numbered lists for steps
1387
+ - Always mention safety precautions
1388
+ - If unsure, ask for clarification`
1389
+ },
1390
+ { role: 'user', content: 'How do I descale?' }
1391
+ ]
1392
+ });
1393
+ ```
1394
+
1395
+ ### 8. Monitor Usage and Costs
1396
+
1397
+ Track usage for cost management:
1398
+
1399
+ ```typescript
1400
+ const response = await ai.chat.completions.create('my-collection', {
1401
+ messages: [...]
1402
+ });
1403
+
1404
+ // Log token usage
1405
+ console.log('Usage:', response.usage);
1406
+ console.log('Prompt tokens:', response.usage.prompt_tokens);
1407
+ console.log('Completion tokens:', response.usage.completion_tokens);
1408
+ console.log('Total tokens:', response.usage.total_tokens);
1409
+
1410
+ // Calculate estimated cost
1411
+ const model = await ai.models.get('my-collection', response.model);
1412
+ const cost =
1413
+ (response.usage.prompt_tokens * model.pricing.input / 1_000_000) +
1414
+ (response.usage.completion_tokens * model.pricing.output / 1_000_000);
1415
+ console.log('Estimated cost: $', cost.toFixed(4));
1416
+ ```
1417
+
1418
+ ---
1419
+
1420
+ ## Providing Content to the AI Assistant
1421
+
1422
+ The portal's built-in AI assistant can discuss the content currently visible to the user. To make this work, your app must supply contextual content when the assistant requests it. There are three extraction methods, tried in priority order:
1423
+
1424
+ | Priority | Method | When Used |
1425
+ |----------|--------|-----------|
1426
+ | 1 | **Direct prop callback** | Container/widget rendered in the parent React context |
1427
+ | 2 | **PostMessage protocol** | App rendered in an iframe |
1428
+ | 3 | **DOM text fallback** | Neither of the above responded |
1429
+
1430
+ This section covers **methods 1 and 2** — the ones you implement in your app.
1431
+
1432
+ ### Method 1: Direct Prop (`onRequestAIContent`)
1433
+
1434
+ When your app is rendered as a **container** (a direct component in the parent's React tree), the framework passes an `onRequestAIContent` prop to your exported component. You do **not** call this prop yourself — the framework calls it when the AI assistant needs context.
1435
+
1436
+ Structure your component to make current state accessible when the callback fires:
1437
+
1438
+ ```tsx
1439
+ import { useEffect, useRef } from 'react';
1440
+
1441
+ export function PublicContainer(props) {
1442
+ const { onRequestAIContent, appId, ...rest } = props;
1443
+
1444
+ // Keep a ref to the latest content so the callback always returns fresh data
1445
+ const currentContentRef = useRef(null);
1446
+
1447
+ useEffect(() => {
1448
+ currentContentRef.current = buildCurrentContent();
1449
+ }, [relevantState]);
1450
+
1451
+ return <div data-app-container={appId}>{/* your UI */}</div>;
1452
+ }
1453
+ ```
1454
+
1455
+ The framework registers the content provider internally via `useAIContentExtraction.registerContentProvider()`. Your component just needs to respond when the callback is invoked.
1456
+
1457
+ ### Method 2: PostMessage Protocol (Iframes)
1458
+
1459
+ For iframe-embedded apps the framework sends a `postMessage` request and expects a response within **500 ms**. If your app doesn't reply in time the framework falls back to DOM text extraction.
1460
+
1461
+ **Request sent by the framework to your iframe:**
1462
+
1463
+ ```typescript
1464
+ {
1465
+ type: 'smartlinks:request-ai-content',
1466
+ requestId: 'ai-content-1709834567890-abc123' // unique per request
1467
+ }
1468
+ ```
1469
+
1470
+ **Response your app must send back:**
1471
+
1472
+ ```typescript
1473
+ {
1474
+ type: 'smartlinks:ai-content-response',
1475
+ requestId: 'ai-content-1709834567890-abc123', // echo back the requestId
1476
+ content: AIContentResponse
1477
+ }
1478
+ ```
1479
+
1480
+ **Minimal implementation:**
1481
+
1482
+ ```typescript
1483
+ window.addEventListener('message', async (event) => {
1484
+ if (event.data?.type === 'smartlinks:request-ai-content') {
1485
+ const content = await gatherAIContent();
1486
+
1487
+ window.parent.postMessage({
1488
+ type: 'smartlinks:ai-content-response',
1489
+ requestId: event.data.requestId,
1490
+ content,
1491
+ }, '*');
1492
+ }
1493
+ });
1494
+
1495
+ async function gatherAIContent(): Promise<AIContentResponse> {
1496
+ return {
1497
+ text: 'The user is viewing the warranty registration form...',
1498
+ contentLabel: 'Warranty Registration',
1499
+ };
1500
+ }
1501
+ ```
1502
+
1503
+ ### The `AIContentResponse` Interface
1504
+
1505
+ ```typescript
1506
+ interface AIContentResponse {
1507
+ /**
1508
+ * Plain text or markdown for the AI to use as context.
1509
+ * Injected into the system prompt. Max recommended: ~4000 characters.
1510
+ */
1511
+ text: string;
1512
+
1513
+ /**
1514
+ * Optional structured metadata (key-value pairs).
1515
+ * Not used directly in prompts but available for custom providers.
1516
+ */
1517
+ metadata?: Record<string, unknown>;
1518
+
1519
+ /**
1520
+ * Which documents to ground answers in. When provided, the assistant can search
1521
+ * the collection's knowledge sets (SL.knowledge.publicSearch) for this product.
1522
+ */
1523
+ ragHint?: {
1524
+ /** The product whose documents to search (matched against a document's meta.productId) */
1525
+ productId: string;
1526
+ /** Optional conversation ID */
1527
+ sessionId?: string;
1528
+ /** Optional hint to help scope the search */
1529
+ context?: string;
1530
+ };
1531
+
1532
+ /**
1533
+ * Human-readable label shown in context-update messages
1534
+ * (e.g. "Product Manual", "FAQ").
1535
+ */
1536
+ contentLabel?: string;
1537
+
1538
+ /**
1539
+ * How the assistant should use this content:
1540
+ * - 'context' (default): inject text into the system prompt
1541
+ * - 'rag': use ragHint to search the collection's knowledge sets
1542
+ * - 'hybrid': inject text as context AND search the knowledge sets
1543
+ */
1544
+ strategy?: 'context' | 'rag' | 'hybrid';
1545
+ }
1546
+ ```
1547
+
1548
+ ### Response Strategies
1549
+
1550
+ #### `context` (Default)
1551
+
1552
+ Return readable text. The assistant injects it into the system prompt as background knowledge. Good for descriptions, summaries, structured data, and FAQs.
1553
+
1554
+ ```typescript
1555
+ return {
1556
+ text: `
1557
+ ## Wine Details
1558
+ - **Name**: 2023 Château Margaux
1559
+ - **Region**: Bordeaux, France
1560
+ - **Tasting Notes**: Dark fruit, cedar, tobacco
1561
+ - **Food Pairing**: Lamb, aged cheese
1562
+ `,
1563
+ contentLabel: 'Wine Information',
1564
+ strategy: 'context',
1565
+ };
1566
+ ```
1567
+
1568
+ #### `rag`
1569
+
1570
+ Tell the assistant to answer from the collection's knowledge sets. The `text` field is minimal: the real knowledge comes from the documents in those sets (see [Knowledge: answers from your own content](#knowledge-answers-from-your-own-content)). Good for product manuals, large document sets, and technical specs.
1571
+
1572
+ ```typescript
1573
+ return {
1574
+ text: 'The user is viewing the espresso machine product page.',
1575
+ contentLabel: 'Product Assistant',
1576
+ strategy: 'rag',
1577
+ ragHint: {
1578
+ productId: 'espresso-machine-pro',
1579
+ context: 'User is on the troubleshooting section',
1580
+ },
1581
+ };
1582
+ ```
1583
+
1584
+ For the `rag` strategy to find anything, the product's documents must be in a knowledge set the visitor can read (`public`, or `customer` for signed-in people), with `productId` in each document's `meta`. A search scoped by the hint looks like this:
1585
+
1586
+ ```typescript
1587
+ const { results } = await SL.knowledge.publicSearch(collectionId, {
1588
+ query: userQuestion,
1589
+ filters: { productId: ragHint.productId },
1590
+ });
1591
+ ```
1592
+
1593
+ #### `hybrid`
1594
+
1595
+ Combines both: the `text` is injected as additional context **and** the user's questions are also answered from the knowledge sets. Good for museum exhibits, guided experiences, or any scenario with rich metadata alongside large document sets.
1596
+
1597
+ ```typescript
1598
+ return {
1599
+ text: `
1600
+ ## Exhibit: The Starry Night
1601
+ - **Artist**: Vincent van Gogh
1602
+ - **Year**: 1889
1603
+ - **Current Location**: Gallery 3, East Wing
1604
+ - **Audio Guide**: Available in 12 languages
1605
+ `,
1606
+ contentLabel: 'Museum Exhibit',
1607
+ strategy: 'hybrid',
1608
+ ragHint: {
1609
+ productId: 'starry-night-exhibit',
1610
+ context: 'Art history and technique questions',
1611
+ },
1612
+ };
1613
+ ```
1614
+
1615
+ ### Content Extraction Examples
1616
+
1617
+ #### Museum Guide App
1618
+
1619
+ ```typescript
1620
+ async function gatherAIContent(): Promise<AIContentResponse> {
1621
+ const exhibit = getCurrentExhibit();
1622
+
1623
+ return {
1624
+ text: `
1625
+ Exhibit: "${exhibit.title}" by ${exhibit.artist}
1626
+ Period: ${exhibit.period}
1627
+ Medium: ${exhibit.medium}
1628
+ Description: ${exhibit.curatorNotes}
1629
+ Related works in this gallery: ${exhibit.relatedWorks.join(', ')}
1630
+ `.trim(),
1631
+ contentLabel: `Exhibit: ${exhibit.title}`,
1632
+ strategy: 'hybrid',
1633
+ ragHint: {
1634
+ productId: exhibit.smartlinksProductId,
1635
+ context: `Art history, technique, and visitor information for ${exhibit.title}`,
1636
+ },
1637
+ metadata: {
1638
+ exhibitId: exhibit.id,
1639
+ gallery: exhibit.gallery,
1640
+ audioGuideAvailable: exhibit.hasAudioGuide,
1641
+ },
1642
+ };
1643
+ }
1644
+ ```
1645
+
1646
+ #### Wine Product App
1647
+
1648
+ ```typescript
1649
+ async function gatherAIContent(): Promise<AIContentResponse> {
1650
+ const wine = getCurrentWine();
1651
+ const reviews = await fetchRecentReviews(wine.id, 5);
1652
+
1653
+ return {
1654
+ text: `
1655
+ Wine: ${wine.name} (${wine.vintage})
1656
+ Winery: ${wine.winery}
1657
+ Region: ${wine.region}, ${wine.country}
1658
+ Grape: ${wine.grape}
1659
+ ABV: ${wine.abv}%
1660
+ Price: ${wine.price}
1661
+ Tasting Notes: ${wine.tastingNotes}
1662
+
1663
+ Recent Reviews:
1664
+ ${reviews.map(r => `- "${r.text}" (${r.rating}/5)`).join('\n')}
1665
+ `.trim(),
1666
+ contentLabel: 'Wine Details',
1667
+ strategy: 'context',
1668
+ };
1669
+ }
1670
+ ```
1671
+
1672
+ #### Equipment Manual App (knowledge only)
1673
+
1674
+ ```typescript
1675
+ async function gatherAIContent(): Promise<AIContentResponse> {
1676
+ const equipment = getCurrentEquipment();
1677
+
1678
+ return {
1679
+ text: `User is viewing: ${equipment.name} (Model: ${equipment.modelNumber})`,
1680
+ contentLabel: `${equipment.name} Assistant`,
1681
+ strategy: 'rag',
1682
+ ragHint: {
1683
+ productId: equipment.smartlinksProductId,
1684
+ sessionId: `manual-${equipment.id}-${Date.now()}`,
1685
+ context: 'Technical manual, troubleshooting, and maintenance',
1686
+ },
1687
+ };
1688
+ }
1689
+ ```
1690
+
1691
+ ### Timing & Lifecycle
1692
+
1693
+ - **On navigation**: When the user navigates to a new product/proof/app, the assistant automatically requests fresh content and injects a context-update system message.
1694
+ - **On first message**: If no content has been gathered yet, the assistant requests it before the first AI call.
1695
+ - **On manual refresh**: The assistant can re-request content at any time (e.g. if the user's view within the app has changed).
1696
+
1697
+ Content is requested **lazily** — your handler is only called when the AI assistant is active and needs context. If the user never opens the assistant, your handler is never called.
1698
+
1699
+ ### Method 3: DOM Fallback (Automatic)
1700
+
1701
+ If your app doesn't implement either of the above, the framework extracts `innerText` from the DOM element with `data-app-container="{appId}"`, truncated to ~4000 characters. This is a **last resort** — content quality is much lower than a structured response. Implementing Method 1 or 2 is strongly recommended.
1702
+
1703
+ ---
1704
+
1705
+ ## Related Documentation
1706
+
1707
+ - [API Summary](./API_SUMMARY.md) - Complete API reference
1708
+ - [Knowledge search](./knowledge.md) - Knowledge sets, sources and search
1709
+ - [Widgets](./widgets.md) - Embedding SmartLinks components
1710
+ - [Realtime](./realtime.md) - Realtime data updates
1711
+ - [iframe Responder](./iframe-responder.md) - iframe integration
1712
+
1713
+ ---
1714
+
1715
+ ## Support
1716
+
1717
+ For questions or issues:
1718
+
1719
+ - **Documentation:** https://smartlinks.app/docs
1720
+ - **GitHub:** https://github.com/Prove-Anything/smartlinks
1721
+ - **Email:** support@smartlinks.app