@providerprotocol/ai 0.0.1 → 0.0.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/anthropic/index.js +4 -2
- package/dist/anthropic/index.js.map +1 -1
- package/dist/{chunk-FTFX2VET.js → chunk-SUNYWHTH.js} +2 -89
- package/dist/chunk-SUNYWHTH.js.map +1 -0
- package/dist/chunk-X5G4EHL7.js +90 -0
- package/dist/chunk-X5G4EHL7.js.map +1 -0
- package/dist/google/index.js +4 -2
- package/dist/google/index.js.map +1 -1
- package/dist/http/index.js +5 -3
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/ollama/index.d.ts +108 -0
- package/dist/ollama/index.js +537 -0
- package/dist/ollama/index.js.map +1 -0
- package/dist/openai/index.js +4 -2
- package/dist/openai/index.js.map +1 -1
- package/dist/openrouter/index.d.ts +235 -0
- package/dist/openrouter/index.js +1342 -0
- package/dist/openrouter/index.js.map +1 -0
- package/package.json +16 -1
- package/src/ollama/index.ts +3 -0
- package/src/openrouter/index.ts +10 -0
- package/src/providers/ollama/index.ts +43 -0
- package/src/providers/ollama/llm.ts +272 -0
- package/src/providers/ollama/transform.ts +456 -0
- package/src/providers/ollama/types.ts +260 -0
- package/src/providers/openrouter/index.ts +173 -0
- package/src/providers/openrouter/llm.completions.ts +201 -0
- package/src/providers/openrouter/llm.responses.ts +211 -0
- package/src/providers/openrouter/transform.completions.ts +605 -0
- package/src/providers/openrouter/transform.responses.ts +755 -0
- package/src/providers/openrouter/types.ts +723 -0
- package/dist/chunk-FTFX2VET.js.map +0 -1
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
Provider,
|
|
3
|
+
ModelReference,
|
|
4
|
+
LLMHandler,
|
|
5
|
+
LLMProvider,
|
|
6
|
+
} from '../../types/provider.ts';
|
|
7
|
+
import { createCompletionsLLMHandler } from './llm.completions.ts';
|
|
8
|
+
import { createResponsesLLMHandler } from './llm.responses.ts';
|
|
9
|
+
import type { OpenRouterLLMParams, OpenRouterConfig } from './types.ts';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* OpenRouter provider options
|
|
13
|
+
*/
|
|
14
|
+
export interface OpenRouterProviderOptions {
|
|
15
|
+
/**
|
|
16
|
+
* Which API to use:
|
|
17
|
+
* - 'completions': Chat Completions API (default, recommended)
|
|
18
|
+
* - 'responses': Responses API (beta)
|
|
19
|
+
*/
|
|
20
|
+
api?: 'completions' | 'responses';
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* OpenRouter provider with configurable API mode
|
|
25
|
+
*
|
|
26
|
+
* @example
|
|
27
|
+
* // Using the Chat Completions API (default)
|
|
28
|
+
* const model = openrouter('openai/gpt-4o');
|
|
29
|
+
*
|
|
30
|
+
* @example
|
|
31
|
+
* // Using the Responses API (beta)
|
|
32
|
+
* const model = openrouter('openai/gpt-4o', { api: 'responses' });
|
|
33
|
+
*
|
|
34
|
+
* @example
|
|
35
|
+
* // Explicit Completions API
|
|
36
|
+
* const model = openrouter('anthropic/claude-3.5-sonnet', { api: 'completions' });
|
|
37
|
+
*/
|
|
38
|
+
export interface OpenRouterProvider extends Provider<OpenRouterProviderOptions> {
|
|
39
|
+
/**
|
|
40
|
+
* Create a model reference
|
|
41
|
+
* @param modelId - The model identifier (e.g., 'openai/gpt-4o', 'anthropic/claude-3.5-sonnet', 'meta-llama/llama-3.1-70b-instruct')
|
|
42
|
+
* @param options - Provider options including API selection
|
|
43
|
+
*/
|
|
44
|
+
(modelId: string, options?: OpenRouterProviderOptions): ModelReference<OpenRouterProviderOptions>;
|
|
45
|
+
|
|
46
|
+
/** Provider name */
|
|
47
|
+
readonly name: 'openrouter';
|
|
48
|
+
|
|
49
|
+
/** Provider version */
|
|
50
|
+
readonly version: string;
|
|
51
|
+
|
|
52
|
+
/** Supported modalities */
|
|
53
|
+
readonly modalities: {
|
|
54
|
+
llm: LLMHandler<OpenRouterLLMParams>;
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Create the OpenRouter provider
|
|
60
|
+
*/
|
|
61
|
+
function createOpenRouterProvider(): OpenRouterProvider {
|
|
62
|
+
// Track which API mode is currently active for the modalities
|
|
63
|
+
// Default to 'completions' (unlike OpenAI which defaults to 'responses')
|
|
64
|
+
let currentApiMode: 'completions' | 'responses' = 'completions';
|
|
65
|
+
|
|
66
|
+
// Create handlers eagerly so we can inject provider reference
|
|
67
|
+
const completionsHandler = createCompletionsLLMHandler();
|
|
68
|
+
const responsesHandler = createResponsesLLMHandler();
|
|
69
|
+
|
|
70
|
+
const fn = function (
|
|
71
|
+
modelId: string,
|
|
72
|
+
options?: OpenRouterProviderOptions
|
|
73
|
+
): ModelReference<OpenRouterProviderOptions> {
|
|
74
|
+
const apiMode = options?.api ?? 'completions';
|
|
75
|
+
currentApiMode = apiMode;
|
|
76
|
+
return { modelId, provider };
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
// Create a dynamic modalities object that returns the correct handler
|
|
80
|
+
const modalities = {
|
|
81
|
+
get llm(): LLMHandler<OpenRouterLLMParams> {
|
|
82
|
+
return currentApiMode === 'responses'
|
|
83
|
+
? responsesHandler
|
|
84
|
+
: completionsHandler;
|
|
85
|
+
},
|
|
86
|
+
};
|
|
87
|
+
|
|
88
|
+
// Define properties
|
|
89
|
+
Object.defineProperties(fn, {
|
|
90
|
+
name: {
|
|
91
|
+
value: 'openrouter',
|
|
92
|
+
writable: false,
|
|
93
|
+
configurable: true,
|
|
94
|
+
},
|
|
95
|
+
version: {
|
|
96
|
+
value: '1.0.0',
|
|
97
|
+
writable: false,
|
|
98
|
+
configurable: true,
|
|
99
|
+
},
|
|
100
|
+
modalities: {
|
|
101
|
+
value: modalities,
|
|
102
|
+
writable: false,
|
|
103
|
+
configurable: true,
|
|
104
|
+
},
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
const provider = fn as OpenRouterProvider;
|
|
108
|
+
|
|
109
|
+
// Inject provider reference into both handlers (spec compliance)
|
|
110
|
+
completionsHandler._setProvider?.(provider as unknown as LLMProvider<OpenRouterLLMParams>);
|
|
111
|
+
responsesHandler._setProvider?.(provider as unknown as LLMProvider<OpenRouterLLMParams>);
|
|
112
|
+
|
|
113
|
+
return provider;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* OpenRouter provider
|
|
118
|
+
*
|
|
119
|
+
* Supports both the Chat Completions API (default) and Responses API (beta).
|
|
120
|
+
*
|
|
121
|
+
* OpenRouter is a unified API that provides access to hundreds of AI models
|
|
122
|
+
* through a single endpoint, including models from OpenAI, Anthropic, Google,
|
|
123
|
+
* Meta, Mistral, and many others.
|
|
124
|
+
*
|
|
125
|
+
* @example
|
|
126
|
+
* ```ts
|
|
127
|
+
* import { openrouter } from './providers/openrouter';
|
|
128
|
+
* import { llm } from './core/llm';
|
|
129
|
+
*
|
|
130
|
+
* // Using Chat Completions API (default, recommended)
|
|
131
|
+
* const model = llm({
|
|
132
|
+
* model: openrouter('openai/gpt-4o'),
|
|
133
|
+
* params: { max_tokens: 1000 }
|
|
134
|
+
* });
|
|
135
|
+
*
|
|
136
|
+
* // Using Responses API (beta)
|
|
137
|
+
* const betaModel = llm({
|
|
138
|
+
* model: openrouter('openai/gpt-4o', { api: 'responses' }),
|
|
139
|
+
* params: { max_output_tokens: 1000 }
|
|
140
|
+
* });
|
|
141
|
+
*
|
|
142
|
+
* // Using OpenRouter-specific features
|
|
143
|
+
* const routedModel = llm({
|
|
144
|
+
* model: openrouter('openai/gpt-4o'),
|
|
145
|
+
* params: {
|
|
146
|
+
* max_tokens: 1000,
|
|
147
|
+
* // Fallback routing
|
|
148
|
+
* models: ['openai/gpt-4o', 'anthropic/claude-3.5-sonnet'],
|
|
149
|
+
* route: 'fallback',
|
|
150
|
+
* // Provider preferences
|
|
151
|
+
* provider: {
|
|
152
|
+
* allow_fallbacks: true,
|
|
153
|
+
* require_parameters: true,
|
|
154
|
+
* },
|
|
155
|
+
* }
|
|
156
|
+
* });
|
|
157
|
+
*
|
|
158
|
+
* // Generate
|
|
159
|
+
* const turn = await model.generate('Hello!');
|
|
160
|
+
* console.log(turn.response.text);
|
|
161
|
+
* ```
|
|
162
|
+
*/
|
|
163
|
+
export const openrouter = createOpenRouterProvider();
|
|
164
|
+
|
|
165
|
+
// Re-export types
|
|
166
|
+
export type {
|
|
167
|
+
OpenRouterLLMParams,
|
|
168
|
+
OpenRouterConfig,
|
|
169
|
+
OpenRouterAPIMode,
|
|
170
|
+
OpenRouterModelOptions,
|
|
171
|
+
OpenRouterModelReference,
|
|
172
|
+
OpenRouterProviderPreferences,
|
|
173
|
+
} from './types.ts';
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
import type { LLMHandler, BoundLLMModel, LLMRequest, LLMResponse, LLMStreamResult, LLMCapabilities } from '../../types/llm.ts';
|
|
2
|
+
import type { StreamEvent } from '../../types/stream.ts';
|
|
3
|
+
import type { LLMProvider } from '../../types/provider.ts';
|
|
4
|
+
import { UPPError } from '../../types/errors.ts';
|
|
5
|
+
import { resolveApiKey } from '../../http/keys.ts';
|
|
6
|
+
import { doFetch, doStreamFetch } from '../../http/fetch.ts';
|
|
7
|
+
import { parseSSEStream } from '../../http/sse.ts';
|
|
8
|
+
import { normalizeHttpError } from '../../http/errors.ts';
|
|
9
|
+
import type { OpenRouterLLMParams, OpenRouterCompletionsResponse, OpenRouterCompletionsStreamChunk } from './types.ts';
|
|
10
|
+
import {
|
|
11
|
+
transformRequest,
|
|
12
|
+
transformResponse,
|
|
13
|
+
transformStreamEvent,
|
|
14
|
+
createStreamState,
|
|
15
|
+
buildResponseFromState,
|
|
16
|
+
} from './transform.completions.ts';
|
|
17
|
+
|
|
18
|
+
const OPENROUTER_API_URL = 'https://openrouter.ai/api/v1/chat/completions';
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* OpenRouter API capabilities
|
|
22
|
+
*/
|
|
23
|
+
const OPENROUTER_CAPABILITIES: LLMCapabilities = {
|
|
24
|
+
streaming: true,
|
|
25
|
+
tools: true,
|
|
26
|
+
structuredOutput: true,
|
|
27
|
+
imageInput: true,
|
|
28
|
+
videoInput: false,
|
|
29
|
+
audioInput: false,
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Create OpenRouter Chat Completions LLM handler
|
|
34
|
+
*/
|
|
35
|
+
export function createCompletionsLLMHandler(): LLMHandler<OpenRouterLLMParams> {
|
|
36
|
+
// Provider reference injected by createProvider() or OpenRouter's custom factory
|
|
37
|
+
let providerRef: LLMProvider<OpenRouterLLMParams> | null = null;
|
|
38
|
+
|
|
39
|
+
return {
|
|
40
|
+
_setProvider(provider: LLMProvider<OpenRouterLLMParams>) {
|
|
41
|
+
providerRef = provider;
|
|
42
|
+
},
|
|
43
|
+
|
|
44
|
+
bind(modelId: string): BoundLLMModel<OpenRouterLLMParams> {
|
|
45
|
+
// Use the injected provider reference
|
|
46
|
+
if (!providerRef) {
|
|
47
|
+
throw new UPPError(
|
|
48
|
+
'Provider reference not set. Handler must be used with createProvider() or have _setProvider called.',
|
|
49
|
+
'INVALID_REQUEST',
|
|
50
|
+
'openrouter',
|
|
51
|
+
'llm'
|
|
52
|
+
);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const model: BoundLLMModel<OpenRouterLLMParams> = {
|
|
56
|
+
modelId,
|
|
57
|
+
capabilities: OPENROUTER_CAPABILITIES,
|
|
58
|
+
|
|
59
|
+
get provider(): LLMProvider<OpenRouterLLMParams> {
|
|
60
|
+
return providerRef!;
|
|
61
|
+
},
|
|
62
|
+
|
|
63
|
+
async complete(request: LLMRequest<OpenRouterLLMParams>): Promise<LLMResponse> {
|
|
64
|
+
const apiKey = await resolveApiKey(
|
|
65
|
+
request.config,
|
|
66
|
+
'OPENROUTER_API_KEY',
|
|
67
|
+
'openrouter',
|
|
68
|
+
'llm'
|
|
69
|
+
);
|
|
70
|
+
|
|
71
|
+
const baseUrl = request.config.baseUrl ?? OPENROUTER_API_URL;
|
|
72
|
+
const body = transformRequest(request, modelId);
|
|
73
|
+
|
|
74
|
+
const response = await doFetch(
|
|
75
|
+
baseUrl,
|
|
76
|
+
{
|
|
77
|
+
method: 'POST',
|
|
78
|
+
headers: {
|
|
79
|
+
'Content-Type': 'application/json',
|
|
80
|
+
Authorization: `Bearer ${apiKey}`,
|
|
81
|
+
},
|
|
82
|
+
body: JSON.stringify(body),
|
|
83
|
+
signal: request.signal,
|
|
84
|
+
},
|
|
85
|
+
request.config,
|
|
86
|
+
'openrouter',
|
|
87
|
+
'llm'
|
|
88
|
+
);
|
|
89
|
+
|
|
90
|
+
const data = (await response.json()) as OpenRouterCompletionsResponse;
|
|
91
|
+
return transformResponse(data);
|
|
92
|
+
},
|
|
93
|
+
|
|
94
|
+
stream(request: LLMRequest<OpenRouterLLMParams>): LLMStreamResult {
|
|
95
|
+
const state = createStreamState();
|
|
96
|
+
let responseResolve: (value: LLMResponse) => void;
|
|
97
|
+
let responseReject: (error: Error) => void;
|
|
98
|
+
|
|
99
|
+
const responsePromise = new Promise<LLMResponse>((resolve, reject) => {
|
|
100
|
+
responseResolve = resolve;
|
|
101
|
+
responseReject = reject;
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
async function* generateEvents(): AsyncGenerator<StreamEvent, void, unknown> {
|
|
105
|
+
try {
|
|
106
|
+
const apiKey = await resolveApiKey(
|
|
107
|
+
request.config,
|
|
108
|
+
'OPENROUTER_API_KEY',
|
|
109
|
+
'openrouter',
|
|
110
|
+
'llm'
|
|
111
|
+
);
|
|
112
|
+
|
|
113
|
+
const baseUrl = request.config.baseUrl ?? OPENROUTER_API_URL;
|
|
114
|
+
const body = transformRequest(request, modelId);
|
|
115
|
+
body.stream = true;
|
|
116
|
+
body.stream_options = { include_usage: true };
|
|
117
|
+
|
|
118
|
+
const response = await doStreamFetch(
|
|
119
|
+
baseUrl,
|
|
120
|
+
{
|
|
121
|
+
method: 'POST',
|
|
122
|
+
headers: {
|
|
123
|
+
'Content-Type': 'application/json',
|
|
124
|
+
Authorization: `Bearer ${apiKey}`,
|
|
125
|
+
},
|
|
126
|
+
body: JSON.stringify(body),
|
|
127
|
+
signal: request.signal,
|
|
128
|
+
},
|
|
129
|
+
request.config,
|
|
130
|
+
'openrouter',
|
|
131
|
+
'llm'
|
|
132
|
+
);
|
|
133
|
+
|
|
134
|
+
if (!response.ok) {
|
|
135
|
+
const error = await normalizeHttpError(response, 'openrouter', 'llm');
|
|
136
|
+
responseReject(error);
|
|
137
|
+
throw error;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
if (!response.body) {
|
|
141
|
+
const error = new UPPError(
|
|
142
|
+
'No response body for streaming request',
|
|
143
|
+
'PROVIDER_ERROR',
|
|
144
|
+
'openrouter',
|
|
145
|
+
'llm'
|
|
146
|
+
);
|
|
147
|
+
responseReject(error);
|
|
148
|
+
throw error;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
for await (const data of parseSSEStream(response.body)) {
|
|
152
|
+
// Skip [DONE] marker
|
|
153
|
+
if (data === '[DONE]') {
|
|
154
|
+
continue;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// Check for OpenRouter error event
|
|
158
|
+
if (typeof data === 'object' && data !== null) {
|
|
159
|
+
const chunk = data as OpenRouterCompletionsStreamChunk;
|
|
160
|
+
|
|
161
|
+
// Check for error in chunk
|
|
162
|
+
if ('error' in chunk && chunk.error) {
|
|
163
|
+
const errorData = chunk.error as { message?: string; type?: string };
|
|
164
|
+
const error = new UPPError(
|
|
165
|
+
errorData.message ?? 'Unknown error',
|
|
166
|
+
'PROVIDER_ERROR',
|
|
167
|
+
'openrouter',
|
|
168
|
+
'llm'
|
|
169
|
+
);
|
|
170
|
+
responseReject(error);
|
|
171
|
+
throw error;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
const uppEvents = transformStreamEvent(chunk, state);
|
|
175
|
+
for (const event of uppEvents) {
|
|
176
|
+
yield event;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// Build final response
|
|
182
|
+
responseResolve(buildResponseFromState(state));
|
|
183
|
+
} catch (error) {
|
|
184
|
+
responseReject(error as Error);
|
|
185
|
+
throw error;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
return {
|
|
190
|
+
[Symbol.asyncIterator]() {
|
|
191
|
+
return generateEvents();
|
|
192
|
+
},
|
|
193
|
+
response: responsePromise,
|
|
194
|
+
};
|
|
195
|
+
},
|
|
196
|
+
};
|
|
197
|
+
|
|
198
|
+
return model;
|
|
199
|
+
},
|
|
200
|
+
};
|
|
201
|
+
}
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
import type { LLMHandler, BoundLLMModel, LLMRequest, LLMResponse, LLMStreamResult, LLMCapabilities } from '../../types/llm.ts';
|
|
2
|
+
import type { StreamEvent } from '../../types/stream.ts';
|
|
3
|
+
import type { LLMProvider } from '../../types/provider.ts';
|
|
4
|
+
import { UPPError } from '../../types/errors.ts';
|
|
5
|
+
import { resolveApiKey } from '../../http/keys.ts';
|
|
6
|
+
import { doFetch, doStreamFetch } from '../../http/fetch.ts';
|
|
7
|
+
import { parseSSEStream } from '../../http/sse.ts';
|
|
8
|
+
import { normalizeHttpError } from '../../http/errors.ts';
|
|
9
|
+
import type { OpenRouterLLMParams, OpenRouterResponsesResponse, OpenRouterResponsesStreamEvent, OpenRouterResponseErrorEvent } from './types.ts';
|
|
10
|
+
import {
|
|
11
|
+
transformRequest,
|
|
12
|
+
transformResponse,
|
|
13
|
+
transformStreamEvent,
|
|
14
|
+
createStreamState,
|
|
15
|
+
buildResponseFromState,
|
|
16
|
+
} from './transform.responses.ts';
|
|
17
|
+
|
|
18
|
+
const OPENROUTER_RESPONSES_API_URL = 'https://openrouter.ai/api/v1/responses';
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* OpenRouter API capabilities
|
|
22
|
+
*/
|
|
23
|
+
const OPENROUTER_CAPABILITIES: LLMCapabilities = {
|
|
24
|
+
streaming: true,
|
|
25
|
+
tools: true,
|
|
26
|
+
structuredOutput: true,
|
|
27
|
+
imageInput: true,
|
|
28
|
+
videoInput: false,
|
|
29
|
+
audioInput: false,
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Create OpenRouter Responses API LLM handler
|
|
34
|
+
*/
|
|
35
|
+
export function createResponsesLLMHandler(): LLMHandler<OpenRouterLLMParams> {
|
|
36
|
+
// Provider reference injected by createProvider() or OpenRouter's custom factory
|
|
37
|
+
let providerRef: LLMProvider<OpenRouterLLMParams> | null = null;
|
|
38
|
+
|
|
39
|
+
return {
|
|
40
|
+
_setProvider(provider: LLMProvider<OpenRouterLLMParams>) {
|
|
41
|
+
providerRef = provider;
|
|
42
|
+
},
|
|
43
|
+
|
|
44
|
+
bind(modelId: string): BoundLLMModel<OpenRouterLLMParams> {
|
|
45
|
+
// Use the injected provider reference
|
|
46
|
+
if (!providerRef) {
|
|
47
|
+
throw new UPPError(
|
|
48
|
+
'Provider reference not set. Handler must be used with createProvider() or have _setProvider called.',
|
|
49
|
+
'INVALID_REQUEST',
|
|
50
|
+
'openrouter',
|
|
51
|
+
'llm'
|
|
52
|
+
);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const model: BoundLLMModel<OpenRouterLLMParams> = {
|
|
56
|
+
modelId,
|
|
57
|
+
capabilities: OPENROUTER_CAPABILITIES,
|
|
58
|
+
|
|
59
|
+
get provider(): LLMProvider<OpenRouterLLMParams> {
|
|
60
|
+
return providerRef!;
|
|
61
|
+
},
|
|
62
|
+
|
|
63
|
+
async complete(request: LLMRequest<OpenRouterLLMParams>): Promise<LLMResponse> {
|
|
64
|
+
const apiKey = await resolveApiKey(
|
|
65
|
+
request.config,
|
|
66
|
+
'OPENROUTER_API_KEY',
|
|
67
|
+
'openrouter',
|
|
68
|
+
'llm'
|
|
69
|
+
);
|
|
70
|
+
|
|
71
|
+
const baseUrl = request.config.baseUrl ?? OPENROUTER_RESPONSES_API_URL;
|
|
72
|
+
const body = transformRequest(request, modelId);
|
|
73
|
+
|
|
74
|
+
const response = await doFetch(
|
|
75
|
+
baseUrl,
|
|
76
|
+
{
|
|
77
|
+
method: 'POST',
|
|
78
|
+
headers: {
|
|
79
|
+
'Content-Type': 'application/json',
|
|
80
|
+
Authorization: `Bearer ${apiKey}`,
|
|
81
|
+
},
|
|
82
|
+
body: JSON.stringify(body),
|
|
83
|
+
signal: request.signal,
|
|
84
|
+
},
|
|
85
|
+
request.config,
|
|
86
|
+
'openrouter',
|
|
87
|
+
'llm'
|
|
88
|
+
);
|
|
89
|
+
|
|
90
|
+
const data = (await response.json()) as OpenRouterResponsesResponse;
|
|
91
|
+
|
|
92
|
+
// Check for error in response
|
|
93
|
+
if (data.status === 'failed' && data.error) {
|
|
94
|
+
throw new UPPError(
|
|
95
|
+
data.error.message,
|
|
96
|
+
'PROVIDER_ERROR',
|
|
97
|
+
'openrouter',
|
|
98
|
+
'llm'
|
|
99
|
+
);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
return transformResponse(data);
|
|
103
|
+
},
|
|
104
|
+
|
|
105
|
+
stream(request: LLMRequest<OpenRouterLLMParams>): LLMStreamResult {
|
|
106
|
+
const state = createStreamState();
|
|
107
|
+
let responseResolve: (value: LLMResponse) => void;
|
|
108
|
+
let responseReject: (error: Error) => void;
|
|
109
|
+
|
|
110
|
+
const responsePromise = new Promise<LLMResponse>((resolve, reject) => {
|
|
111
|
+
responseResolve = resolve;
|
|
112
|
+
responseReject = reject;
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
async function* generateEvents(): AsyncGenerator<StreamEvent, void, unknown> {
|
|
116
|
+
try {
|
|
117
|
+
const apiKey = await resolveApiKey(
|
|
118
|
+
request.config,
|
|
119
|
+
'OPENROUTER_API_KEY',
|
|
120
|
+
'openrouter',
|
|
121
|
+
'llm'
|
|
122
|
+
);
|
|
123
|
+
|
|
124
|
+
const baseUrl = request.config.baseUrl ?? OPENROUTER_RESPONSES_API_URL;
|
|
125
|
+
const body = transformRequest(request, modelId);
|
|
126
|
+
body.stream = true;
|
|
127
|
+
|
|
128
|
+
const response = await doStreamFetch(
|
|
129
|
+
baseUrl,
|
|
130
|
+
{
|
|
131
|
+
method: 'POST',
|
|
132
|
+
headers: {
|
|
133
|
+
'Content-Type': 'application/json',
|
|
134
|
+
Authorization: `Bearer ${apiKey}`,
|
|
135
|
+
},
|
|
136
|
+
body: JSON.stringify(body),
|
|
137
|
+
signal: request.signal,
|
|
138
|
+
},
|
|
139
|
+
request.config,
|
|
140
|
+
'openrouter',
|
|
141
|
+
'llm'
|
|
142
|
+
);
|
|
143
|
+
|
|
144
|
+
if (!response.ok) {
|
|
145
|
+
const error = await normalizeHttpError(response, 'openrouter', 'llm');
|
|
146
|
+
responseReject(error);
|
|
147
|
+
throw error;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
if (!response.body) {
|
|
151
|
+
const error = new UPPError(
|
|
152
|
+
'No response body for streaming request',
|
|
153
|
+
'PROVIDER_ERROR',
|
|
154
|
+
'openrouter',
|
|
155
|
+
'llm'
|
|
156
|
+
);
|
|
157
|
+
responseReject(error);
|
|
158
|
+
throw error;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
for await (const data of parseSSEStream(response.body)) {
|
|
162
|
+
// Skip [DONE] marker
|
|
163
|
+
if (data === '[DONE]') {
|
|
164
|
+
continue;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// Check for OpenRouter error event
|
|
168
|
+
if (typeof data === 'object' && data !== null) {
|
|
169
|
+
const event = data as OpenRouterResponsesStreamEvent;
|
|
170
|
+
|
|
171
|
+
// Check for error event
|
|
172
|
+
if (event.type === 'error') {
|
|
173
|
+
const errorEvent = event as OpenRouterResponseErrorEvent;
|
|
174
|
+
const error = new UPPError(
|
|
175
|
+
errorEvent.error.message,
|
|
176
|
+
'PROVIDER_ERROR',
|
|
177
|
+
'openrouter',
|
|
178
|
+
'llm'
|
|
179
|
+
);
|
|
180
|
+
responseReject(error);
|
|
181
|
+
throw error;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const uppEvents = transformStreamEvent(event, state);
|
|
185
|
+
for (const uppEvent of uppEvents) {
|
|
186
|
+
yield uppEvent;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// Build final response
|
|
192
|
+
responseResolve(buildResponseFromState(state));
|
|
193
|
+
} catch (error) {
|
|
194
|
+
responseReject(error as Error);
|
|
195
|
+
throw error;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
return {
|
|
200
|
+
[Symbol.asyncIterator]() {
|
|
201
|
+
return generateEvents();
|
|
202
|
+
},
|
|
203
|
+
response: responsePromise,
|
|
204
|
+
};
|
|
205
|
+
},
|
|
206
|
+
};
|
|
207
|
+
|
|
208
|
+
return model;
|
|
209
|
+
},
|
|
210
|
+
};
|
|
211
|
+
}
|