@webknox/ai-sdk 0.0.0-stage → 0.1.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 skycraft GmbH
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,50 @@
1
- # Temporary Holding Version
1
+ # @webknox/ai-sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ WebKnox for the [AI SDK](https://ai-sdk.dev). One tool, `askWebknox`, answers everyday questions with a sourced card your app can show: weather, nutrition, recipes, comparisons with photos, translations, maths, media and [more](https://webknox.com/docs/cards).
4
+
5
+ ```bash
6
+ npm install @webknox/ai-sdk
7
+ ```
8
+
9
+ Set `WEBKNOX_API_KEY`, with a key from [the console](https://webknox.com/console), and add the tool:
10
+
11
+ ```js
12
+ import {generateText, isStepCount} from 'ai';
13
+ import {askWebknox} from '@webknox/ai-sdk';
14
+
15
+ const {text, steps} = await generateText({
16
+ model: 'openai/gpt-5-mini',
17
+ prompt: 'Do I need an umbrella in Dresden tomorrow?',
18
+ tools: {askWebknox: askWebknox()},
19
+ stopWhen: isStepCount(3),
20
+ });
21
+
22
+ console.log(text);
23
+ ```
24
+
25
+ ## Showing the card
26
+
27
+ The tool's result is the whole [answer](https://webknox.com/docs/reference). Hand it to [`<webknox-answer>`](https://webknox.com/docs/rendering) from `@webknox/elements`:
28
+
29
+ ```js
30
+ const element = document.createElement('webknox-answer');
31
+ element.answer = toolResult.output;
32
+ ```
33
+
34
+ The model reads only the answer's text and sources, and is told the user already sees the card. That keeps a large card out of its context, and it won't read the card back. [The Next.js chat](https://github.com/webknox/webknox-examples/tree/main/examples/nextjs-chat) shows the whole loop.
35
+
36
+ ## Options
37
+
38
+ ```js
39
+ askWebknox({
40
+ locale: 'de', // en (default), de, fr, es, pt, it
41
+ context: {timezone: 'Europe/Berlin', units: 'metric'},
42
+ accept: ['weather.forecast', 'nutrition.facts'], // card types your app can show
43
+ });
44
+ ```
45
+
46
+ `apiKey`, `baseUrl`, `render` (hosted embeds and images, on Pro and Scale) and `fetch` work the same way. A question WebKnox can't answer comes back with `matched: false`, and the model answers it itself. A refused request throws a `WebKnoxError` with `status`, `code` and `retryAfterS`.
47
+
48
+ ## License
49
+
50
+ MIT
package/package.json CHANGED
@@ -1,6 +1,39 @@
1
1
  {
2
2
  "name": "@webknox/ai-sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "WebKnox for the AI SDK: a tool that answers everyday questions with sourced UI cards.",
5
+ "keywords": ["webknox", "ai-sdk", "vercel-ai-sdk", "tool", "generative-ui", "cards"],
6
+ "homepage": "https://webknox.com/docs/ai-sdk",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/webknox/webknox-examples.git",
10
+ "directory": "packages/ai-sdk"
11
+ },
12
+ "bugs": {
13
+ "email": "hello@webknox.com"
14
+ },
15
+ "license": "MIT",
16
+ "type": "module",
17
+ "exports": {
18
+ ".": {
19
+ "types": "./src/index.d.ts",
20
+ "default": "./src/index.js"
21
+ }
22
+ },
23
+ "types": "./src/index.d.ts",
24
+ "files": ["src", "README.md", "LICENSE"],
25
+ "scripts": {
26
+ "test": "node --test \"test/**/*.test.js\""
27
+ },
28
+ "peerDependencies": {
29
+ "ai": "^6.0.0 || ^7.0.0",
30
+ "zod": "^4.0.0"
31
+ },
32
+ "devDependencies": {
33
+ "ai": "^7.0.0",
34
+ "zod": "^4.0.0"
35
+ },
36
+ "publishConfig": {
37
+ "access": "public"
38
+ }
39
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,67 @@
1
+ import type {Tool} from 'ai';
2
+
3
+ /** Card types, `null` when the answer has none. New types can appear: see https://webknox.com/docs/cards */
4
+ export interface WebKnoxCard {
5
+ type: string;
6
+ version: number;
7
+ data: Record<string, unknown>;
8
+ }
9
+
10
+ export interface WebKnoxSource {
11
+ name: string;
12
+ url?: string;
13
+ license?: string;
14
+ }
15
+
16
+ /** An Answers API answer. New optional fields can appear: see https://webknox.com/docs/reference */
17
+ export interface WebKnoxAnswer {
18
+ v: number;
19
+ id: string;
20
+ matched: boolean;
21
+ reason?: string;
22
+ locale: string;
23
+ skill?: string;
24
+ confidence?: number;
25
+ text: string | null;
26
+ speech?: string;
27
+ card: WebKnoxCard | null;
28
+ sources: WebKnoxSource[];
29
+ follow_ups: string[];
30
+ actions: Array<Record<string, unknown>>;
31
+ usage: {billable: boolean};
32
+ attribution?: {text: string; url: string};
33
+ render?: {embed_url?: string; image_url?: string; expires_at: string};
34
+ }
35
+
36
+ export interface AskWebknoxOptions {
37
+ /** Defaults to the WEBKNOX_API_KEY environment variable. */
38
+ apiKey?: string;
39
+ /** Defaults to https://api.webknox.com */
40
+ baseUrl?: string;
41
+ /** en (default), de, fr, es, pt or it: the language of the text and of localized card fields. */
42
+ locale?: string;
43
+ /** What to know about the user, for "today" and "here". */
44
+ context?: {
45
+ timezone?: string;
46
+ now?: string;
47
+ location?: {lat: number; lon: number};
48
+ units?: 'metric' | 'imperial';
49
+ };
50
+ /** Card types your client can render. Omit it to accept all. */
51
+ accept?: string[];
52
+ /** Hosted render URLs, on Pro and Scale. */
53
+ render?: {theme?: unknown; layout?: string; formats: Array<'embed' | 'image'>};
54
+ /** Defaults to the global fetch. */
55
+ fetch?: typeof globalThis.fetch;
56
+ }
57
+
58
+ export function askWebknox(options?: AskWebknoxOptions): Tool<{question: string}, WebKnoxAnswer>;
59
+
60
+ /** What the model reads of an answer: its text and sources, not the card. */
61
+ export function forModel(answer: WebKnoxAnswer): string;
62
+
63
+ export class WebKnoxError extends Error {
64
+ status?: number;
65
+ code?: string;
66
+ retryAfterS?: number;
67
+ }
package/src/index.js ADDED
@@ -0,0 +1,68 @@
1
+ import {tool} from 'ai';
2
+ import {z} from 'zod';
3
+
4
+ const API = 'https://api.webknox.com';
5
+
6
+ const DESCRIPTION = [
7
+ 'Answers everyday questions with a sourced card the user sees in the chat: weather, nutrition, recipes, recipe, game and',
8
+ 'artwork searches, comparisons with photos, translations, definitions, conversions, maths, time and timers, sunrise and',
9
+ 'sunset, videos, music and radio, pictures, jokes, quotes and this day in history.',
10
+ 'Call it when the user asks for one of these, and answer anything else yourself.',
11
+ ].join(' ');
12
+
13
+ const QUESTION = 'The question as one self-contained sentence in the user\'s language that names the place, food or things it is about; a follow-up such as "and tomorrow?" written out as a full question.';
14
+
15
+ /** A request the API refused: `code` is its error code, `retryAfterS` is set on a 429. */
16
+ export class WebKnoxError extends Error {
17
+ constructor(message, {status, code, retryAfterS} = {}) {
18
+ super(message);
19
+ this.name = 'WebKnoxError';
20
+ this.status = status;
21
+ this.code = code;
22
+ this.retryAfterS = retryAfterS;
23
+ }
24
+ }
25
+
26
+ /** What the model reads: the answer's text and sources. The card stays in the tool result, for the UI. */
27
+ export function forModel(answer) {
28
+ if (!answer.matched) return 'WebKnox has no answer for this. Answer from what you know.';
29
+ const sources = answer.sources.map((source) => source.name).filter(Boolean);
30
+ return [
31
+ answer.text,
32
+ sources.length ? `Sources: ${sources.join(', ')}.` : null,
33
+ answer.card ? 'The user already sees this as a card, so don\'t repeat it. Add only what the card doesn\'t say.' : null,
34
+ ].filter(Boolean).join('\n');
35
+ }
36
+
37
+ async function refused(response) {
38
+ const error = await response.json().then((body) => body?.error, () => null);
39
+ return new WebKnoxError(error?.message || `WebKnox answered ${response.status}`, {
40
+ status: response.status,
41
+ code: error?.code,
42
+ retryAfterS: error?.retry_after_s,
43
+ });
44
+ }
45
+
46
+ /**
47
+ * The WebKnox tool for `generateText`, `streamText` and agents. Its result is the Answers API's answer: hand it to
48
+ * `<webknox-answer>` to show the card.
49
+ */
50
+ export function askWebknox({apiKey, baseUrl = API, locale, context, accept, render, fetch: fetchImpl = globalThis.fetch} = {}) {
51
+ return tool({
52
+ description: DESCRIPTION,
53
+ inputSchema: z.object({question: z.string().trim().min(1).max(1000).describe(QUESTION)}),
54
+ execute: async ({question}, {abortSignal} = {}) => {
55
+ const key = apiKey ?? globalThis.process?.env?.WEBKNOX_API_KEY;
56
+ if (!key) throw new WebKnoxError('No API key: set WEBKNOX_API_KEY or pass apiKey. Get one at https://webknox.com/console');
57
+ const response = await fetchImpl(`${baseUrl}/v2/answers`, {
58
+ method: 'POST',
59
+ headers: {Authorization: `Bearer ${key}`, 'Content-Type': 'application/json'},
60
+ body: JSON.stringify({messages: [{role: 'user', content: question}], locale, context, accept, render}),
61
+ signal: abortSignal,
62
+ });
63
+ if (!response.ok) throw await refused(response);
64
+ return response.json();
65
+ },
66
+ toModelOutput: ({output}) => ({type: 'text', value: forModel(output)}),
67
+ });
68
+ }