-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathopenrouter.ts
57 lines (55 loc) · 1.5 KB
/
openrouter.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import { Provider } from '../models.js'
import { openai as openai_structured_output, OpenAIProviderOptions } from './openai.js'
import { openai as openai_response_functions } from './openai_response_functions.js'
/**
* Required options for the OpenRouter provider.
*
* @see OpenAIProviderOptions
*/
type OpenRouterOptions = Partial<OpenAIProviderOptions> & {
/**
* Certain providers, such as Anthropic, do not support structured output.
* In this case, we use response functions instead.
*/
structured_output?: boolean
}
/**
* OpenRouter provider.
*
* Uses OpenAI API, but with custom base URL and API key.
*/
export const openrouter = (options: OpenRouterOptions = {}): Provider => {
const {
model = 'meta-llama/llama-3.1-405b-instruct',
structured_output = true,
options: clientOptions,
body = {},
} = options
const openAiOptions = {
model,
options: {
apiKey: process.env.OPENROUTER_API_KEY,
baseURL: 'https://openrouter.ai/api/v1',
...clientOptions,
},
/**
* Force OpenRouter to load-balance requests across providers that
* support structured output.
*/
body: {
...body,
provider: {
/**
* @see https://openrouter.ai/docs/provider-routing#required-parameters-_beta_
*/
require_parameters: true,
...body?.provider,
},
},
}
if (structured_output) {
return openai_structured_output(openAiOptions)
} else {
return openai_response_functions(openAiOptions)
}
}