@yourgpt/llm-sdk 2.1.4-alpha.1 → 2.1.4-alpha.3
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/dist/adapters/index.d.mts +4 -2
- package/dist/adapters/index.d.ts +4 -2
- package/dist/base-5n-UuPfS.d.mts +768 -0
- package/dist/base-Di31iy_8.d.ts +768 -0
- package/dist/fallback/index.d.mts +96 -0
- package/dist/fallback/index.d.ts +96 -0
- package/dist/fallback/index.js +284 -0
- package/dist/fallback/index.mjs +280 -0
- package/dist/index.d.mts +62 -3
- package/dist/index.d.ts +62 -3
- package/dist/index.js +117 -2
- package/dist/index.mjs +116 -3
- package/dist/providers/anthropic/index.d.mts +3 -1
- package/dist/providers/anthropic/index.d.ts +3 -1
- package/dist/providers/azure/index.d.mts +3 -1
- package/dist/providers/azure/index.d.ts +3 -1
- package/dist/providers/google/index.d.mts +3 -1
- package/dist/providers/google/index.d.ts +3 -1
- package/dist/providers/ollama/index.d.mts +4 -2
- package/dist/providers/ollama/index.d.ts +4 -2
- package/dist/providers/openai/index.d.mts +3 -1
- package/dist/providers/openai/index.d.ts +3 -1
- package/dist/providers/openrouter/index.d.mts +3 -1
- package/dist/providers/openrouter/index.d.ts +3 -1
- package/dist/providers/xai/index.d.mts +3 -1
- package/dist/providers/xai/index.d.ts +3 -1
- package/dist/types-BQl1suAv.d.mts +212 -0
- package/dist/types-C0vLXzuw.d.ts +355 -0
- package/dist/types-CNL8ZRne.d.ts +212 -0
- package/dist/types-CR8mi9I0.d.mts +417 -0
- package/dist/types-CR8mi9I0.d.ts +417 -0
- package/dist/types-VDgiUvH2.d.mts +355 -0
- package/dist/yourgpt/index.d.mts +77 -0
- package/dist/yourgpt/index.d.ts +77 -0
- package/dist/yourgpt/index.js +167 -0
- package/dist/yourgpt/index.mjs +164 -0
- package/package.json +12 -1
- package/dist/adapters/index.js.map +0 -1
- package/dist/adapters/index.mjs.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/index.mjs.map +0 -1
- package/dist/providers/anthropic/index.js.map +0 -1
- package/dist/providers/anthropic/index.mjs.map +0 -1
- package/dist/providers/azure/index.js.map +0 -1
- package/dist/providers/azure/index.mjs.map +0 -1
- package/dist/providers/google/index.js.map +0 -1
- package/dist/providers/google/index.mjs.map +0 -1
- package/dist/providers/ollama/index.js.map +0 -1
- package/dist/providers/ollama/index.mjs.map +0 -1
- package/dist/providers/openai/index.js.map +0 -1
- package/dist/providers/openai/index.mjs.map +0 -1
- package/dist/providers/openrouter/index.js.map +0 -1
- package/dist/providers/openrouter/index.mjs.map +0 -1
- package/dist/providers/xai/index.js.map +0 -1
- package/dist/providers/xai/index.mjs.map +0 -1
- package/dist/types-COAOEe_y.d.mts +0 -1460
- package/dist/types-COAOEe_y.d.ts +0 -1460
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
import { L as LLMAdapter } from './base-Di31iy_8.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Fallback Chain & Routing Strategy Types
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Pluggable state store for routing strategies.
|
|
9
|
+
*
|
|
10
|
+
* Round-robin and other stateful strategies use this to persist
|
|
11
|
+
* which model was last used. The default implementation is in-memory.
|
|
12
|
+
*
|
|
13
|
+
* For multi-instance or serverless deployments, plug in your own:
|
|
14
|
+
* Redis, Upstash, Cloudflare KV, DynamoDB, etc.
|
|
15
|
+
*
|
|
16
|
+
* @example
|
|
17
|
+
* ```typescript
|
|
18
|
+
* // Redis-backed store (example — bring your own client)
|
|
19
|
+
* const redisStore: RoutingStore = {
|
|
20
|
+
* async get(key) {
|
|
21
|
+
* const val = await redis.get(key);
|
|
22
|
+
* return val ? Number(val) : undefined;
|
|
23
|
+
* },
|
|
24
|
+
* async set(key, value) {
|
|
25
|
+
* await redis.set(key, value);
|
|
26
|
+
* },
|
|
27
|
+
* };
|
|
28
|
+
* ```
|
|
29
|
+
*/
|
|
30
|
+
interface RoutingStore {
|
|
31
|
+
/** Get the stored value for a key */
|
|
32
|
+
get(key: string): Promise<number | undefined>;
|
|
33
|
+
/** Set the stored value for a key */
|
|
34
|
+
set(key: string, value: number): Promise<void>;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* A single failed model in the fallback chain (after all retries exhausted)
|
|
38
|
+
*/
|
|
39
|
+
interface FallbackFailure {
|
|
40
|
+
/** Model ID that failed */
|
|
41
|
+
model: string;
|
|
42
|
+
/** Provider name */
|
|
43
|
+
provider: string;
|
|
44
|
+
/** The last error from this model */
|
|
45
|
+
error: Error;
|
|
46
|
+
/** Which model in the chain this was (1-based) */
|
|
47
|
+
attempt: number;
|
|
48
|
+
/** How many times this model was retried before giving up */
|
|
49
|
+
retriesAttempted: number;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Passed to the onFallback callback when a model is abandoned and the next one is tried
|
|
53
|
+
*/
|
|
54
|
+
interface FallbackInfo {
|
|
55
|
+
/** Model that just failed (after all its retries) */
|
|
56
|
+
attemptedModel: string;
|
|
57
|
+
/** Model that will be tried next */
|
|
58
|
+
nextModel: string;
|
|
59
|
+
/** The last error from the failed model */
|
|
60
|
+
error: Error;
|
|
61
|
+
/** Which model in the chain this was (1-based) */
|
|
62
|
+
attempt: number;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Passed to the onRetry callback on each per-model retry attempt
|
|
66
|
+
*/
|
|
67
|
+
interface RetryInfo {
|
|
68
|
+
/** Model being retried */
|
|
69
|
+
model: string;
|
|
70
|
+
/** Provider name */
|
|
71
|
+
provider: string;
|
|
72
|
+
/** The error that triggered this retry */
|
|
73
|
+
error: Error;
|
|
74
|
+
/** Which retry attempt this is (1-based: 1 = first retry after initial failure) */
|
|
75
|
+
retryAttempt: number;
|
|
76
|
+
/** Total retries configured for this chain */
|
|
77
|
+
maxRetries: number;
|
|
78
|
+
/** How long (ms) we will wait before retrying */
|
|
79
|
+
delayMs: number;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* How the chain decides which model to try first.
|
|
83
|
+
*
|
|
84
|
+
* - `priority` — always try models in defined order (default)
|
|
85
|
+
* - `round-robin` — rotate starting model evenly across calls
|
|
86
|
+
*/
|
|
87
|
+
type RoutingStrategy = "priority" | "round-robin";
|
|
88
|
+
/**
|
|
89
|
+
* Backoff strategy between per-model retries.
|
|
90
|
+
*
|
|
91
|
+
* - `exponential` — delay doubles on each retry: 500ms → 1000ms → 2000ms (default)
|
|
92
|
+
* - `fixed` — same delay every retry: 500ms → 500ms → 500ms
|
|
93
|
+
*/
|
|
94
|
+
type RetryBackoff = "exponential" | "fixed";
|
|
95
|
+
/**
|
|
96
|
+
* Configuration for createFallbackChain()
|
|
97
|
+
*/
|
|
98
|
+
interface FallbackChainConfig {
|
|
99
|
+
/**
|
|
100
|
+
* Ordered list of adapters to try.
|
|
101
|
+
* On failure, the chain moves to the next adapter in this list.
|
|
102
|
+
*
|
|
103
|
+
* @example
|
|
104
|
+
* ```typescript
|
|
105
|
+
* import { createOpenAI } from '@yourgpt/llm-sdk/openai';
|
|
106
|
+
* import { createAnthropic } from '@yourgpt/llm-sdk/anthropic';
|
|
107
|
+
*
|
|
108
|
+
* const openai = createOpenAI({ apiKey: '...' });
|
|
109
|
+
* const anthropic = createAnthropic({ apiKey: '...' });
|
|
110
|
+
*
|
|
111
|
+
* const chain = createFallbackChain({
|
|
112
|
+
* models: [
|
|
113
|
+
* openai.languageModel('gpt-4o'),
|
|
114
|
+
* anthropic.languageModel('claude-3-5-sonnet-20241022'),
|
|
115
|
+
* ],
|
|
116
|
+
* });
|
|
117
|
+
* ```
|
|
118
|
+
*/
|
|
119
|
+
models: LLMAdapter[];
|
|
120
|
+
/**
|
|
121
|
+
* Routing strategy controlling which model is tried first.
|
|
122
|
+
* @default 'priority'
|
|
123
|
+
*/
|
|
124
|
+
strategy?: RoutingStrategy;
|
|
125
|
+
/**
|
|
126
|
+
* State store for strategies that require persistence (e.g., round-robin).
|
|
127
|
+
* Defaults to an in-memory store (MemoryRoutingStore).
|
|
128
|
+
*
|
|
129
|
+
* Replace with a shared store (Redis, Upstash, etc.) for multi-instance
|
|
130
|
+
* or serverless deployments where round-robin state must be shared.
|
|
131
|
+
*/
|
|
132
|
+
store?: RoutingStore;
|
|
133
|
+
/**
|
|
134
|
+
* Number of times to retry the same model before moving to the next one.
|
|
135
|
+
*
|
|
136
|
+
* LiteLLM equivalent: `num_retries`
|
|
137
|
+
*
|
|
138
|
+
* @default 0 (no retries — fail immediately and move to next model)
|
|
139
|
+
*
|
|
140
|
+
* @example
|
|
141
|
+
* ```typescript
|
|
142
|
+
* // Try each model up to 3 times before falling back
|
|
143
|
+
* createFallbackChain({ models: [...], retries: 3 })
|
|
144
|
+
* ```
|
|
145
|
+
*/
|
|
146
|
+
retries?: number;
|
|
147
|
+
/**
|
|
148
|
+
* Base delay in milliseconds between per-model retries.
|
|
149
|
+
*
|
|
150
|
+
* With `retryBackoff: 'exponential'` (default):
|
|
151
|
+
* retry 1 → retryDelay ms
|
|
152
|
+
* retry 2 → retryDelay * 2 ms
|
|
153
|
+
* retry 3 → retryDelay * 4 ms
|
|
154
|
+
*
|
|
155
|
+
* With `retryBackoff: 'fixed'`:
|
|
156
|
+
* every retry → retryDelay ms
|
|
157
|
+
*
|
|
158
|
+
* @default 500
|
|
159
|
+
*/
|
|
160
|
+
retryDelay?: number;
|
|
161
|
+
/**
|
|
162
|
+
* Backoff strategy between per-model retries.
|
|
163
|
+
* @default 'exponential'
|
|
164
|
+
*/
|
|
165
|
+
retryBackoff?: RetryBackoff;
|
|
166
|
+
/**
|
|
167
|
+
* Called on each per-model retry attempt (before the delay).
|
|
168
|
+
* Use for logging, metrics, or alerting per retry.
|
|
169
|
+
*
|
|
170
|
+
* @example
|
|
171
|
+
* ```typescript
|
|
172
|
+
* onRetry: ({ model, retryAttempt, maxRetries, delayMs, error }) => {
|
|
173
|
+
* console.warn(`[retry] ${model} attempt ${retryAttempt}/${maxRetries} — waiting ${delayMs}ms | ${error.message}`);
|
|
174
|
+
* }
|
|
175
|
+
* ```
|
|
176
|
+
*/
|
|
177
|
+
onRetry?: (info: RetryInfo) => void;
|
|
178
|
+
/**
|
|
179
|
+
* Called each time a model is abandoned and the next one is tried.
|
|
180
|
+
* Use for logging, metrics, or alerting.
|
|
181
|
+
*
|
|
182
|
+
* @example
|
|
183
|
+
* ```typescript
|
|
184
|
+
* onFallback: ({ attemptedModel, nextModel, error, attempt }) => {
|
|
185
|
+
* console.warn(`[fallback] attempt ${attempt}: ${attemptedModel} failed → ${nextModel}`, error.message);
|
|
186
|
+
* }
|
|
187
|
+
* ```
|
|
188
|
+
*/
|
|
189
|
+
onFallback?: (info: FallbackInfo) => void;
|
|
190
|
+
/**
|
|
191
|
+
* Custom predicate to decide whether an error should trigger a fallback.
|
|
192
|
+
*
|
|
193
|
+
* By default, the following trigger fallback:
|
|
194
|
+
* - HTTP 5xx server errors
|
|
195
|
+
* - HTTP 429 rate limit errors
|
|
196
|
+
* - Network timeouts and connection failures
|
|
197
|
+
*
|
|
198
|
+
* The following do NOT trigger fallback by default:
|
|
199
|
+
* - HTTP 4xx client errors (bad request, invalid API key, etc.)
|
|
200
|
+
*
|
|
201
|
+
* Override this to extend or restrict fallback behavior.
|
|
202
|
+
*
|
|
203
|
+
* @example
|
|
204
|
+
* ```typescript
|
|
205
|
+
* // Also fall back on any error
|
|
206
|
+
* retryableErrors: () => true,
|
|
207
|
+
* ```
|
|
208
|
+
*/
|
|
209
|
+
retryableErrors?: (error: unknown) => boolean;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
export type { FallbackChainConfig as F, RoutingStore as R, RoutingStrategy as a, RetryBackoff as b, FallbackFailure as c, FallbackInfo as d, RetryInfo as e };
|
|
@@ -0,0 +1,417 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Core Types for @yourgpt/llm-sdk
|
|
5
|
+
*
|
|
6
|
+
* Modern, instance-based types following Vercel AI SDK patterns.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* A language model instance that can generate text.
|
|
11
|
+
* This is what provider functions like `openai('gpt-4o')` return.
|
|
12
|
+
*/
|
|
13
|
+
interface LanguageModel {
|
|
14
|
+
/** Provider identifier (e.g., 'openai', 'anthropic') */
|
|
15
|
+
readonly provider: string;
|
|
16
|
+
/** Model identifier (e.g., 'gpt-4o', 'claude-3-5-sonnet') */
|
|
17
|
+
readonly modelId: string;
|
|
18
|
+
/** Model capabilities for feature detection */
|
|
19
|
+
readonly capabilities: ModelCapabilities;
|
|
20
|
+
/**
|
|
21
|
+
* Generate a complete response (non-streaming)
|
|
22
|
+
* Used internally by generateText()
|
|
23
|
+
*/
|
|
24
|
+
doGenerate(params: DoGenerateParams): Promise<DoGenerateResult>;
|
|
25
|
+
/**
|
|
26
|
+
* Stream a response
|
|
27
|
+
* Used internally by streamText()
|
|
28
|
+
*/
|
|
29
|
+
doStream(params: DoGenerateParams): AsyncGenerator<StreamChunk>;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Model capabilities for UI feature flags
|
|
33
|
+
*/
|
|
34
|
+
interface ModelCapabilities {
|
|
35
|
+
/** Supports image inputs */
|
|
36
|
+
supportsVision: boolean;
|
|
37
|
+
/** Supports tool/function calling */
|
|
38
|
+
supportsTools: boolean;
|
|
39
|
+
/** Supports streaming responses */
|
|
40
|
+
supportsStreaming: boolean;
|
|
41
|
+
/** Supports JSON mode / structured output */
|
|
42
|
+
supportsJsonMode: boolean;
|
|
43
|
+
/** Supports extended thinking (Claude) */
|
|
44
|
+
supportsThinking: boolean;
|
|
45
|
+
/** Supports PDF document inputs */
|
|
46
|
+
supportsPDF: boolean;
|
|
47
|
+
/** Maximum context tokens */
|
|
48
|
+
maxTokens: number;
|
|
49
|
+
/** Supported image MIME types */
|
|
50
|
+
supportedImageTypes: string[];
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Default capabilities for unknown models
|
|
54
|
+
*/
|
|
55
|
+
declare const DEFAULT_CAPABILITIES: ModelCapabilities;
|
|
56
|
+
/**
|
|
57
|
+
* Core message types for LLM conversations
|
|
58
|
+
*/
|
|
59
|
+
type CoreMessage = SystemMessage | UserMessage | AssistantMessage | ToolMessage;
|
|
60
|
+
interface SystemMessage {
|
|
61
|
+
role: "system";
|
|
62
|
+
content: string;
|
|
63
|
+
}
|
|
64
|
+
interface UserMessage {
|
|
65
|
+
role: "user";
|
|
66
|
+
content: string | UserContentPart[];
|
|
67
|
+
}
|
|
68
|
+
interface AssistantMessage {
|
|
69
|
+
role: "assistant";
|
|
70
|
+
content: string | null;
|
|
71
|
+
toolCalls?: ToolCall[];
|
|
72
|
+
}
|
|
73
|
+
interface ToolMessage {
|
|
74
|
+
role: "tool";
|
|
75
|
+
toolCallId: string;
|
|
76
|
+
content: string;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Content parts for multimodal user messages
|
|
80
|
+
*/
|
|
81
|
+
type UserContentPart = TextPart | ImagePart | FilePart;
|
|
82
|
+
interface TextPart {
|
|
83
|
+
type: "text";
|
|
84
|
+
text: string;
|
|
85
|
+
}
|
|
86
|
+
interface ImagePart {
|
|
87
|
+
type: "image";
|
|
88
|
+
/** Base64 data or URL */
|
|
89
|
+
image: string | Uint8Array;
|
|
90
|
+
/** MIME type (e.g., 'image/png') */
|
|
91
|
+
mimeType?: string;
|
|
92
|
+
}
|
|
93
|
+
interface FilePart {
|
|
94
|
+
type: "file";
|
|
95
|
+
/** Base64 data or URL */
|
|
96
|
+
data: string;
|
|
97
|
+
/** MIME type (e.g., 'application/pdf') */
|
|
98
|
+
mimeType: string;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Tool definition with Zod schema support
|
|
102
|
+
*/
|
|
103
|
+
interface Tool<TParams = unknown, TResult = unknown> {
|
|
104
|
+
/** Tool description for the LLM */
|
|
105
|
+
description: string;
|
|
106
|
+
/** Zod schema for parameters */
|
|
107
|
+
parameters: z.ZodType<TParams>;
|
|
108
|
+
/** Execute function */
|
|
109
|
+
execute: (params: TParams, context: ToolContext) => Promise<TResult>;
|
|
110
|
+
/**
|
|
111
|
+
* Hide this tool's execution from the chat UI.
|
|
112
|
+
* When true, tool calls and results won't be displayed to the user,
|
|
113
|
+
* but the tool will still execute normally.
|
|
114
|
+
* @default false
|
|
115
|
+
*/
|
|
116
|
+
hidden?: boolean;
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Context passed to tool execute function
|
|
120
|
+
*/
|
|
121
|
+
interface ToolContext {
|
|
122
|
+
/** Abort signal for cancellation */
|
|
123
|
+
abortSignal?: AbortSignal;
|
|
124
|
+
/** Unique tool call ID */
|
|
125
|
+
toolCallId: string;
|
|
126
|
+
/** Optional: messages in conversation */
|
|
127
|
+
messages?: CoreMessage[];
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Tool call from LLM response
|
|
131
|
+
*/
|
|
132
|
+
interface ToolCall {
|
|
133
|
+
/** Unique ID for this tool call */
|
|
134
|
+
id: string;
|
|
135
|
+
/** Tool name */
|
|
136
|
+
name: string;
|
|
137
|
+
/** Parsed arguments */
|
|
138
|
+
args: Record<string, unknown>;
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* Tool execution result
|
|
142
|
+
*/
|
|
143
|
+
interface ToolResult {
|
|
144
|
+
/** Tool call ID this result corresponds to */
|
|
145
|
+
toolCallId: string;
|
|
146
|
+
/** Result data (will be JSON stringified for LLM) */
|
|
147
|
+
result: unknown;
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Parameters for model.doGenerate() and model.doStream()
|
|
151
|
+
*/
|
|
152
|
+
interface DoGenerateParams {
|
|
153
|
+
/** Messages to send to LLM */
|
|
154
|
+
messages: CoreMessage[];
|
|
155
|
+
/** Tools available to the LLM (already formatted for provider) */
|
|
156
|
+
tools?: unknown[];
|
|
157
|
+
/** Temperature (0-2) */
|
|
158
|
+
temperature?: number;
|
|
159
|
+
/** Maximum tokens to generate */
|
|
160
|
+
maxTokens?: number;
|
|
161
|
+
/** Abort signal */
|
|
162
|
+
signal?: AbortSignal;
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Result from model.doGenerate()
|
|
166
|
+
*/
|
|
167
|
+
interface DoGenerateResult {
|
|
168
|
+
/** Generated text content */
|
|
169
|
+
text: string;
|
|
170
|
+
/** Tool calls requested by the LLM */
|
|
171
|
+
toolCalls: ToolCall[];
|
|
172
|
+
/** Why generation stopped */
|
|
173
|
+
finishReason: FinishReason;
|
|
174
|
+
/** Token usage */
|
|
175
|
+
usage: TokenUsage;
|
|
176
|
+
/** Raw provider response (for debugging) */
|
|
177
|
+
rawResponse?: unknown;
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Finish reason for generation
|
|
181
|
+
*/
|
|
182
|
+
type FinishReason = "stop" | "length" | "tool-calls" | "content-filter" | "error" | "unknown";
|
|
183
|
+
/**
|
|
184
|
+
* Token usage statistics
|
|
185
|
+
*/
|
|
186
|
+
interface TokenUsage {
|
|
187
|
+
promptTokens: number;
|
|
188
|
+
completionTokens: number;
|
|
189
|
+
totalTokens: number;
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* Stream chunk from model.doStream()
|
|
193
|
+
*/
|
|
194
|
+
type StreamChunk = TextDeltaChunk | ToolCallChunk | ToolResultChunk | FinishChunk | ErrorChunk;
|
|
195
|
+
interface TextDeltaChunk {
|
|
196
|
+
type: "text-delta";
|
|
197
|
+
text: string;
|
|
198
|
+
}
|
|
199
|
+
interface ToolCallChunk {
|
|
200
|
+
type: "tool-call";
|
|
201
|
+
toolCall: ToolCall;
|
|
202
|
+
}
|
|
203
|
+
interface ToolResultChunk {
|
|
204
|
+
type: "tool-result";
|
|
205
|
+
toolCallId: string;
|
|
206
|
+
result: unknown;
|
|
207
|
+
}
|
|
208
|
+
interface FinishChunk {
|
|
209
|
+
type: "finish";
|
|
210
|
+
finishReason: FinishReason;
|
|
211
|
+
usage?: TokenUsage;
|
|
212
|
+
}
|
|
213
|
+
interface ErrorChunk {
|
|
214
|
+
type: "error";
|
|
215
|
+
error: Error;
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* Parameters for generateText()
|
|
219
|
+
*/
|
|
220
|
+
interface GenerateTextParams {
|
|
221
|
+
/** Language model to use */
|
|
222
|
+
model: LanguageModel;
|
|
223
|
+
/** Simple prompt (converted to user message) */
|
|
224
|
+
prompt?: string;
|
|
225
|
+
/** System prompt */
|
|
226
|
+
system?: string;
|
|
227
|
+
/** Full message history */
|
|
228
|
+
messages?: CoreMessage[];
|
|
229
|
+
/** Tools available to the LLM */
|
|
230
|
+
tools?: Record<string, Tool>;
|
|
231
|
+
/** Maximum agentic steps (tool call loops) */
|
|
232
|
+
maxSteps?: number;
|
|
233
|
+
/** Temperature (0-2) */
|
|
234
|
+
temperature?: number;
|
|
235
|
+
/** Maximum tokens to generate */
|
|
236
|
+
maxTokens?: number;
|
|
237
|
+
/** Abort signal */
|
|
238
|
+
signal?: AbortSignal;
|
|
239
|
+
}
|
|
240
|
+
/**
|
|
241
|
+
* Result from generateText()
|
|
242
|
+
*/
|
|
243
|
+
interface GenerateTextResult {
|
|
244
|
+
/** Final text output */
|
|
245
|
+
text: string;
|
|
246
|
+
/** Token usage */
|
|
247
|
+
usage: TokenUsage;
|
|
248
|
+
/** Why generation stopped */
|
|
249
|
+
finishReason: FinishReason;
|
|
250
|
+
/** All steps taken (for agentic workflows) */
|
|
251
|
+
steps: GenerateStep[];
|
|
252
|
+
/** All tool calls made across all steps */
|
|
253
|
+
toolCalls: ToolCall[];
|
|
254
|
+
/** All tool results across all steps */
|
|
255
|
+
toolResults: ToolResult[];
|
|
256
|
+
/** Final message list including tool interactions */
|
|
257
|
+
response: {
|
|
258
|
+
messages: CoreMessage[];
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
/**
|
|
262
|
+
* A single step in the generation process
|
|
263
|
+
*/
|
|
264
|
+
interface GenerateStep {
|
|
265
|
+
/** Text generated in this step */
|
|
266
|
+
text: string;
|
|
267
|
+
/** Tool calls made in this step */
|
|
268
|
+
toolCalls: ToolCall[];
|
|
269
|
+
/** Tool results from this step */
|
|
270
|
+
toolResults: ToolResult[];
|
|
271
|
+
/** Finish reason for this step */
|
|
272
|
+
finishReason: FinishReason;
|
|
273
|
+
/** Token usage for this step */
|
|
274
|
+
usage: TokenUsage;
|
|
275
|
+
}
|
|
276
|
+
/**
|
|
277
|
+
* Parameters for streamText() - same as generateText
|
|
278
|
+
*/
|
|
279
|
+
type StreamTextParams = GenerateTextParams;
|
|
280
|
+
/**
|
|
281
|
+
* Result from streamText()
|
|
282
|
+
*/
|
|
283
|
+
interface StreamTextResult {
|
|
284
|
+
/** Async iterable of text chunks only */
|
|
285
|
+
textStream: AsyncIterable<string>;
|
|
286
|
+
/** Async iterable of all stream parts */
|
|
287
|
+
fullStream: AsyncIterable<StreamPart>;
|
|
288
|
+
/** Promise that resolves to full text when complete */
|
|
289
|
+
readonly text: Promise<string>;
|
|
290
|
+
/** Promise that resolves to usage when complete */
|
|
291
|
+
readonly usage: Promise<TokenUsage>;
|
|
292
|
+
/** Promise that resolves to finish reason when complete */
|
|
293
|
+
readonly finishReason: Promise<FinishReason>;
|
|
294
|
+
/** Convert to plain text streaming Response */
|
|
295
|
+
toTextStreamResponse(options?: ResponseOptions): Response;
|
|
296
|
+
/** Convert to data stream Response (SSE with tool calls) */
|
|
297
|
+
toDataStreamResponse(options?: ResponseOptions): Response;
|
|
298
|
+
}
|
|
299
|
+
/**
|
|
300
|
+
* Stream part for fullStream
|
|
301
|
+
*/
|
|
302
|
+
type StreamPart = {
|
|
303
|
+
type: "text-delta";
|
|
304
|
+
text: string;
|
|
305
|
+
} | {
|
|
306
|
+
type: "tool-call-start";
|
|
307
|
+
toolCallId: string;
|
|
308
|
+
toolName: string;
|
|
309
|
+
} | {
|
|
310
|
+
type: "tool-call-delta";
|
|
311
|
+
toolCallId: string;
|
|
312
|
+
argsText: string;
|
|
313
|
+
} | {
|
|
314
|
+
type: "tool-call-complete";
|
|
315
|
+
toolCall: ToolCall;
|
|
316
|
+
} | {
|
|
317
|
+
type: "tool-result";
|
|
318
|
+
toolCallId: string;
|
|
319
|
+
result: unknown;
|
|
320
|
+
} | {
|
|
321
|
+
type: "step-start";
|
|
322
|
+
step: number;
|
|
323
|
+
} | {
|
|
324
|
+
type: "step-finish";
|
|
325
|
+
step: number;
|
|
326
|
+
finishReason: FinishReason;
|
|
327
|
+
} | {
|
|
328
|
+
type: "finish";
|
|
329
|
+
finishReason: FinishReason;
|
|
330
|
+
usage: TokenUsage;
|
|
331
|
+
} | {
|
|
332
|
+
type: "error";
|
|
333
|
+
error: Error;
|
|
334
|
+
};
|
|
335
|
+
/**
|
|
336
|
+
* Options for Response helpers
|
|
337
|
+
*/
|
|
338
|
+
interface ResponseOptions {
|
|
339
|
+
/** Additional headers */
|
|
340
|
+
headers?: Record<string, string>;
|
|
341
|
+
/** Response status (default: 200) */
|
|
342
|
+
status?: number;
|
|
343
|
+
}
|
|
344
|
+
/**
|
|
345
|
+
* Message format for storage adapters.
|
|
346
|
+
* Intentionally simpler than LLM-specific formats — adapters convert as needed.
|
|
347
|
+
*/
|
|
348
|
+
interface StorageMessage {
|
|
349
|
+
role: "user" | "assistant" | "system" | "tool";
|
|
350
|
+
content: string;
|
|
351
|
+
toolCalls?: unknown[];
|
|
352
|
+
toolCallId?: string;
|
|
353
|
+
/** Content type for the message — determines how it's stored in the backend */
|
|
354
|
+
contentType?: "text" | "image" | "file";
|
|
355
|
+
/** URL for image/file attachments */
|
|
356
|
+
url?: string;
|
|
357
|
+
metadata?: Record<string, unknown>;
|
|
358
|
+
}
|
|
359
|
+
/**
|
|
360
|
+
* Generic storage adapter interface for session + message persistence.
|
|
361
|
+
*
|
|
362
|
+
* `createYourGPT()` is the default implementation for YourGPT platform.
|
|
363
|
+
* Third-party developers can implement this interface for custom backends.
|
|
364
|
+
*
|
|
365
|
+
* @example
|
|
366
|
+
* ```ts
|
|
367
|
+
* import { createRuntime } from '@yourgpt/llm-sdk'
|
|
368
|
+
* import { createYourGPT } from '@yourgpt/llm-sdk/yourgpt'
|
|
369
|
+
*
|
|
370
|
+
* const runtime = createRuntime({
|
|
371
|
+
* provider: anthropic,
|
|
372
|
+
* model: 'claude-haiku-4-5',
|
|
373
|
+
* storage: createYourGPT({ apiKey, widgetUid }),
|
|
374
|
+
* })
|
|
375
|
+
* // runtime.chat() and runtime.stream() now auto-persist messages
|
|
376
|
+
* ```
|
|
377
|
+
*/
|
|
378
|
+
interface StorageAdapter {
|
|
379
|
+
/** Create a new session. Returns session ID to use as threadId. */
|
|
380
|
+
createSession(data?: {
|
|
381
|
+
title?: string;
|
|
382
|
+
metadata?: Record<string, unknown>;
|
|
383
|
+
}): Promise<{
|
|
384
|
+
id: string;
|
|
385
|
+
}>;
|
|
386
|
+
/** Append messages to a session (called sequentially — input before output). */
|
|
387
|
+
saveMessages(sessionId: string, messages: StorageMessage[]): Promise<void>;
|
|
388
|
+
/** List sessions (optional — used for thread picker sync in future). */
|
|
389
|
+
getSessions?(): Promise<{
|
|
390
|
+
id: string;
|
|
391
|
+
title?: string;
|
|
392
|
+
updatedAt?: Date;
|
|
393
|
+
}[]>;
|
|
394
|
+
/** Get messages for a session (optional — used for thread restore in future). */
|
|
395
|
+
getMessages?(sessionId: string): Promise<StorageMessage[]>;
|
|
396
|
+
/**
|
|
397
|
+
* Upload a file to storage. Returns a URL the LLM can reference.
|
|
398
|
+
* When present, the server exposes a /upload endpoint and the client
|
|
399
|
+
* uses it instead of embedding base64 in the message body.
|
|
400
|
+
*/
|
|
401
|
+
uploadFile?(file: StorageFile): Promise<{
|
|
402
|
+
url: string;
|
|
403
|
+
}>;
|
|
404
|
+
}
|
|
405
|
+
/**
|
|
406
|
+
* File data for upload via StorageAdapter.uploadFile()
|
|
407
|
+
*/
|
|
408
|
+
interface StorageFile {
|
|
409
|
+
/** Base64-encoded file data (with or without data URI prefix) */
|
|
410
|
+
data: string;
|
|
411
|
+
/** MIME type (e.g., "image/png", "application/pdf") */
|
|
412
|
+
mimeType: string;
|
|
413
|
+
/** Original filename */
|
|
414
|
+
filename?: string;
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
export { type AssistantMessage as A, type CoreMessage as C, type DoGenerateParams as D, type ErrorChunk as E, type FilePart as F, type GenerateTextParams as G, type ImagePart as I, type LanguageModel as L, type ModelCapabilities as M, type ResponseOptions as R, type StreamTextParams as S, type ToolContext as T, type UserMessage as U, type GenerateTextResult as a, type StreamTextResult as b, type Tool as c, type StorageAdapter as d, type StorageMessage as e, type DoGenerateResult as f, type SystemMessage as g, type ToolMessage as h, type UserContentPart as i, type TextPart as j, type ToolCall as k, type ToolResult as l, type GenerateStep as m, type StreamPart as n, type StreamChunk as o, type TextDeltaChunk as p, type ToolCallChunk as q, type ToolResultChunk as r, type FinishChunk as s, type TokenUsage as t, type FinishReason as u, type StorageFile as v, DEFAULT_CAPABILITIES as w };
|