@proveanything/smartlinks 2.1.41 → 2.1.43

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 (122) 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.js +1 -1
  5. package/dist/api/index.d.ts +1 -0
  6. package/dist/api/index.js +1 -0
  7. package/dist/api/product.d.ts +2 -1
  8. package/dist/api/product.js +2 -1
  9. package/dist/api/subscriptions.d.ts +97 -0
  10. package/dist/api/subscriptions.js +178 -0
  11. package/dist/baseline.css +194 -194
  12. package/dist/docs/API_SUMMARY.md +1135 -832
  13. package/dist/docs/admin-cards.md +189 -189
  14. package/dist/docs/admin-views.md +9 -4
  15. package/dist/docs/agent-tools.md +156 -156
  16. package/dist/docs/ai-tools-and-skills.md +180 -180
  17. package/dist/docs/ai.md +1721 -1721
  18. package/dist/docs/analytics.md +39 -39
  19. package/dist/docs/app-data-storage.md +277 -277
  20. package/dist/docs/app-docs.md +73 -73
  21. package/dist/docs/app-manifest.md +852 -852
  22. package/dist/docs/app-records-pattern.md +388 -388
  23. package/dist/docs/appConfig.md +550 -550
  24. package/dist/docs/assistant-apps.md +172 -172
  25. package/dist/docs/assistant-context.md +119 -119
  26. package/dist/docs/bookings.md +442 -442
  27. package/dist/docs/comms.md +686 -686
  28. package/dist/docs/connectors.md +340 -340
  29. package/dist/docs/css-baseline.md +133 -133
  30. package/dist/docs/customer-guide.md +70 -70
  31. package/dist/docs/deploying-apps.md +340 -340
  32. package/dist/docs/entitlements.md +90 -90
  33. package/dist/docs/files.md +69 -69
  34. package/dist/docs/host-dependency-contract.md +210 -210
  35. package/dist/docs/i18n.md +9 -0
  36. package/dist/docs/integrations.md +322 -322
  37. package/dist/docs/interactions.md +545 -545
  38. package/dist/docs/item-context.md +181 -181
  39. package/dist/docs/knowledge.md +102 -102
  40. package/dist/docs/lots.md +111 -111
  41. package/dist/docs/loyalty.md +352 -352
  42. package/dist/docs/members.md +183 -182
  43. package/dist/docs/memberships.md +149 -0
  44. package/dist/docs/mobile-admin-container.md +693 -693
  45. package/dist/docs/operations.md +281 -281
  46. package/dist/docs/overview.md +483 -482
  47. package/dist/docs/proof-comms-triggers.md +142 -142
  48. package/dist/docs/proof-ownership-transfer.md +155 -155
  49. package/dist/docs/proof-product-data-scoping.md +462 -462
  50. package/dist/docs/proof-share-grants.md +305 -305
  51. package/dist/docs/realtime.md +138 -138
  52. package/dist/docs/records-admin-pattern.md +304 -304
  53. package/dist/docs/server-functions.md +1 -0
  54. package/dist/docs/standard-query.md +187 -187
  55. package/dist/docs/tag-codes.md +97 -97
  56. package/dist/docs/theme-tokens.md +252 -252
  57. package/dist/docs/wallet-passes.md +107 -107
  58. package/dist/docs/websites.md +123 -123
  59. package/dist/i18n.d.ts +6 -0
  60. package/dist/i18n.js +10 -0
  61. package/dist/openapi.yaml +426 -3
  62. package/dist/theme-boot.js +82 -78
  63. package/dist/theme.css +75 -75
  64. package/dist/types/appManifest.d.ts +32 -0
  65. package/dist/types/index.d.ts +1 -0
  66. package/dist/types/index.js +1 -0
  67. package/dist/types/subscriptions.d.ts +195 -0
  68. package/dist/types/subscriptions.js +9 -0
  69. package/docs/API_SUMMARY.md +1135 -832
  70. package/docs/admin-cards.md +189 -189
  71. package/docs/admin-views.md +9 -4
  72. package/docs/agent-tools.md +156 -156
  73. package/docs/ai-tools-and-skills.md +180 -180
  74. package/docs/ai.md +1721 -1721
  75. package/docs/analytics.md +39 -39
  76. package/docs/app-data-storage.md +277 -277
  77. package/docs/app-docs.md +73 -73
  78. package/docs/app-manifest.md +852 -852
  79. package/docs/app-records-pattern.md +388 -388
  80. package/docs/appConfig.md +550 -550
  81. package/docs/assistant-apps.md +172 -172
  82. package/docs/assistant-context.md +119 -119
  83. package/docs/bookings.md +442 -442
  84. package/docs/comms.md +686 -686
  85. package/docs/connectors.md +340 -340
  86. package/docs/css-baseline.md +133 -133
  87. package/docs/customer-guide.md +70 -70
  88. package/docs/deploying-apps.md +340 -340
  89. package/docs/entitlements.md +90 -90
  90. package/docs/files.md +69 -69
  91. package/docs/host-dependency-contract.md +210 -210
  92. package/docs/i18n.md +9 -0
  93. package/docs/integrations.md +322 -322
  94. package/docs/interactions.md +545 -545
  95. package/docs/item-context.md +181 -181
  96. package/docs/knowledge.md +102 -102
  97. package/docs/lots.md +111 -111
  98. package/docs/loyalty.md +352 -352
  99. package/docs/members.md +183 -182
  100. package/docs/memberships.md +149 -0
  101. package/docs/mobile-admin-container.md +693 -693
  102. package/docs/operations.md +281 -281
  103. package/docs/overview.md +483 -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/server-functions.md +1 -0
  110. package/docs/standard-query.md +187 -187
  111. package/docs/tag-codes.md +97 -97
  112. package/docs/theme-lookbook.v1.json +120 -120
  113. package/docs/theme-tokens.md +252 -252
  114. package/docs/wallet-passes.md +107 -107
  115. package/docs/websites.md +123 -123
  116. package/openapi.yaml +426 -3
  117. package/package.json +87 -87
  118. package/scripts/headless-check.mjs +87 -87
  119. package/scripts/lib/bare-imports.mjs +57 -57
  120. package/scripts/lib/keyed-app-data.mjs +21 -21
  121. package/scripts/publish.mjs +272 -272
  122. package/scripts/register-release.mjs +91 -91
package/docs/ai.md CHANGED
@@ -1,1721 +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
- - [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
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