@providerprotocol/ai 0.0.10 → 0.0.12

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 (64) hide show
  1. package/dist/index.d.ts +7 -1
  2. package/dist/index.js +37 -9
  3. package/dist/index.js.map +1 -1
  4. package/package.json +1 -10
  5. package/src/anthropic/index.ts +0 -3
  6. package/src/core/image.ts +0 -188
  7. package/src/core/llm.ts +0 -624
  8. package/src/core/provider.ts +0 -92
  9. package/src/google/index.ts +0 -3
  10. package/src/http/errors.ts +0 -112
  11. package/src/http/fetch.ts +0 -210
  12. package/src/http/index.ts +0 -31
  13. package/src/http/keys.ts +0 -136
  14. package/src/http/retry.ts +0 -205
  15. package/src/http/sse.ts +0 -136
  16. package/src/index.ts +0 -32
  17. package/src/ollama/index.ts +0 -3
  18. package/src/openai/index.ts +0 -39
  19. package/src/openrouter/index.ts +0 -11
  20. package/src/providers/anthropic/index.ts +0 -17
  21. package/src/providers/anthropic/llm.ts +0 -196
  22. package/src/providers/anthropic/transform.ts +0 -434
  23. package/src/providers/anthropic/types.ts +0 -213
  24. package/src/providers/google/index.ts +0 -17
  25. package/src/providers/google/llm.ts +0 -203
  26. package/src/providers/google/transform.ts +0 -447
  27. package/src/providers/google/types.ts +0 -214
  28. package/src/providers/ollama/index.ts +0 -43
  29. package/src/providers/ollama/llm.ts +0 -272
  30. package/src/providers/ollama/transform.ts +0 -434
  31. package/src/providers/ollama/types.ts +0 -260
  32. package/src/providers/openai/index.ts +0 -186
  33. package/src/providers/openai/llm.completions.ts +0 -201
  34. package/src/providers/openai/llm.responses.ts +0 -211
  35. package/src/providers/openai/transform.completions.ts +0 -561
  36. package/src/providers/openai/transform.responses.ts +0 -708
  37. package/src/providers/openai/types.ts +0 -1249
  38. package/src/providers/openrouter/index.ts +0 -177
  39. package/src/providers/openrouter/llm.completions.ts +0 -201
  40. package/src/providers/openrouter/llm.responses.ts +0 -211
  41. package/src/providers/openrouter/transform.completions.ts +0 -538
  42. package/src/providers/openrouter/transform.responses.ts +0 -742
  43. package/src/providers/openrouter/types.ts +0 -717
  44. package/src/providers/xai/index.ts +0 -223
  45. package/src/providers/xai/llm.completions.ts +0 -201
  46. package/src/providers/xai/llm.messages.ts +0 -195
  47. package/src/providers/xai/llm.responses.ts +0 -211
  48. package/src/providers/xai/transform.completions.ts +0 -565
  49. package/src/providers/xai/transform.messages.ts +0 -448
  50. package/src/providers/xai/transform.responses.ts +0 -678
  51. package/src/providers/xai/types.ts +0 -938
  52. package/src/types/content.ts +0 -133
  53. package/src/types/errors.ts +0 -85
  54. package/src/types/index.ts +0 -105
  55. package/src/types/llm.ts +0 -211
  56. package/src/types/messages.ts +0 -205
  57. package/src/types/provider.ts +0 -195
  58. package/src/types/schema.ts +0 -58
  59. package/src/types/stream.ts +0 -146
  60. package/src/types/thread.ts +0 -226
  61. package/src/types/tool.ts +0 -88
  62. package/src/types/turn.ts +0 -118
  63. package/src/utils/id.ts +0 -28
  64. package/src/xai/index.ts +0 -41
@@ -1,226 +0,0 @@
1
- import { generateId } from '../utils/id.ts';
2
- import {
3
- Message,
4
- UserMessage,
5
- AssistantMessage,
6
- ToolResultMessage,
7
- } from './messages.ts';
8
- import type { MessageType, MessageMetadata } from './messages.ts';
9
- import type { ContentBlock, UserContent, AssistantContent } from './content.ts';
10
- import type { Turn } from './turn.ts';
11
- import type { ToolCall, ToolResult } from './tool.ts';
12
-
13
- /**
14
- * Serialized message format
15
- */
16
- export interface MessageJSON {
17
- id: string;
18
- type: MessageType;
19
- content: ContentBlock[];
20
- toolCalls?: ToolCall[];
21
- results?: ToolResult[];
22
- metadata?: MessageMetadata;
23
- timestamp: string;
24
- }
25
-
26
- /**
27
- * Serialized thread format
28
- */
29
- export interface ThreadJSON {
30
- id: string;
31
- messages: MessageJSON[];
32
- createdAt: string;
33
- updatedAt: string;
34
- }
35
-
36
- /**
37
- * Thread - A utility class for managing conversation history
38
- * Users control their own history; Thread is optional
39
- */
40
- export class Thread {
41
- /** Unique thread identifier */
42
- readonly id: string;
43
-
44
- /** Internal message storage */
45
- private _messages: Message[];
46
-
47
- /** Creation timestamp */
48
- private _createdAt: Date;
49
-
50
- /** Last update timestamp */
51
- private _updatedAt: Date;
52
-
53
- /**
54
- * Create a new thread, optionally with initial messages
55
- */
56
- constructor(messages?: Message[]) {
57
- this.id = generateId();
58
- this._messages = messages ? [...messages] : [];
59
- this._createdAt = new Date();
60
- this._updatedAt = new Date();
61
- }
62
-
63
- /** All messages in the thread (readonly) */
64
- get messages(): readonly Message[] {
65
- return this._messages;
66
- }
67
-
68
- /** Number of messages */
69
- get length(): number {
70
- return this._messages.length;
71
- }
72
-
73
- /**
74
- * Append messages from a turn
75
- */
76
- append(turn: Turn): this {
77
- this._messages.push(...turn.messages);
78
- this._updatedAt = new Date();
79
- return this;
80
- }
81
-
82
- /**
83
- * Add raw messages
84
- */
85
- push(...messages: Message[]): this {
86
- this._messages.push(...messages);
87
- this._updatedAt = new Date();
88
- return this;
89
- }
90
-
91
- /**
92
- * Add a user message
93
- */
94
- user(content: string | UserContent[]): this {
95
- this._messages.push(new UserMessage(content));
96
- this._updatedAt = new Date();
97
- return this;
98
- }
99
-
100
- /**
101
- * Add an assistant message
102
- */
103
- assistant(content: string | AssistantContent[]): this {
104
- this._messages.push(new AssistantMessage(content));
105
- this._updatedAt = new Date();
106
- return this;
107
- }
108
-
109
- /**
110
- * Get messages by type
111
- */
112
- filter(type: MessageType): Message[] {
113
- return this._messages.filter((m) => m.type === type);
114
- }
115
-
116
- /**
117
- * Get the last N messages
118
- */
119
- tail(count: number): Message[] {
120
- return this._messages.slice(-count);
121
- }
122
-
123
- /**
124
- * Create a new thread with a subset of messages
125
- */
126
- slice(start?: number, end?: number): Thread {
127
- return new Thread(this._messages.slice(start, end));
128
- }
129
-
130
- /**
131
- * Clear all messages
132
- */
133
- clear(): this {
134
- this._messages = [];
135
- this._updatedAt = new Date();
136
- return this;
137
- }
138
-
139
- /**
140
- * Convert to plain message array
141
- */
142
- toMessages(): Message[] {
143
- return [...this._messages];
144
- }
145
-
146
- /**
147
- * Serialize to JSON
148
- */
149
- toJSON(): ThreadJSON {
150
- return {
151
- id: this.id,
152
- messages: this._messages.map((m) => this.messageToJSON(m)),
153
- createdAt: this._createdAt.toISOString(),
154
- updatedAt: this._updatedAt.toISOString(),
155
- };
156
- }
157
-
158
- /**
159
- * Deserialize from JSON
160
- */
161
- static fromJSON(json: ThreadJSON): Thread {
162
- const messages = json.messages.map((m) => Thread.messageFromJSON(m));
163
- const thread = new Thread(messages);
164
- // Override the generated id with the serialized one
165
- (thread as { id: string }).id = json.id;
166
- thread._createdAt = new Date(json.createdAt);
167
- thread._updatedAt = new Date(json.updatedAt);
168
- return thread;
169
- }
170
-
171
- /**
172
- * Iterate over messages
173
- */
174
- [Symbol.iterator](): Iterator<Message> {
175
- return this._messages[Symbol.iterator]();
176
- }
177
-
178
- /**
179
- * Convert a message to JSON
180
- */
181
- private messageToJSON(m: Message): MessageJSON {
182
- const base: MessageJSON = {
183
- id: m.id,
184
- type: m.type,
185
- content: [],
186
- metadata: m.metadata,
187
- timestamp: m.timestamp.toISOString(),
188
- };
189
-
190
- if (m instanceof UserMessage) {
191
- base.content = m.content;
192
- } else if (m instanceof AssistantMessage) {
193
- base.content = m.content;
194
- base.toolCalls = m.toolCalls;
195
- } else if (m instanceof ToolResultMessage) {
196
- base.results = m.results;
197
- }
198
-
199
- return base;
200
- }
201
-
202
- /**
203
- * Reconstruct a message from JSON
204
- */
205
- private static messageFromJSON(json: MessageJSON): Message {
206
- const options = {
207
- id: json.id,
208
- metadata: json.metadata,
209
- };
210
-
211
- switch (json.type) {
212
- case 'user':
213
- return new UserMessage(json.content as UserContent[], options);
214
- case 'assistant':
215
- return new AssistantMessage(
216
- json.content as AssistantContent[],
217
- json.toolCalls,
218
- options
219
- );
220
- case 'tool_result':
221
- return new ToolResultMessage(json.results ?? [], options);
222
- default:
223
- throw new Error(`Unknown message type: ${json.type}`);
224
- }
225
- }
226
- }
package/src/types/tool.ts DELETED
@@ -1,88 +0,0 @@
1
- import type { JSONSchema } from './schema.ts';
2
-
3
- /**
4
- * Tool call requested by the model
5
- */
6
- export interface ToolCall {
7
- toolCallId: string;
8
- toolName: string;
9
- arguments: Record<string, unknown>;
10
- }
11
-
12
- /**
13
- * Result of tool execution
14
- */
15
- export interface ToolResult {
16
- toolCallId: string;
17
- result: unknown;
18
- isError?: boolean;
19
- }
20
-
21
- /**
22
- * Tool definition
23
- */
24
- export interface Tool<TParams = unknown, TResult = unknown> {
25
- /** Tool name (must be unique within a llm() instance) */
26
- name: string;
27
-
28
- /** Human-readable description for the model */
29
- description: string;
30
-
31
- /** JSON Schema defining parameters */
32
- parameters: JSONSchema;
33
-
34
- /** Tool execution function */
35
- run(params: TParams): TResult | Promise<TResult>;
36
-
37
- /** Optional approval handler for sensitive operations */
38
- approval?(params: TParams): boolean | Promise<boolean>;
39
- }
40
-
41
- /**
42
- * Strategy for tool execution
43
- */
44
- export interface ToolUseStrategy {
45
- /** Maximum tool execution rounds (default: 10) */
46
- maxIterations?: number;
47
-
48
- /** Called when the model requests a tool call */
49
- onToolCall?(tool: Tool, params: unknown): void | Promise<void>;
50
-
51
- /** Called before tool execution, return false to skip */
52
- onBeforeCall?(tool: Tool, params: unknown): boolean | Promise<boolean>;
53
-
54
- /** Called after tool execution */
55
- onAfterCall?(tool: Tool, params: unknown, result: unknown): void | Promise<void>;
56
-
57
- /** Called on tool execution error */
58
- onError?(tool: Tool, params: unknown, error: Error): void | Promise<void>;
59
-
60
- /** Called when max iterations reached */
61
- onMaxIterations?(iterations: number): void | Promise<void>;
62
- }
63
-
64
- /**
65
- * Record of a tool execution
66
- */
67
- export interface ToolExecution {
68
- /** The tool that was called */
69
- toolName: string;
70
-
71
- /** Tool call ID */
72
- toolCallId: string;
73
-
74
- /** Arguments passed to the tool */
75
- arguments: Record<string, unknown>;
76
-
77
- /** Result returned by the tool */
78
- result: unknown;
79
-
80
- /** Whether the tool execution resulted in an error */
81
- isError: boolean;
82
-
83
- /** Execution duration in milliseconds */
84
- duration: number;
85
-
86
- /** Whether approval was required and granted */
87
- approved?: boolean;
88
- }
package/src/types/turn.ts DELETED
@@ -1,118 +0,0 @@
1
- import type { Message, AssistantMessage } from './messages.ts';
2
- import type { ToolExecution } from './tool.ts';
3
-
4
- /**
5
- * Token usage information
6
- */
7
- export interface TokenUsage {
8
- /** Input tokens across all cycles */
9
- inputTokens: number;
10
-
11
- /** Output tokens across all cycles */
12
- outputTokens: number;
13
-
14
- /** Total tokens */
15
- totalTokens: number;
16
-
17
- /** Per-cycle breakdown (if available) */
18
- cycles?: Array<{
19
- inputTokens: number;
20
- outputTokens: number;
21
- }>;
22
- }
23
-
24
- /**
25
- * A Turn represents the complete result of one inference call,
26
- * including all messages produced during tool execution loops.
27
- */
28
- export interface Turn<TData = unknown> {
29
- /**
30
- * All messages produced during this inference, in chronological order.
31
- * Types: UserMessage, AssistantMessage (may include toolCalls), ToolResultMessage
32
- */
33
- readonly messages: Message[];
34
-
35
- /** The final assistant response (convenience accessor) */
36
- readonly response: AssistantMessage;
37
-
38
- /** Tool executions that occurred during this turn */
39
- readonly toolExecutions: ToolExecution[];
40
-
41
- /** Aggregate token usage for the entire turn */
42
- readonly usage: TokenUsage;
43
-
44
- /** Total number of inference cycles (1 + number of tool rounds) */
45
- readonly cycles: number;
46
-
47
- /**
48
- * Structured output data (if structure was provided).
49
- * Type is inferred from the schema when using TypeScript.
50
- */
51
- readonly data?: TData;
52
- }
53
-
54
- /**
55
- * Create a Turn from accumulated data
56
- */
57
- export function createTurn<TData = unknown>(
58
- messages: Message[],
59
- toolExecutions: ToolExecution[],
60
- usage: TokenUsage,
61
- cycles: number,
62
- data?: TData
63
- ): Turn<TData> {
64
- // Find the last assistant message as the response
65
- const response = messages
66
- .filter((m): m is AssistantMessage => m.type === 'assistant')
67
- .pop();
68
-
69
- if (!response) {
70
- throw new Error('Turn must contain at least one assistant message');
71
- }
72
-
73
- return {
74
- messages,
75
- response,
76
- toolExecutions,
77
- usage,
78
- cycles,
79
- data,
80
- };
81
- }
82
-
83
- /**
84
- * Create empty token usage
85
- */
86
- export function emptyUsage(): TokenUsage {
87
- return {
88
- inputTokens: 0,
89
- outputTokens: 0,
90
- totalTokens: 0,
91
- cycles: [],
92
- };
93
- }
94
-
95
- /**
96
- * Aggregate token usage from multiple cycles
97
- */
98
- export function aggregateUsage(usages: TokenUsage[]): TokenUsage {
99
- const cycles: TokenUsage['cycles'] = [];
100
- let inputTokens = 0;
101
- let outputTokens = 0;
102
-
103
- for (const usage of usages) {
104
- inputTokens += usage.inputTokens;
105
- outputTokens += usage.outputTokens;
106
- cycles.push({
107
- inputTokens: usage.inputTokens,
108
- outputTokens: usage.outputTokens,
109
- });
110
- }
111
-
112
- return {
113
- inputTokens,
114
- outputTokens,
115
- totalTokens: inputTokens + outputTokens,
116
- cycles,
117
- };
118
- }
package/src/utils/id.ts DELETED
@@ -1,28 +0,0 @@
1
- /**
2
- * Generate a unique ID
3
- * Uses crypto.randomUUID if available, falls back to a simple implementation
4
- */
5
- export function generateId(): string {
6
- if (typeof crypto !== 'undefined' && crypto.randomUUID) {
7
- return crypto.randomUUID();
8
- }
9
-
10
- // Fallback for environments without crypto.randomUUID
11
- return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
12
- const r = (Math.random() * 16) | 0;
13
- const v = c === 'x' ? r : (r & 0x3) | 0x8;
14
- return v.toString(16);
15
- });
16
- }
17
-
18
- /**
19
- * Generate a short ID (for tool call IDs, etc.)
20
- */
21
- export function generateShortId(prefix = ''): string {
22
- const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
23
- let result = prefix;
24
- for (let i = 0; i < 12; i++) {
25
- result += chars.charAt(Math.floor(Math.random() * chars.length));
26
- }
27
- return result;
28
- }
package/src/xai/index.ts DELETED
@@ -1,41 +0,0 @@
1
- /**
2
- * xAI provider for UPP (Unified Provider Protocol)
3
- *
4
- * This module exports the xAI provider for use with the Grok family of models.
5
- * xAI's APIs are compatible with both OpenAI and Anthropic SDKs.
6
- *
7
- * @example
8
- * ```ts
9
- * import { xai } from '@providerprotocol/ai/xai';
10
- * import { llm } from '@providerprotocol/ai';
11
- *
12
- * // Create an LLM instance with Grok
13
- * const model = llm({
14
- * model: xai('grok-4'),
15
- * params: { max_tokens: 1000 }
16
- * });
17
- *
18
- * // Generate a response
19
- * const turn = await model.generate('What is the meaning of life?');
20
- * console.log(turn.response.text);
21
- * ```
22
- *
23
- * @packageDocumentation
24
- */
25
-
26
- export { xai } from '../providers/xai/index.ts';
27
- export type {
28
- XAIProviderOptions,
29
- XAIProvider,
30
- } from '../providers/xai/index.ts';
31
- export type {
32
- XAICompletionsParams,
33
- XAIResponsesParams,
34
- XAIMessagesParams,
35
- XAIConfig,
36
- XAIAPIMode,
37
- XAIModelOptions,
38
- XAIModelReference,
39
- XAISearchParameters,
40
- XAIAgentTool,
41
- } from '../providers/xai/types.ts';