@proveanything/smartlinks 2.1.39 → 2.1.40

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.
package/docs/ai.md CHANGED
@@ -11,7 +11,7 @@ Build AI-powered SmartLinks experiences with a practical SDK guide for responses
11
11
  - [Authentication](#authentication)
12
12
  - [Responses API](#responses-api)
13
13
  - [Chat Completions](#chat-completions)
14
- - [RAG: Product Assistants](#rag-product-assistants)
14
+ - [Knowledge: answers from your own content](#knowledge-answers-from-your-own-content)
15
15
  - [Voice Integration](#voice-integration)
16
16
  - [Podcast Generation](#podcast-generation)
17
17
  - [Types & API reference](#types--api-reference)
@@ -33,29 +33,30 @@ This guide is written for SDK users building real products, not backend operator
33
33
  |---|---|
34
34
  | Build a new AI workflow | Use [Responses API](#responses-api) |
35
35
  | Add compatibility with existing chat clients | Use [Chat Completions](#chat-completions) |
36
- | Build a product/manual assistant | Use [RAG: Product Assistants](#rag-product-assistants) |
36
+ | Answer questions from manuals, help articles or product pages | Use [Knowledge: answers from your own content](#knowledge-answers-from-your-own-content) |
37
37
  | Add spoken input/output | Use [Voice Integration](#voice-integration) |
38
38
  | Add progressive rendering | Use [Streaming Responses](#streaming-responses) or [Streaming Chat](#streaming-chat) |
39
39
 
40
- > **Which AI chat API? Three surfaces, three jobs — don't confuse them:**
41
- > - **`ai.chat.responses`** — the **default for new work**. Structured input, tool use, multi-agent, streaming; you manage any history. Reach for this first.
42
- > - **`ai.chat.completions`** — **OpenAI-compatible** (`messages[]`). Use it *only* to drop into existing OpenAI-style code; prefer Responses for anything new.
43
- > - **`ai.public.chat`** (+ `getSession` / `clearSession`) — the **public product assistant** with **server-managed conversation sessions** (RAG-grounded). This is the "ongoing conversation" surface, and it's public-facing.
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.
44
45
  >
45
- > Responses and Completions are *generation* APIs (not single-shot vs conversation — both take history); `ai.public.chat` is the one that keeps a conversation for you.
46
+ > Responses and Completions are generation APIs; both take history, neither stores it for you.
46
47
 
47
48
  ### Recommended starting points
48
49
 
49
50
  - New AI features: start with `ai.chat.responses.create(...)`
50
- - Product/manual assistants: start with `ai.public.chat(...)`
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
51
52
  - Existing OpenAI-style clients: use `ai.chat.completions.create(...)`
52
- - Real-time voice: use `ai.public.getToken(...)` and your provider's live client
53
+ - Real-time voice: use `ai.live.start(...)` or your provider's live client
53
54
 
54
55
  SmartLinks AI provides five main capabilities:
55
56
 
56
57
  1. **Responses API** - Preferred API for agentic workflows, multimodal inputs, and tool-driven responses
57
58
  2. **Chat Completions** - OpenAI-compatible text generation with streaming and tool calling
58
- 3. **RAG (Retrieval-Augmented Generation)** - Document-grounded Q&A for product assistants
59
+ 3. **Knowledge search** - Find the right passage in your manuals and help content, for people and for AI agents
59
60
  4. **Voice Integration** - Voice-to-text and text-to-voice for hands-free interaction
60
61
  5. **Podcast Generation** - NotebookLM-style multi-voice conversational podcasts from documents
61
62
 
@@ -64,12 +65,10 @@ SmartLinks AI provides five main capabilities:
64
65
  - ✅ Full TypeScript support with type safety
65
66
  - ✅ Streaming responses with async iterators
66
67
  - ✅ Automatic rate limit handling
67
- - ✅ Session management for conversations
68
68
  - ✅ Voice input/output helpers
69
69
  - ✅ Tool/function calling support
70
70
  - ✅ OpenAI-style Responses API support
71
- - ✅ Document indexing and retrieval
72
- - ✅ Customizable assistant behavior
71
+ - ✅ Knowledge search over your own content (meaning and keywords together)
73
72
 
74
73
  ---
75
74
 
@@ -97,22 +96,27 @@ const response = await ai.chat.responses.create('my-collection', {
97
96
  console.log(response.output_text);
98
97
  ```
99
98
 
100
- ### 2. Build a product assistant
99
+ ### 2. Answer a product question from your manuals
101
100
 
102
101
  ```typescript
103
- import { initializeApi, ai } from '@proveanything/smartlinks';
102
+ import { initializeApi, knowledge } from '@proveanything/smartlinks';
104
103
 
105
104
  initializeApi({ baseURL: 'https://smartlinks.app/api/v1' });
106
105
 
107
- const answer = await ai.public.chat('my-collection', {
108
- productId: 'coffee-maker-deluxe',
109
- userId: 'user-123',
110
- message: 'How do I descale this machine?'
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
111
110
  });
112
111
 
113
- console.log(answer.message);
112
+ for (const r of results) {
113
+ console.log(r.title, r.heading, r.url);
114
+ console.log(r.snippet);
115
+ }
114
116
  ```
115
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
+
116
120
  ### 3. Stream output into your UI
117
121
 
118
122
  ```typescript
@@ -147,17 +151,17 @@ The SDK automatically includes the API key in the `Authorization: Bearer <token>
147
151
 
148
152
  ### Public Endpoints
149
153
 
150
- Public endpoints don't require an API key but are rate-limited by `userId`:
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:
151
155
 
152
156
  ```typescript
153
157
  // No API key needed
154
- const response = await ai.public.chat('my-collection', {
155
- productId: 'coffee-maker',
156
- userId: 'user-123',
157
- message: 'How do I clean this?'
158
+ const { results } = await knowledge.publicSearch('my-collection', {
159
+ query: 'How do I clean this?'
158
160
  });
159
161
  ```
160
162
 
163
+ Public AI calls such as `ai.public.agentRun` are rate-limited per user (see [Rate Limiting](#rate-limiting)).
164
+
161
165
  ---
162
166
 
163
167
  ## Responses API
@@ -662,117 +666,101 @@ If you want a safe default for most new work, start with `openai/gpt-5.4`. If yo
662
666
 
663
667
  ---
664
668
 
665
- ## RAG: Product Assistants
669
+ ## Knowledge: answers from your own content
666
670
 
667
- Create intelligent product assistants that answer questions based on product documentation.
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.
668
672
 
669
- ### Setup: Index Documents
673
+ ### How it fits together
670
674
 
671
- First, index your product documentation:
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.
672
684
 
673
- ```typescript
674
- // Index a product manual from URL
675
- const result = await ai.rag.indexDocument('my-collection', {
676
- productId: 'coffee-maker-deluxe',
677
- documentUrl: 'https://example.com/manuals/coffee-maker.pdf',
678
- chunkSize: 500, // Tokens per chunk
679
- overlap: 50, // Token overlap between chunks
680
- provider: 'openai' // Embedding provider
681
- });
685
+ ### Set up a set and its sources (admin)
682
686
 
683
- console.log(`Indexed ${result.chunks} chunks`);
684
- console.log(`Dimensions: ${result.metadata.embeddingDimensions}`);
687
+ ```typescript
688
+ import { knowledge } from '@proveanything/smartlinks';
685
689
 
686
- // Or index from text directly
687
- await ai.rag.indexDocument('my-collection', {
688
- productId: 'coffee-maker-deluxe',
689
- text: 'Your product manual content here...',
690
- metadata: {
691
- source: 'manual',
692
- version: '2.0'
693
- }
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'
694
695
  });
695
- ```
696
696
 
697
- ### Configure Assistant
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
+ });
698
702
 
699
- Customize the assistant's behavior:
703
+ // Or documents your app pushes itself (up to 500 at a time)
704
+ const source = await knowledge.addSource('my-collection', 'manuals', { kind: 'documents' });
700
705
 
701
- ```typescript
702
- await ai.rag.configureAssistant('my-collection', {
703
- productId: 'coffee-maker-deluxe',
704
- systemPrompt: 'You are a helpful coffee maker assistant. Be concise and friendly.',
705
- model: 'google/gemini-2.5-flash',
706
- temperature: 0.7,
707
- maxTokensPerResponse: 500,
708
- rateLimitPerUser: 20,
709
- allowedTopics: ['usage', 'cleaning', 'troubleshooting'],
710
- customInstructions: {
711
- tone: 'friendly',
712
- additionalRules: 'Always include safety warnings when relevant.'
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
713
  }
714
- });
714
+ ]);
715
+
716
+ // Check progress: status is 'pending' | 'indexing' | 'ready' | 'failed'
717
+ const sources = await knowledge.listSources('my-collection', 'manuals');
715
718
  ```
716
719
 
717
- ### Public Chat
720
+ ### Search from a website, Portal or Hub
718
721
 
719
- Users can chat with the product assistant without authentication:
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.
720
723
 
721
724
  ```typescript
722
- // First question
723
- const response = await ai.public.chat('my-collection', {
724
- productId: 'coffee-maker-deluxe',
725
- userId: 'user-123',
726
- message: 'How do I descale my coffee maker?'
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
727
730
  });
728
731
 
729
- console.log('Answer:', response.message);
730
- console.log('Used', response.context.chunksUsed, 'document sections');
731
- console.log('Top similarity:', response.context.topSimilarity);
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
+ }
732
738
  ```
733
739
 
734
- ### Conversation History
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 })`.
735
741
 
736
- Maintain conversation context with sessions:
742
+ ### AI-written answers (admin agent with `knowledge.search`)
737
743
 
738
- ```typescript
739
- const sessionId = `session-${Date.now()}`;
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:
740
745
 
741
- // First question
742
- const q1 = await ai.public.chat('my-collection', {
743
- productId: 'coffee-maker-deluxe',
744
- userId: 'user-123',
745
- message: 'How do I clean it?',
746
- sessionId
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'] }
747
752
  });
748
753
 
749
- // Follow-up question (uses history)
750
- const q2 = await ai.public.chat('my-collection', {
751
- productId: 'coffee-maker-deluxe',
752
- userId: 'user-123',
753
- message: 'How often should I do that?',
754
- sessionId
755
- });
754
+ console.log(result.finalText);
755
+ ```
756
756
 
757
- // Get full conversation history
758
- const session = await ai.public.getSession('my-collection', sessionId);
759
- console.log('Messages:', session.messages);
760
- console.log('Total messages:', session.messageCount);
757
+ The same `toolbelt` works with `ai.chat.responses.create`.
761
758
 
762
- // Clear session when done
763
- await ai.public.clearSession('my-collection', sessionId);
764
- ```
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.
765
760
 
766
- ### Session Management
761
+ ### Conversations
767
762
 
768
- ```typescript
769
- // Get session statistics (admin)
770
- const stats = await ai.sessions.stats('my-collection');
771
- console.log('Total sessions:', stats.totalSessions);
772
- console.log('Active sessions:', stats.activeSessions);
773
- console.log('Total messages:', stats.totalMessages);
774
- console.log('Rate-limited users:', stats.rateLimitedUsers);
775
- ```
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.
776
764
 
777
765
  ---
778
766
 
@@ -786,20 +774,20 @@ The SDK supports three practical voice patterns:
786
774
 
787
775
  | Pattern | Best For | SDK Building Blocks |
788
776
  |---------|----------|---------------------|
789
- | Voice → Text → AI → Text | Manual helper Q&A, troubleshooting steps | `ai.voice.listen()` + `ai.public.chat()` |
790
- | Voice → Text → AI → Voice | Hands-free assistants, accessibility | `ai.voice.listen()` + `ai.public.chat()` + `ai.voice.speak()` or `ai.tts.generate()` |
791
- | Real-time Voice | Low-latency spoken conversation | `ai.public.getToken()` + Gemini Live client |
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 |
792
780
 
793
781
  ### Current SDK Support
794
782
 
795
783
  - `ai.voice.listen()` and `ai.voice.speak()` are browser helpers built on the Web Speech APIs.
796
- - `ai.public.getToken()` generates ephemeral tokens for Gemini Live sessions.
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.
797
785
  - `ai.tts.generate()` supports server-side text-to-speech generation.
798
- - The SDK does not currently expose a first-class transcription endpoint like Whisper; if you need that flow, implement it as your own backend endpoint and feed the transcribed text into `ai.public.chat()` or `ai.chat.responses.create()`.
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.
799
787
 
800
788
  ### Recommended Approach
801
789
 
802
- For product assistants and RAG-backed support, start with Voice → Text → AI → Text/Voice. It gives you the best control over retrieval, session history, and cost. Use Gemini Live when low-latency spoken conversation matters more than deep document grounding.
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.
803
791
 
804
792
  ### Browser Voice Helpers
805
793
 
@@ -812,18 +800,16 @@ if (ai.voice.isSupported()) {
812
800
  const question = await ai.voice.listen('en-US');
813
801
  console.log('User said:', question);
814
802
 
815
- // Get answer from AI
816
- const response = await ai.public.chat('my-collection', {
817
- productId: 'coffee-maker-deluxe',
818
- userId: 'user-123',
819
- message: question
820
- });
821
-
822
- // Speak the answer
823
- await ai.voice.speak(response.message, {
824
- voice: 'alloy',
825
- rate: 1.0
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
826
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 });
827
813
  }
828
814
  ```
829
815
 
@@ -833,94 +819,61 @@ Create a complete voice assistant:
833
819
 
834
820
  ```typescript
835
821
  class ProductVoiceAssistant {
836
- private collectionId: string;
837
- private productId: string;
838
- private userId: string;
839
- private sessionId: string;
840
-
841
- constructor(config: {
842
- collectionId: string;
843
- productId: string;
844
- userId: string;
845
- }) {
846
- this.collectionId = config.collectionId;
847
- this.productId = config.productId;
848
- this.userId = config.userId;
849
- this.sessionId = `voice-${Date.now()}`;
850
- }
822
+ constructor(private collectionId: string, private productId: string) {}
851
823
 
852
824
  async ask(): Promise<string> {
853
- // Listen for question
854
- console.log('Listening...');
825
+ // Listen for the question
855
826
  const question = await ai.voice.listen();
856
827
 
857
- // Get answer
858
- console.log('Processing...');
859
- const response = await ai.public.chat(this.collectionId, {
860
- productId: this.productId,
861
- userId: this.userId,
862
- message: question,
863
- sessionId: this.sessionId
828
+ // Find the best passage
829
+ const { results } = await knowledge.publicSearch(this.collectionId, {
830
+ query: question,
831
+ filters: { productId: this.productId },
832
+ k: 1
864
833
  });
834
+ const answer = results[0]?.text ?? "Sorry, I couldn't find that in the manual.";
865
835
 
866
- // Speak answer
867
- console.log('Speaking...');
868
- await ai.voice.speak(response.message);
869
-
870
- return response.message;
871
- }
872
-
873
- async getRemainingQuestions(): Promise<number> {
874
- const status = await ai.public.getRateLimit(this.collectionId, this.userId);
875
- return status.remaining;
836
+ // Speak it
837
+ await ai.voice.speak(answer);
838
+ return answer;
876
839
  }
877
840
  }
878
841
 
879
842
  // Usage
880
- const assistant = new ProductVoiceAssistant({
881
- collectionId: 'my-collection',
882
- productId: 'coffee-maker-deluxe',
883
- userId: 'user-123'
884
- });
885
-
886
- await assistant.ask(); // Voice question → Voice answer
887
- const remaining = await assistant.getRemainingQuestions();
888
- console.log(`${remaining} questions remaining`);
843
+ const assistant = new ProductVoiceAssistant('my-collection', 'coffee-maker-deluxe');
844
+ await assistant.ask(); // Voice question → spoken passage
889
845
  ```
890
846
 
891
- ### Gemini Live Integration
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'] }`.
892
848
 
893
- Generate ephemeral tokens for Gemini Live (multimodal voice):
849
+ ### Live Voice Sessions
894
850
 
895
- Use this path for real-time voice sessions. The SDK only issues the short-lived token; the actual live connection is made with the provider client.
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).
896
852
 
897
853
  ```typescript
898
- // Generate token for voice session
899
- const token = await ai.public.getToken('my-collection', {
900
- settings: {
901
- ttl: 3600, // 1 hour
902
- voice: 'alloy',
903
- language: 'en-US'
904
- }
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)
905
861
  });
906
862
 
907
- console.log('Token:', token.token);
908
- console.log('Expires at:', new Date(token.expiresAt));
909
-
910
- // Use token with Gemini Live API
911
- // (See Google's Gemini documentation)
863
+ // Later
864
+ live.stop();
912
865
  ```
913
866
 
914
- ### Voice + RAG Guidance
867
+ ### Voice + Knowledge Guidance
915
868
 
916
- For document-grounded assistants, prefer this pattern:
869
+ For answers grounded in your documents, prefer this pattern:
917
870
 
918
871
  1. Capture voice with `ai.voice.listen()` or your own transcription flow.
919
- 2. Send the transcribed text to `ai.public.chat()`.
872
+ 2. Search with `knowledge.publicSearch()`, or send the text to your own backend, which runs an admin agent with `knowledge.search`.
920
873
  3. Render the text response for readability.
921
874
  4. Optionally speak the answer with `ai.voice.speak()` or `ai.tts.generate()`.
922
875
 
923
- This is usually a better fit for manuals and procedural guidance than trying to use a live voice session as the primary retrieval layer.
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.
924
877
 
925
878
  ---
926
879
 
@@ -1042,34 +995,33 @@ For inline types, use LSP hover / go-to-definition on `SL.ai.*`.
1042
995
 
1043
996
  ## Usage Examples
1044
997
 
1045
- ### Example 1: Product FAQ Bot
998
+ ### Example 1: Product FAQ
1046
999
 
1047
1000
  ```typescript
1048
- async function createProductFAQ() {
1049
- const collectionId = 'my-collection';
1050
- const productId = 'coffee-maker-deluxe';
1051
-
1052
- // 1. Index product documentation
1053
- await ai.rag.indexDocument(collectionId, {
1054
- productId,
1055
- documentUrl: 'https://example.com/manual.pdf'
1056
- });
1057
-
1058
- // 2. Configure assistant
1059
- await ai.rag.configureAssistant(collectionId, {
1060
- productId,
1061
- systemPrompt: 'You are a coffee maker expert. Provide clear, step-by-step instructions.',
1062
- rateLimitPerUser: 30
1063
- });
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
+ }
1064
1016
 
1065
- // 3. Answer user questions
1066
- const answer = await ai.public.chat(collectionId, {
1067
- productId,
1068
- userId: 'user-123',
1069
- message: 'How do I make espresso?'
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
1070
1023
  });
1071
-
1072
- console.log(answer.message);
1024
+ return results.map(r => ({ title: r.heading ?? r.title, snippet: r.snippet, url: r.url }));
1073
1025
  }
1074
1026
  ```
1075
1027
 
@@ -1102,101 +1054,67 @@ async function streamingChatbot(userMessage: string) {
1102
1054
 
1103
1055
  ### Example 3: Multi-Turn Conversation
1104
1056
 
1057
+ With the Responses API you keep the history yourself and send it with each call:
1058
+
1105
1059
  ```typescript
1106
1060
  async function chatConversation() {
1107
1061
  const collectionId = 'my-collection';
1108
- const sessionId = `chat-${Date.now()}`;
1109
- const userId = 'user-123';
1110
- const productId = 'coffee-maker-deluxe';
1111
-
1112
- // Question 1
1113
- const a1 = await ai.public.chat(collectionId, {
1114
- productId,
1115
- userId,
1116
- message: 'How do I clean the machine?',
1117
- sessionId
1118
- });
1119
- console.log('A1:', a1.message);
1120
-
1121
- // Question 2 (references previous context)
1122
- const a2 = await ai.public.chat(collectionId, {
1123
- productId,
1124
- userId,
1125
- message: 'How often should I do that?',
1126
- sessionId
1127
- });
1128
- console.log('A2:', a2.message);
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
+ }
1129
1070
 
1130
- // Get full history
1131
- const session = await ai.public.getSession(collectionId, sessionId);
1132
- console.log('Full conversation:', session.messages);
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
1133
1073
  }
1134
1074
  ```
1135
1075
 
1136
- ### Example 4: React Hook for Product Assistant
1076
+ ### Example 4: React Hook for Product Help
1137
1077
 
1138
1078
  ```typescript
1139
1079
  import { useState, useCallback } from 'react';
1140
- import { ai } from '@proveanything/smartlinks';
1080
+ import { knowledge } from '@proveanything/smartlinks';
1081
+ import type { KnowledgeSearchResult } from '@proveanything/smartlinks';
1141
1082
 
1142
- export function useProductAssistant(
1143
- collectionId: string,
1144
- productId: string,
1145
- userId: string
1146
- ) {
1083
+ export function useProductHelp(collectionId: string, productId: string) {
1147
1084
  const [loading, setLoading] = useState(false);
1148
1085
  const [error, setError] = useState<string | null>(null);
1149
- const [rateLimit, setRateLimit] = useState({ remaining: 20, limit: 20 });
1086
+ const [results, setResults] = useState<KnowledgeSearchResult[]>([]);
1150
1087
 
1151
- const ask = useCallback(async (message: string) => {
1088
+ const ask = useCallback(async (query: string) => {
1152
1089
  setLoading(true);
1153
1090
  setError(null);
1154
-
1155
1091
  try {
1156
- const response = await ai.public.chat(collectionId, {
1157
- productId,
1158
- userId,
1159
- message
1160
- });
1161
-
1162
- setRateLimit(prev => ({
1163
- ...prev,
1164
- remaining: prev.remaining - 1
1165
- }));
1166
-
1167
- return response.message;
1092
+ const res = await knowledge.publicSearch(collectionId, { query, filters: { productId }, k: 3 });
1093
+ setResults(res.results);
1168
1094
  } catch (err: any) {
1169
1095
  setError(err.message);
1170
- throw err;
1171
1096
  } finally {
1172
1097
  setLoading(false);
1173
1098
  }
1174
- }, [collectionId, productId, userId]);
1099
+ }, [collectionId, productId]);
1175
1100
 
1176
- return { ask, loading, error, rateLimit };
1101
+ return { ask, loading, error, results };
1177
1102
  }
1178
1103
 
1179
1104
  // Usage in component
1180
1105
  function ProductHelp() {
1181
- const { ask, loading, rateLimit } = useProductAssistant(
1182
- 'my-collection',
1183
- 'coffee-maker',
1184
- 'user-123'
1185
- );
1186
- const [answer, setAnswer] = useState('');
1187
-
1188
- const handleAsk = async () => {
1189
- const response = await ask('How do I clean this?');
1190
- setAnswer(response);
1191
- };
1106
+ const { ask, loading, results } = useProductHelp('my-collection', 'coffee-maker');
1192
1107
 
1193
1108
  return (
1194
1109
  <div>
1195
- <button onClick={handleAsk} disabled={loading}>
1196
- {loading ? 'Asking...' : 'Ask Question'}
1110
+ <button onClick={() => ask('How do I clean this?')} disabled={loading}>
1111
+ {loading ? 'Searching...' : 'Ask Question'}
1197
1112
  </button>
1198
- {answer && <p>{answer}</p>}
1199
- <p>{rateLimit.remaining} questions remaining</p>
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
+ ))}
1200
1118
  </div>
1201
1119
  );
1202
1120
  }
@@ -1216,7 +1134,6 @@ function ProductHelp() {
1216
1134
  | `authentication_error` | `authentication_error` | 401 | Invalid/missing API key |
1217
1135
  | `permission_denied` | `permission_error` | 403 | Insufficient permissions |
1218
1136
  | `not_found` | `not_found_error` | 404 | Resource not found |
1219
- | `document_not_found` | `not_found_error` | 404 | Product document not indexed |
1220
1137
  | `server_error` | `server_error` | 500 | Internal server error |
1221
1138
  | `service_unavailable` | `server_error` | 503 | Service temporarily unavailable |
1222
1139
 
@@ -1227,12 +1144,10 @@ import { SmartLinksAIError } from '@proveanything/smartlinks';
1227
1144
 
1228
1145
  async function robustChat() {
1229
1146
  try {
1230
- const response = await ai.public.chat('my-collection', {
1231
- productId: 'coffee-maker',
1232
- userId: 'user-123',
1233
- message: 'Help!'
1147
+ const response = await ai.chat.responses.create('my-collection', {
1148
+ input: 'Help!'
1234
1149
  });
1235
- return response.message;
1150
+ return response.output_text;
1236
1151
  } catch (error) {
1237
1152
  if (error instanceof SmartLinksAIError) {
1238
1153
  switch (error.code) {
@@ -1240,9 +1155,6 @@ async function robustChat() {
1240
1155
  console.error('Rate limit exceeded');
1241
1156
  console.log('Try again at:', new Date(error.resetAt!));
1242
1157
  break;
1243
- case 'document_not_found':
1244
- console.error('Product manual not indexed yet');
1245
- break;
1246
1158
  case 'authentication_error':
1247
1159
  console.error('Invalid API key');
1248
1160
  break;
@@ -1264,14 +1176,14 @@ async function robustChat() {
1264
1176
 
1265
1177
  ```typescript
1266
1178
  async function chatWithRetry(
1267
- request: PublicChatRequest,
1179
+ request: ResponsesRequest,
1268
1180
  maxRetries = 3
1269
1181
  ) {
1270
1182
  let retries = 0;
1271
1183
 
1272
1184
  while (retries < maxRetries) {
1273
1185
  try {
1274
- return await ai.public.chat('my-collection', request);
1186
+ return await ai.chat.responses.create('my-collection', request);
1275
1187
  } catch (error) {
1276
1188
  if (error instanceof SmartLinksAIError && error.isRateLimitError()) {
1277
1189
  if (retries === maxRetries - 1) throw error;
@@ -1297,15 +1209,7 @@ async function chatWithRetry(
1297
1209
 
1298
1210
  ### Rate Limit Overview
1299
1211
 
1300
- Public endpoints are rate-limited per `userId`:
1301
-
1302
- | Endpoint Type | Default Limit | Window |
1303
- |--------------|---------------|--------|
1304
- | Public Chat | 20 requests | 1 hour |
1305
- | Token Generation | 10 requests | 1 hour |
1306
- | Admin Endpoints | Unlimited* | - |
1307
-
1308
- *Admin endpoints use API key authentication and are not rate-limited by default.
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.
1309
1213
 
1310
1214
  ### Rate Limit Headers
1311
1215
 
@@ -1329,7 +1233,7 @@ console.log('Resets at:', new Date(status.resetAt));
1329
1233
 
1330
1234
  if (status.remaining > 0) {
1331
1235
  // Safe to make request
1332
- await ai.public.chat(/* ... */);
1236
+ await ai.public.agentRun('my-collection', { input: question, userId: 'user-123' });
1333
1237
  } else {
1334
1238
  // Show user when they can ask again
1335
1239
  console.log('Rate limit reached. Try again at:', status.resetAt);
@@ -1395,26 +1299,19 @@ for await (const chunk of stream) {
1395
1299
  }
1396
1300
  ```
1397
1301
 
1398
- ### 3. Maintain Session Context
1302
+ ### 3. Keep Conversation History Yourself
1399
1303
 
1400
- Keep conversations coherent with session IDs:
1304
+ The Responses API doesn't store a conversation for you. Keep the turns and send them with each call:
1401
1305
 
1402
1306
  ```typescript
1403
- // Generate unique session ID per conversation
1404
- const sessionId = `user-${userId}-product-${productId}`;
1405
-
1406
- // All questions in same conversation use same sessionId
1407
- await ai.public.chat('my-collection', {
1408
- sessionId,
1409
- message: 'First question',
1410
- ...
1411
- });
1307
+ const history: ResponseInputItem[] = [];
1412
1308
 
1413
- await ai.public.chat('my-collection', {
1414
- sessionId,
1415
- message: 'Follow-up question',
1416
- ...
1417
- });
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 });
1418
1315
  ```
1419
1316
 
1420
1317
  ### 4. Handle Rate Limits Gracefully
@@ -1423,7 +1320,7 @@ Show clear feedback to users:
1423
1320
 
1424
1321
  ```typescript
1425
1322
  try {
1426
- await ai.public.chat('my-collection', {...});
1323
+ await ai.public.agentRun('my-collection', { input: question, userId });
1427
1324
  } catch (error) {
1428
1325
  if (error instanceof SmartLinksAIError && error.isRateLimitError()) {
1429
1326
  const resetTime = new Date(error.resetAt!);
@@ -1445,14 +1342,12 @@ async function voiceAssistant() {
1445
1342
  showStatus('Listening...');
1446
1343
  const question = await ai.voice.listen();
1447
1344
 
1448
- showStatus('Processing...');
1449
- const answer = await ai.public.chat('my-collection', {
1450
- message: question,
1451
- ...
1452
- });
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.";
1453
1348
 
1454
1349
  showStatus('Speaking...');
1455
- await ai.voice.speak(answer.message);
1350
+ await ai.voice.speak(answer);
1456
1351
 
1457
1352
  showStatus('Ready');
1458
1353
  } catch (error) {
@@ -1461,28 +1356,22 @@ async function voiceAssistant() {
1461
1356
  }
1462
1357
  ```
1463
1358
 
1464
- ### 6. Chunk Large Documents
1359
+ ### 6. Give Documents Clear Headings
1465
1360
 
1466
- For better RAG performance, chunk documents appropriately:
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:
1467
1362
 
1468
- ```typescript
1469
- // For technical manuals
1470
- await ai.rag.indexDocument('my-collection', {
1471
- productId: 'coffee-maker',
1472
- documentUrl: '...',
1473
- chunkSize: 500, // Smaller chunks for precise answers
1474
- overlap: 50 // Overlap maintains context
1475
- });
1363
+ ```markdown
1364
+ ## Descaling
1476
1365
 
1477
- // For narrative content
1478
- await ai.rag.indexDocument('my-collection', {
1479
- productId: 'coffee-maker',
1480
- documentUrl: '...',
1481
- chunkSize: 1000, // Larger chunks for coherent responses
1482
- overlap: 100
1483
- });
1366
+ Descale once a month...
1367
+
1368
+ ## Cleaning the milk frother
1369
+
1370
+ Rinse after every use...
1484
1371
  ```
1485
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
+
1486
1375
  ### 7. Use System Prompts Effectively
1487
1376
 
1488
1377
  Provide clear instructions:
@@ -1628,15 +1517,15 @@ interface AIContentResponse {
1628
1517
  metadata?: Record<string, unknown>;
1629
1518
 
1630
1519
  /**
1631
- * Pre-built RAG configuration. When provided, the assistant can use
1632
- * SL.ai.public.chat() to ground answers in indexed product documents.
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.
1633
1522
  */
1634
1523
  ragHint?: {
1635
- /** The product ID whose indexed documents should be queried */
1524
+ /** The product whose documents to search (matched against a document's meta.productId) */
1636
1525
  productId: string;
1637
- /** Optional session ID for multi-turn RAG conversations */
1526
+ /** Optional conversation ID */
1638
1527
  sessionId?: string;
1639
- /** Optional context hint to help scope the RAG query */
1528
+ /** Optional hint to help scope the search */
1640
1529
  context?: string;
1641
1530
  };
1642
1531
 
@@ -1649,8 +1538,8 @@ interface AIContentResponse {
1649
1538
  /**
1650
1539
  * How the assistant should use this content:
1651
1540
  * - 'context' (default): inject text into the system prompt
1652
- * - 'rag': use ragHint to query indexed docs via SL.ai.public.chat()
1653
- * - 'hybrid': inject text as context AND ground answers via RAG
1541
+ * - 'rag': use ragHint to search the collection's knowledge sets
1542
+ * - 'hybrid': inject text as context AND search the knowledge sets
1654
1543
  */
1655
1544
  strategy?: 'context' | 'rag' | 'hybrid';
1656
1545
  }
@@ -1678,7 +1567,7 @@ return {
1678
1567
 
1679
1568
  #### `rag`
1680
1569
 
1681
- Tell the assistant to query pre-indexed documents via SmartLinks RAG. The `text` field is minimal — the real knowledge comes from the indexed docs. Good for product manuals, large document sets, and technical specs.
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.
1682
1571
 
1683
1572
  ```typescript
1684
1573
  return {
@@ -1687,26 +1576,23 @@ return {
1687
1576
  strategy: 'rag',
1688
1577
  ragHint: {
1689
1578
  productId: 'espresso-machine-pro',
1690
- sessionId: `rag-session-${userId}`,
1691
1579
  context: 'User is on the troubleshooting section',
1692
1580
  },
1693
1581
  };
1694
1582
  ```
1695
1583
 
1696
- When the assistant receives a `rag` strategy it routes the question through `SL.ai.public.chat()`:
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:
1697
1585
 
1698
1586
  ```typescript
1699
- const response = await SL.ai.public.chat(collectionId, {
1700
- productId: ragHint.productId,
1701
- userId: currentUserId,
1702
- message: userQuestion,
1703
- sessionId: ragHint.sessionId,
1587
+ const { results } = await SL.knowledge.publicSearch(collectionId, {
1588
+ query: userQuestion,
1589
+ filters: { productId: ragHint.productId },
1704
1590
  });
1705
1591
  ```
1706
1592
 
1707
1593
  #### `hybrid`
1708
1594
 
1709
- Combines both — the `text` is injected as additional context **and** the user's questions are also grounded via RAG. Good for museum exhibits, guided experiences, or any scenario with rich metadata alongside large document sets.
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.
1710
1596
 
1711
1597
  ```typescript
1712
1598
  return {
@@ -1783,7 +1669,7 @@ ${reviews.map(r => `- "${r.text}" (${r.rating}/5)`).join('\n')}
1783
1669
  }
1784
1670
  ```
1785
1671
 
1786
- #### Equipment Manual App (RAG-only)
1672
+ #### Equipment Manual App (knowledge only)
1787
1673
 
1788
1674
  ```typescript
1789
1675
  async function gatherAIContent(): Promise<AIContentResponse> {
@@ -1819,6 +1705,7 @@ If your app doesn't implement either of the above, the framework extracts `inner
1819
1705
  ## Related Documentation
1820
1706
 
1821
1707
  - [API Summary](./API_SUMMARY.md) - Complete API reference
1708
+ - [Knowledge search](./knowledge.md) - Knowledge sets, sources and search
1822
1709
  - [Widgets](./widgets.md) - Embedding SmartLinks components
1823
1710
  - [Realtime](./realtime.md) - Realtime data updates
1824
1711
  - [iframe Responder](./iframe-responder.md) - iframe integration