@@ -34,6 +34,30 @@ export class OpenAICompatibleHandler extends BaseHandler<OpenAICompatibleModel>
34
34
}
35
35
}
36
36
37
+ determineAPIKey = ( ) => {
38
+ if ( this . opts . apiKey ) {
39
+ return this . opts . apiKey
40
+ } else if ( process . env . OPENAI_COMPATIBLE_API_KEY ) {
41
+ return process . env . OPENAI_COMPATIBLE_API_KEY
42
+ } else {
43
+ /**
44
+ * We hardcode an empty API key if none is defined because the OpenAI SDK throws an error if we do not do this.
45
+ * There are plenty of reasonable cases where an API is not required by an openai compartible model provider (locally
46
+ * hosted models for example), so we want to avoid runtime errors in those situations.
47
+ * See this issue for an example: https://github.com/twinnydotdev/twinny/issues/440
48
+ *
49
+ * However, the tradeoff with this is that if the underlying provider requires an API key and the user does not provide one,
50
+ * they may get an unpredictable error. We deem this tradeoff acceptible in this case because using an unvetted openai-compatible
51
+ * model provider is inherently less safe than using a provider officially integrated and supported by Token.js. If users often,
52
+ * report errors related to this, we should consider officially supporting the behavior of the underlying provider that is causing issues.
53
+ *
54
+ * For example, we may want to officially support ollama local models if users often report problems related to using that provider via this
55
+ * generic implementation.
56
+ */
57
+ return ''
58
+ }
59
+ }
60
+
37
61
async create (
38
62
body : ProviderCompletionParams < 'openai' >
39
63
) : Promise < CompletionResponse | StreamCompletionResponse > {
@@ -42,7 +66,7 @@ export class OpenAICompatibleHandler extends BaseHandler<OpenAICompatibleModel>
42
66
// Uses the OPENAI_API_KEY environment variable, if the apiKey is not provided.
43
67
// This makes the UX better for switching between providers because you can just
44
68
// define all the environment variables and then change the model field without doing anything else.
45
- const apiKey = this . opts . apiKey ?? process . env . OPENAI_COMPATIBLE_API_KEY
69
+ const apiKey = this . determineAPIKey ( )
46
70
const openai = new OpenAI ( {
47
71
...this . opts ,
48
72
apiKey,
0 commit comments