@livekit/agents-plugin-openai 1.10.1 → 1.11.1
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/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/llm.cjs +41 -1
- package/dist/llm.cjs.map +1 -1
- package/dist/llm.d.cts +29 -1
- package/dist/llm.d.ts +29 -1
- package/dist/llm.d.ts.map +1 -1
- package/dist/llm.js +41 -1
- package/dist/llm.js.map +1 -1
- package/dist/llm.test.cjs +91 -0
- package/dist/llm.test.cjs.map +1 -1
- package/dist/llm.test.js +92 -1
- package/dist/llm.test.js.map +1 -1
- package/package.json +5 -5
- package/src/llm.test.ts +110 -1
- package/src/llm.ts +64 -2
package/dist/index.cjs
CHANGED
package/dist/index.js
CHANGED
package/dist/llm.cjs
CHANGED
|
@@ -320,6 +320,40 @@ class LLM extends import_agents.llm.LLM {
|
|
|
320
320
|
...opts
|
|
321
321
|
});
|
|
322
322
|
}
|
|
323
|
+
/**
|
|
324
|
+
* Create a new instance of a Modal LLM.
|
|
325
|
+
*
|
|
326
|
+
* @remarks
|
|
327
|
+
* `model` is the endpoint hostname, e.g. `my-endpoint.us-west.modal.direct`.
|
|
328
|
+
* `baseURL` defaults to the shared inference gateway in the hostname's region and can be set to
|
|
329
|
+
* a dedicated Endpoint or self-hosted server URL.
|
|
330
|
+
*
|
|
331
|
+
* For authenticated Modal endpoints, pass your proxy token as `apiKey`, or set
|
|
332
|
+
* `MODAL_PROXY_TOKEN` or the `MODAL_PROXY_TOKEN_ID` and `MODAL_PROXY_TOKEN_SECRET` pair.
|
|
333
|
+
* A supplied `client` uses its own URL and credentials.
|
|
334
|
+
*/
|
|
335
|
+
static withModal(opts) {
|
|
336
|
+
let apiKey = opts.apiKey || process.env.MODAL_PROXY_TOKEN;
|
|
337
|
+
if (!apiKey) {
|
|
338
|
+
const tokenId = process.env.MODAL_PROXY_TOKEN_ID;
|
|
339
|
+
const tokenSecret = process.env.MODAL_PROXY_TOKEN_SECRET;
|
|
340
|
+
if (tokenId && tokenSecret) {
|
|
341
|
+
apiKey = `${tokenId}.${tokenSecret}`;
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
let baseURL = opts.baseURL;
|
|
345
|
+
if (baseURL === void 0) {
|
|
346
|
+
const region = opts.model.endsWith(".modal.direct") ? opts.model.split(".").at(-3) : "us-west";
|
|
347
|
+
baseURL = `https://inference.${region}.modal.direct/v1`;
|
|
348
|
+
}
|
|
349
|
+
return new LLM({
|
|
350
|
+
parallelToolCalls: void 0,
|
|
351
|
+
...opts,
|
|
352
|
+
apiKey: apiKey || "modal",
|
|
353
|
+
baseURL,
|
|
354
|
+
toolChoice: opts.toolChoice ?? "auto"
|
|
355
|
+
});
|
|
356
|
+
}
|
|
323
357
|
chat({
|
|
324
358
|
chatCtx,
|
|
325
359
|
toolCtx: toolCtxInput,
|
|
@@ -339,7 +373,7 @@ class LLM extends import_agents.llm.LLM {
|
|
|
339
373
|
if (this.#opts.maxCompletionTokens) {
|
|
340
374
|
extras.max_completion_tokens = this.#opts.maxCompletionTokens;
|
|
341
375
|
}
|
|
342
|
-
if (this.#opts.temperature) {
|
|
376
|
+
if (this.#opts.temperature !== void 0) {
|
|
343
377
|
extras.temperature = this.#opts.temperature;
|
|
344
378
|
}
|
|
345
379
|
if (this.#opts.topP !== void 0) {
|
|
@@ -354,6 +388,12 @@ class LLM extends import_agents.llm.LLM {
|
|
|
354
388
|
if (this.#opts.reasoningEffort !== void 0) {
|
|
355
389
|
extras.reasoning_effort = this.#opts.reasoningEffort;
|
|
356
390
|
}
|
|
391
|
+
if (this.#opts.safetyIdentifier !== void 0) {
|
|
392
|
+
extras.safety_identifier = this.#opts.safetyIdentifier;
|
|
393
|
+
}
|
|
394
|
+
if (this.#opts.promptCacheKey !== void 0) {
|
|
395
|
+
extras.prompt_cache_key = this.#opts.promptCacheKey;
|
|
396
|
+
}
|
|
357
397
|
parallelToolCalls = parallelToolCalls !== void 0 ? parallelToolCalls : this.#opts.parallelToolCalls;
|
|
358
398
|
if (toolCtx && Object.keys(toolCtx.functionTools).length > 0 && parallelToolCalls !== void 0) {
|
|
359
399
|
extras.parallel_tool_calls = parallelToolCalls;
|
package/dist/llm.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/llm.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2025 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport type { APIConnectOptions } from '@livekit/agents';\nimport { DEFAULT_API_CONNECT_OPTIONS, inference, llm } from '@livekit/agents';\nimport { AzureOpenAI, OpenAI } from 'openai';\nimport type {\n CerebrasChatModels,\n ChatModels,\n DeepSeekChatModels,\n GroqChatModels,\n MetaChatModels,\n OctoChatModels,\n PerplexityChatModels,\n ReasoningEffort,\n TelnyxChatModels,\n TogetherChatModels,\n XAIChatModels,\n} from './models.js';\nimport { defaultReasoningEffort } from './models.js';\n\nexport interface LLMOptions {\n model: string | ChatModels;\n apiKey?: string;\n baseURL?: string;\n user?: string;\n temperature?: number;\n topP?: number;\n client?: OpenAI;\n toolChoice?: llm.ToolChoice;\n parallelToolCalls?: boolean;\n metadata?: Record<string, string>;\n maxCompletionTokens?: number;\n serviceTier?: string;\n store?: boolean;\n reasoningEffort?: ReasoningEffort;\n strictToolSchema?: boolean;\n}\n\nconst defaultLLMOptions: LLMOptions = {\n model: 'gpt-4.1',\n apiKey: process.env.OPENAI_API_KEY,\n parallelToolCalls: true,\n strictToolSchema: false,\n};\n\nconst defaultAzureLLMOptions: LLMOptions = {\n model: 'gpt-4.1',\n apiKey: process.env.AZURE_API_KEY,\n strictToolSchema: false,\n};\n\nexport class LLM extends llm.LLM {\n #opts: LLMOptions;\n #client: OpenAI;\n #providerFmt: llm.ProviderFormat;\n\n /**\n * Create a new instance of OpenAI LLM.\n *\n * @remarks\n * `apiKey` must be set to your OpenAI API key, either using the argument or by setting the\n * `OPENAI_API_KEY` environment variable.\n */\n constructor(\n opts: Partial<LLMOptions> = defaultLLMOptions,\n providerFmt: llm.ProviderFormat = 'openai',\n ) {\n super();\n\n this.#opts = { ...defaultLLMOptions, ...opts };\n this.#opts.reasoningEffort ??= defaultReasoningEffort(this.#opts.model);\n this.#providerFmt = providerFmt;\n if (this.#opts.apiKey === undefined && !this.#opts.client) {\n throw new Error('OpenAI API key is required, whether as an argument or as $OPENAI_API_KEY');\n }\n\n this.#client =\n this.#opts.client ||\n new OpenAI({\n baseURL: this.#opts.baseURL,\n maxRetries: 0,\n apiKey: this.#opts.apiKey,\n });\n }\n\n label(): string {\n return 'openai.LLM';\n }\n\n get model(): string {\n return this.#opts.model;\n }\n\n get provider(): string {\n try {\n const url = new URL(this.#client.baseURL);\n return url.host;\n } catch {\n return 'api.openai.com';\n }\n }\n\n protected override async _prewarmImpl(signal: AbortSignal): Promise<void> {\n await this.#client.models.list({ signal });\n }\n\n /**\n * Create a new instance of OpenAI LLM with Azure.\n *\n * @remarks\n * This automatically infers the following arguments from their corresponding environment variables if they are not provided:\n * - `apiKey` from `AZURE_OPENAI_API_KEY`\n * - `organization` from `OPENAI_ORG_ID`\n * - `project` from `OPENAI_PROJECT_ID`\n * - `azureAdToken` from `AZURE_OPENAI_AD_TOKEN`\n * - `apiVersion` from `OPENAI_API_VERSION`\n * - `azureEndpoint` from `AZURE_OPENAI_ENDPOINT`\n */\n static withAzure(\n opts: {\n model: string | ChatModels;\n azureEndpoint?: string;\n azureDeployment?: string;\n apiVersion?: string;\n apiKey?: string;\n azureAdToken?: string;\n azureAdTokenProvider?: () => Promise<string>;\n organization?: string;\n project?: string;\n baseURL?: string;\n user?: string;\n temperature?: number;\n } = defaultAzureLLMOptions,\n ): LLM {\n opts = { ...defaultAzureLLMOptions, ...opts };\n if (opts.apiKey === undefined) {\n throw new Error('Azure API key is required, whether as an argument or as $AZURE_API_KEY');\n }\n\n return new LLM({\n temperature: opts.temperature,\n user: opts.user,\n client: new AzureOpenAI({ ...opts, maxRetries: 0 }),\n });\n }\n\n /**\n * Create a new instance of Cerebras LLM.\n *\n * @remarks\n * `apiKey` must be set to your Cerebras API key, either using the argument or by setting the\n * `CEREBRAS_API_KEY` environment variable.\n */\n static withCerebras(\n opts: Partial<{\n model: string | CerebrasChatModels;\n apiKey?: string;\n baseURL?: string;\n user?: string;\n temperature?: number;\n client: OpenAI;\n }> = {},\n ): LLM {\n opts.apiKey = opts.apiKey || process.env.CEREBRAS_API_KEY;\n if (opts.apiKey === undefined) {\n throw new Error(\n 'Cerebras API key is required, whether as an argument or as $CEREBRAS_API_KEY',\n );\n }\n\n return new LLM({\n model: 'gpt-oss-120b',\n baseURL: 'https://api.cerebras.ai/v1',\n ...opts,\n });\n }\n\n /**\n * Create a new instance of Fireworks LLM.\n *\n * @remarks\n * `apiKey` must be set to your Fireworks API key, either using the argument or by setting the\n * `FIREWORKS_API_KEY` environment variable.\n */\n static withFireworks(opts: Partial<LLMOptions> = {}): LLM {\n opts.apiKey = opts.apiKey || process.env.FIREWORKS_API_KEY;\n if (opts.apiKey === undefined) {\n throw new Error(\n 'Fireworks API key is required, whether as an argument or as $FIREWORKS_API_KEY',\n );\n }\n\n return new LLM({\n model: 'accounts/fireworks/models/llama-v3p1-70b-instruct',\n baseURL: 'https://api.fireworks.ai/inference/v1',\n ...opts,\n });\n }\n\n /**\n * Create a new instance of xAI LLM.\n *\n * @remarks\n * `apiKey` must be set to your xAI API key, either using the argument or by setting the\n * `XAI_API_KEY` environment variable.\n */\n static withXAI(\n opts: Partial<{\n model: string | XAIChatModels;\n apiKey?: string;\n baseURL?: string;\n user?: string;\n temperature?: number;\n client: OpenAI;\n }> = {},\n ): LLM {\n opts.apiKey = opts.apiKey || process.env.XAI_API_KEY;\n if (opts.apiKey === undefined) {\n throw new Error('xAI API key is required, whether as an argument or as $XAI_API_KEY');\n }\n\n return new LLM({\n model: 'grok-2-public',\n baseURL: 'https://api.x.ai/v1',\n ...opts,\n });\n }\n\n /**\n * Create a new instance of Groq LLM.\n *\n * @remarks\n * `apiKey` must be set to your Groq API key, either using the argument or by setting the\n * `GROQ_API_KEY` environment variable.\n */\n static withGroq(\n opts: Partial<{\n model: string | GroqChatModels;\n apiKey?: string;\n baseURL?: string;\n user?: string;\n temperature?: number;\n client: OpenAI;\n }> = {},\n ): LLM {\n opts.apiKey = opts.apiKey || process.env.GROQ_API_KEY;\n if (opts.apiKey === undefined) {\n throw new Error('Groq API key is required, whether as an argument or as $GROQ_API_KEY');\n }\n\n return new LLM({\n model: 'openai/gpt-oss-120b',\n baseURL: 'https://api.groq.com/openai/v1',\n ...opts,\n });\n }\n\n /**\n * Create a new instance of DeepSeek LLM.\n *\n * @remarks\n * `apiKey` must be set to your DeepSeek API key, either using the argument or by setting the\n * `DEEPSEEK_API_KEY` environment variable.\n */\n static withDeepSeek(\n opts: Partial<{\n model: string | DeepSeekChatModels;\n apiKey?: string;\n baseURL?: string;\n user?: string;\n temperature?: number;\n client: OpenAI;\n }> = {},\n ): LLM {\n opts.apiKey = opts.apiKey || process.env.DEEPSEEK_API_KEY;\n if (opts.apiKey === undefined) {\n throw new Error(\n 'DeepSeek API key is required, whether as an argument or as $DEEPSEEK_API_KEY',\n );\n }\n\n return new LLM({\n model: 'deepseek-chat',\n baseURL: 'https://api.deepseek.com/v1',\n ...opts,\n });\n }\n\n /**\n * Create a new instance of OctoAI LLM.\n *\n * @remarks\n * `apiKey` must be set to your OctoAI API key, either using the argument or by setting the\n * `OCTOAI_TOKEN` environment variable.\n */\n static withOcto(\n opts: Partial<{\n model: string | OctoChatModels;\n apiKey?: string;\n baseURL?: string;\n user?: string;\n temperature?: number;\n client: OpenAI;\n }> = {},\n ): LLM {\n opts.apiKey = opts.apiKey || process.env.OCTOAI_TOKEN;\n if (opts.apiKey === undefined) {\n throw new Error('OctoAI API key is required, whether as an argument or as $OCTOAI_TOKEN');\n }\n\n return new LLM({\n model: 'llama-2-13b-chat',\n baseURL: 'https://text.octoai.run/v1',\n ...opts,\n });\n }\n\n /** Create a new instance of Ollama LLM. */\n static withOllama(\n opts: Partial<{\n model: string;\n baseURL?: string;\n temperature?: number;\n client: OpenAI;\n }> = {},\n ): LLM {\n return new LLM({\n model: 'llama3.1',\n baseURL: 'http://localhost:11434/v1',\n apiKey: 'ollama',\n ...opts,\n });\n }\n\n /**\n * Create a new instance of PerplexityAI LLM.\n *\n * @remarks\n * `apiKey` must be set to your PerplexityAI API key, either using the argument or by setting the\n * `PERPLEXITY_API_KEY` environment variable.\n */\n static withPerplexity(\n opts: Partial<{\n model: string | PerplexityChatModels;\n apiKey?: string;\n baseURL?: string;\n user?: string;\n temperature?: number;\n client: OpenAI;\n }> = {},\n ): LLM {\n opts.apiKey = opts.apiKey || process.env.PERPLEXITY_API_KEY;\n if (opts.apiKey === undefined) {\n throw new Error(\n 'PerplexityAI API key is required, whether as an argument or as $PERPLEXITY_API_KEY',\n );\n }\n\n return new LLM({\n model: 'llama-3.1-sonar-small-128k-chat',\n baseURL: 'https://api.perplexity.ai',\n ...opts,\n });\n }\n\n /**\n * Create a new instance of TogetherAI LLM.\n *\n * @remarks\n * `apiKey` must be set to your TogetherAI API key, either using the argument or by setting the\n * `TOGETHER_API_KEY` environment variable.\n */\n static withTogether(\n opts: Partial<{\n model: string | TogetherChatModels;\n apiKey?: string;\n baseURL?: string;\n user?: string;\n temperature?: number;\n client: OpenAI;\n }> = {},\n ): LLM {\n opts.apiKey = opts.apiKey || process.env.TOGETHER_API_KEY;\n if (opts.apiKey === undefined) {\n throw new Error(\n 'TogetherAI API key is required, whether as an argument or as $TOGETHER_API_KEY',\n );\n }\n\n return new LLM({\n model: 'meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo',\n baseURL: 'https://api.together.xyz/v1',\n ...opts,\n });\n }\n\n /**\n * Create a new instance of Telnyx LLM.\n *\n * @remarks\n * `apiKey` must be set to your Telnyx API key, either using the argument or by setting the\n * `TELNYX_API_KEY` environment variable.\n */\n static withTelnyx(\n opts: Partial<{\n model: string | TelnyxChatModels;\n apiKey?: string;\n baseURL?: string;\n user?: string;\n temperature?: number;\n client: OpenAI;\n }> = {},\n ): LLM {\n opts.apiKey = opts.apiKey || process.env.TELNYX_API_KEY;\n if (opts.apiKey === undefined) {\n throw new Error('Telnyx API key is required, whether as an argument or as $TELNYX_API_KEY');\n }\n\n return new LLM({\n model: 'meta-llama/Meta-Llama-3.1-70B-Instruct',\n baseURL: 'https://api.telnyx.com/v2/ai',\n ...opts,\n });\n }\n\n /**\n * Create a new instance of Meta Llama LLM.\n *\n * @remarks\n * `apiKey` must be set to your Meta Llama API key, either using the argument or by setting the\n * `LLAMA_API_KEY` environment variable.\n */\n static withMeta(\n opts: Partial<{\n apiKey?: string;\n baseURL?: string;\n client?: OpenAI;\n model?: string | MetaChatModels;\n temperature?: number;\n user?: string;\n }> = {},\n ): LLM {\n opts.apiKey = opts.apiKey || process.env.LLAMA_API_KEY;\n opts.baseURL = opts.baseURL || 'https://api.llama.com/compat/v1/';\n opts.model = opts.model || 'Llama-4-Maverick-17B-128E-Instruct-FP8';\n\n if (opts.apiKey === undefined) {\n throw new Error(\n 'Meta Llama API key is required, either as argument or set LLAMA_API_KEY environment variable',\n );\n }\n\n return new LLM(opts);\n }\n\n /**\n * Create a new instance of OVHcloud AI Endpoints LLM.\n *\n * @remarks\n * `apiKey` must be set to your OVHcloud AI Endpoints API key, either using the argument or by setting the\n * `OVHCLOUD_API_KEY` environment variable.\n */\n static withOVHcloud(opts: Partial<LLMOptions> = {}): LLM {\n opts.apiKey = opts.apiKey || process.env.OVHCLOUD_API_KEY;\n if (opts.apiKey === undefined) {\n throw new Error(\n 'OVHcloud AI Endpoints API key is required, whether as an argument or as $OVHCLOUD_API_KEY',\n );\n }\n\n return new LLM({\n model: 'gpt-oss-120b',\n baseURL: 'https://oai.endpoints.kepler.ai.cloud.ovh.net/v1',\n ...opts,\n });\n }\n\n chat({\n chatCtx,\n toolCtx: toolCtxInput,\n connOptions = DEFAULT_API_CONNECT_OPTIONS,\n parallelToolCalls,\n toolChoice,\n extraKwargs,\n }: {\n chatCtx: llm.ChatContext;\n toolCtx?: llm.ToolContextLike;\n connOptions?: APIConnectOptions;\n parallelToolCalls?: boolean;\n toolChoice?: llm.ToolChoice;\n extraKwargs?: Record<string, unknown>;\n }): LLMStream {\n const toolCtx = llm.toToolContext(toolCtxInput);\n const extras: Record<string, unknown> = { ...extraKwargs };\n\n if (this.#opts.metadata) {\n extras.metadata = this.#opts.metadata;\n }\n\n if (this.#opts.user) {\n extras.user = this.#opts.user;\n }\n\n if (this.#opts.maxCompletionTokens) {\n extras.max_completion_tokens = this.#opts.maxCompletionTokens;\n }\n\n if (this.#opts.temperature) {\n extras.temperature = this.#opts.temperature;\n }\n\n if (this.#opts.topP !== undefined) {\n extras.top_p = this.#opts.topP;\n }\n\n if (this.#opts.serviceTier) {\n extras.service_tier = this.#opts.serviceTier;\n }\n\n if (this.#opts.store !== undefined) {\n extras.store = this.#opts.store;\n }\n\n if (this.#opts.reasoningEffort !== undefined) {\n extras.reasoning_effort = this.#opts.reasoningEffort;\n }\n\n parallelToolCalls =\n parallelToolCalls !== undefined ? parallelToolCalls : this.#opts.parallelToolCalls;\n if (\n toolCtx &&\n Object.keys(toolCtx.functionTools).length > 0 &&\n parallelToolCalls !== undefined\n ) {\n extras.parallel_tool_calls = parallelToolCalls;\n }\n\n toolChoice = toolChoice !== undefined ? toolChoice : this.#opts.toolChoice;\n if (toolChoice) {\n extras.tool_choice = toolChoice;\n }\n\n return new LLMStream(this as unknown as inference.LLM, {\n model: this.#opts.model,\n providerFmt: this.#providerFmt,\n client: this.#client as any,\n chatCtx,\n toolCtx,\n connOptions,\n modelOptions: extras,\n strictToolSchema: this.#opts.strictToolSchema || false,\n gatewayOptions: undefined, // OpenAI plugin doesn't use gateway authentication\n });\n }\n}\n\nexport class LLMStream extends inference.LLMStream {}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAIA,oBAA4D;AAC5D,oBAAoC;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OAAO,KAAK,MAAM;AAAA,MAClB,aAAa,KAAK;AAAA,MAClB,QAAQ,KAAK;AAAA,MACb;AAAA,MACA;AAAA,MACA;AAAA,MACA,cAAc;AAAA,MACd,kBAAkB,KAAK,MAAM,oBAAoB;AAAA,MACjD,gBAAgB;AAAA;AAAA,IAClB,CAAC;AAAA,EACH;AACF;AAEO,MAAM,kBAAkB,wBAAU,UAAU;AAAC;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/llm.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2025 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport type { APIConnectOptions } from '@livekit/agents';\nimport { DEFAULT_API_CONNECT_OPTIONS, inference, llm } from '@livekit/agents';\nimport { AzureOpenAI, OpenAI } from 'openai';\nimport type {\n CerebrasChatModels,\n ChatModels,\n DeepSeekChatModels,\n GroqChatModels,\n MetaChatModels,\n OctoChatModels,\n PerplexityChatModels,\n ReasoningEffort,\n TelnyxChatModels,\n TogetherChatModels,\n XAIChatModels,\n} from './models.js';\nimport { defaultReasoningEffort } from './models.js';\n\nexport interface LLMOptions {\n model: string | ChatModels;\n apiKey?: string;\n baseURL?: string;\n user?: string;\n temperature?: number;\n topP?: number;\n client?: OpenAI;\n toolChoice?: llm.ToolChoice;\n parallelToolCalls?: boolean;\n metadata?: Record<string, string>;\n maxCompletionTokens?: number;\n serviceTier?: string;\n store?: boolean;\n reasoningEffort?: ReasoningEffort | 'xhigh' | 'max';\n safetyIdentifier?: string;\n promptCacheKey?: string;\n strictToolSchema?: boolean;\n}\n\nconst defaultLLMOptions: LLMOptions = {\n model: 'gpt-4.1',\n apiKey: process.env.OPENAI_API_KEY,\n parallelToolCalls: true,\n strictToolSchema: false,\n};\n\nconst defaultAzureLLMOptions: LLMOptions = {\n model: 'gpt-4.1',\n apiKey: process.env.AZURE_API_KEY,\n strictToolSchema: false,\n};\n\nexport class LLM extends llm.LLM {\n #opts: LLMOptions;\n #client: OpenAI;\n #providerFmt: llm.ProviderFormat;\n\n /**\n * Create a new instance of OpenAI LLM.\n *\n * @remarks\n * `apiKey` must be set to your OpenAI API key, either using the argument or by setting the\n * `OPENAI_API_KEY` environment variable.\n */\n constructor(\n opts: Partial<LLMOptions> = defaultLLMOptions,\n providerFmt: llm.ProviderFormat = 'openai',\n ) {\n super();\n\n this.#opts = { ...defaultLLMOptions, ...opts };\n this.#opts.reasoningEffort ??= defaultReasoningEffort(this.#opts.model);\n this.#providerFmt = providerFmt;\n if (this.#opts.apiKey === undefined && !this.#opts.client) {\n throw new Error('OpenAI API key is required, whether as an argument or as $OPENAI_API_KEY');\n }\n\n this.#client =\n this.#opts.client ||\n new OpenAI({\n baseURL: this.#opts.baseURL,\n maxRetries: 0,\n apiKey: this.#opts.apiKey,\n });\n }\n\n label(): string {\n return 'openai.LLM';\n }\n\n get model(): string {\n return this.#opts.model;\n }\n\n get provider(): string {\n try {\n const url = new URL(this.#client.baseURL);\n return url.host;\n } catch {\n return 'api.openai.com';\n }\n }\n\n protected override async _prewarmImpl(signal: AbortSignal): Promise<void> {\n await this.#client.models.list({ signal });\n }\n\n /**\n * Create a new instance of OpenAI LLM with Azure.\n *\n * @remarks\n * This automatically infers the following arguments from their corresponding environment variables if they are not provided:\n * - `apiKey` from `AZURE_OPENAI_API_KEY`\n * - `organization` from `OPENAI_ORG_ID`\n * - `project` from `OPENAI_PROJECT_ID`\n * - `azureAdToken` from `AZURE_OPENAI_AD_TOKEN`\n * - `apiVersion` from `OPENAI_API_VERSION`\n * - `azureEndpoint` from `AZURE_OPENAI_ENDPOINT`\n */\n static withAzure(\n opts: {\n model: string | ChatModels;\n azureEndpoint?: string;\n azureDeployment?: string;\n apiVersion?: string;\n apiKey?: string;\n azureAdToken?: string;\n azureAdTokenProvider?: () => Promise<string>;\n organization?: string;\n project?: string;\n baseURL?: string;\n user?: string;\n temperature?: number;\n } = defaultAzureLLMOptions,\n ): LLM {\n opts = { ...defaultAzureLLMOptions, ...opts };\n if (opts.apiKey === undefined) {\n throw new Error('Azure API key is required, whether as an argument or as $AZURE_API_KEY');\n }\n\n return new LLM({\n temperature: opts.temperature,\n user: opts.user,\n client: new AzureOpenAI({ ...opts, maxRetries: 0 }),\n });\n }\n\n /**\n * Create a new instance of Cerebras LLM.\n *\n * @remarks\n * `apiKey` must be set to your Cerebras API key, either using the argument or by setting the\n * `CEREBRAS_API_KEY` environment variable.\n */\n static withCerebras(\n opts: Partial<{\n model: string | CerebrasChatModels;\n apiKey?: string;\n baseURL?: string;\n user?: string;\n temperature?: number;\n client: OpenAI;\n }> = {},\n ): LLM {\n opts.apiKey = opts.apiKey || process.env.CEREBRAS_API_KEY;\n if (opts.apiKey === undefined) {\n throw new Error(\n 'Cerebras API key is required, whether as an argument or as $CEREBRAS_API_KEY',\n );\n }\n\n return new LLM({\n model: 'gpt-oss-120b',\n baseURL: 'https://api.cerebras.ai/v1',\n ...opts,\n });\n }\n\n /**\n * Create a new instance of Fireworks LLM.\n *\n * @remarks\n * `apiKey` must be set to your Fireworks API key, either using the argument or by setting the\n * `FIREWORKS_API_KEY` environment variable.\n */\n static withFireworks(opts: Partial<LLMOptions> = {}): LLM {\n opts.apiKey = opts.apiKey || process.env.FIREWORKS_API_KEY;\n if (opts.apiKey === undefined) {\n throw new Error(\n 'Fireworks API key is required, whether as an argument or as $FIREWORKS_API_KEY',\n );\n }\n\n return new LLM({\n model: 'accounts/fireworks/models/llama-v3p1-70b-instruct',\n baseURL: 'https://api.fireworks.ai/inference/v1',\n ...opts,\n });\n }\n\n /**\n * Create a new instance of xAI LLM.\n *\n * @remarks\n * `apiKey` must be set to your xAI API key, either using the argument or by setting the\n * `XAI_API_KEY` environment variable.\n */\n static withXAI(\n opts: Partial<{\n model: string | XAIChatModels;\n apiKey?: string;\n baseURL?: string;\n user?: string;\n temperature?: number;\n client: OpenAI;\n }> = {},\n ): LLM {\n opts.apiKey = opts.apiKey || process.env.XAI_API_KEY;\n if (opts.apiKey === undefined) {\n throw new Error('xAI API key is required, whether as an argument or as $XAI_API_KEY');\n }\n\n return new LLM({\n model: 'grok-2-public',\n baseURL: 'https://api.x.ai/v1',\n ...opts,\n });\n }\n\n /**\n * Create a new instance of Groq LLM.\n *\n * @remarks\n * `apiKey` must be set to your Groq API key, either using the argument or by setting the\n * `GROQ_API_KEY` environment variable.\n */\n static withGroq(\n opts: Partial<{\n model: string | GroqChatModels;\n apiKey?: string;\n baseURL?: string;\n user?: string;\n temperature?: number;\n client: OpenAI;\n }> = {},\n ): LLM {\n opts.apiKey = opts.apiKey || process.env.GROQ_API_KEY;\n if (opts.apiKey === undefined) {\n throw new Error('Groq API key is required, whether as an argument or as $GROQ_API_KEY');\n }\n\n return new LLM({\n model: 'openai/gpt-oss-120b',\n baseURL: 'https://api.groq.com/openai/v1',\n ...opts,\n });\n }\n\n /**\n * Create a new instance of DeepSeek LLM.\n *\n * @remarks\n * `apiKey` must be set to your DeepSeek API key, either using the argument or by setting the\n * `DEEPSEEK_API_KEY` environment variable.\n */\n static withDeepSeek(\n opts: Partial<{\n model: string | DeepSeekChatModels;\n apiKey?: string;\n baseURL?: string;\n user?: string;\n temperature?: number;\n client: OpenAI;\n }> = {},\n ): LLM {\n opts.apiKey = opts.apiKey || process.env.DEEPSEEK_API_KEY;\n if (opts.apiKey === undefined) {\n throw new Error(\n 'DeepSeek API key is required, whether as an argument or as $DEEPSEEK_API_KEY',\n );\n }\n\n return new LLM({\n model: 'deepseek-chat',\n baseURL: 'https://api.deepseek.com/v1',\n ...opts,\n });\n }\n\n /**\n * Create a new instance of OctoAI LLM.\n *\n * @remarks\n * `apiKey` must be set to your OctoAI API key, either using the argument or by setting the\n * `OCTOAI_TOKEN` environment variable.\n */\n static withOcto(\n opts: Partial<{\n model: string | OctoChatModels;\n apiKey?: string;\n baseURL?: string;\n user?: string;\n temperature?: number;\n client: OpenAI;\n }> = {},\n ): LLM {\n opts.apiKey = opts.apiKey || process.env.OCTOAI_TOKEN;\n if (opts.apiKey === undefined) {\n throw new Error('OctoAI API key is required, whether as an argument or as $OCTOAI_TOKEN');\n }\n\n return new LLM({\n model: 'llama-2-13b-chat',\n baseURL: 'https://text.octoai.run/v1',\n ...opts,\n });\n }\n\n /** Create a new instance of Ollama LLM. */\n static withOllama(\n opts: Partial<{\n model: string;\n baseURL?: string;\n temperature?: number;\n client: OpenAI;\n }> = {},\n ): LLM {\n return new LLM({\n model: 'llama3.1',\n baseURL: 'http://localhost:11434/v1',\n apiKey: 'ollama',\n ...opts,\n });\n }\n\n /**\n * Create a new instance of PerplexityAI LLM.\n *\n * @remarks\n * `apiKey` must be set to your PerplexityAI API key, either using the argument or by setting the\n * `PERPLEXITY_API_KEY` environment variable.\n */\n static withPerplexity(\n opts: Partial<{\n model: string | PerplexityChatModels;\n apiKey?: string;\n baseURL?: string;\n user?: string;\n temperature?: number;\n client: OpenAI;\n }> = {},\n ): LLM {\n opts.apiKey = opts.apiKey || process.env.PERPLEXITY_API_KEY;\n if (opts.apiKey === undefined) {\n throw new Error(\n 'PerplexityAI API key is required, whether as an argument or as $PERPLEXITY_API_KEY',\n );\n }\n\n return new LLM({\n model: 'llama-3.1-sonar-small-128k-chat',\n baseURL: 'https://api.perplexity.ai',\n ...opts,\n });\n }\n\n /**\n * Create a new instance of TogetherAI LLM.\n *\n * @remarks\n * `apiKey` must be set to your TogetherAI API key, either using the argument or by setting the\n * `TOGETHER_API_KEY` environment variable.\n */\n static withTogether(\n opts: Partial<{\n model: string | TogetherChatModels;\n apiKey?: string;\n baseURL?: string;\n user?: string;\n temperature?: number;\n client: OpenAI;\n }> = {},\n ): LLM {\n opts.apiKey = opts.apiKey || process.env.TOGETHER_API_KEY;\n if (opts.apiKey === undefined) {\n throw new Error(\n 'TogetherAI API key is required, whether as an argument or as $TOGETHER_API_KEY',\n );\n }\n\n return new LLM({\n model: 'meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo',\n baseURL: 'https://api.together.xyz/v1',\n ...opts,\n });\n }\n\n /**\n * Create a new instance of Telnyx LLM.\n *\n * @remarks\n * `apiKey` must be set to your Telnyx API key, either using the argument or by setting the\n * `TELNYX_API_KEY` environment variable.\n */\n static withTelnyx(\n opts: Partial<{\n model: string | TelnyxChatModels;\n apiKey?: string;\n baseURL?: string;\n user?: string;\n temperature?: number;\n client: OpenAI;\n }> = {},\n ): LLM {\n opts.apiKey = opts.apiKey || process.env.TELNYX_API_KEY;\n if (opts.apiKey === undefined) {\n throw new Error('Telnyx API key is required, whether as an argument or as $TELNYX_API_KEY');\n }\n\n return new LLM({\n model: 'meta-llama/Meta-Llama-3.1-70B-Instruct',\n baseURL: 'https://api.telnyx.com/v2/ai',\n ...opts,\n });\n }\n\n /**\n * Create a new instance of Meta Llama LLM.\n *\n * @remarks\n * `apiKey` must be set to your Meta Llama API key, either using the argument or by setting the\n * `LLAMA_API_KEY` environment variable.\n */\n static withMeta(\n opts: Partial<{\n apiKey?: string;\n baseURL?: string;\n client?: OpenAI;\n model?: string | MetaChatModels;\n temperature?: number;\n user?: string;\n }> = {},\n ): LLM {\n opts.apiKey = opts.apiKey || process.env.LLAMA_API_KEY;\n opts.baseURL = opts.baseURL || 'https://api.llama.com/compat/v1/';\n opts.model = opts.model || 'Llama-4-Maverick-17B-128E-Instruct-FP8';\n\n if (opts.apiKey === undefined) {\n throw new Error(\n 'Meta Llama API key is required, either as argument or set LLAMA_API_KEY environment variable',\n );\n }\n\n return new LLM(opts);\n }\n\n /**\n * Create a new instance of OVHcloud AI Endpoints LLM.\n *\n * @remarks\n * `apiKey` must be set to your OVHcloud AI Endpoints API key, either using the argument or by setting the\n * `OVHCLOUD_API_KEY` environment variable.\n */\n static withOVHcloud(opts: Partial<LLMOptions> = {}): LLM {\n opts.apiKey = opts.apiKey || process.env.OVHCLOUD_API_KEY;\n if (opts.apiKey === undefined) {\n throw new Error(\n 'OVHcloud AI Endpoints API key is required, whether as an argument or as $OVHCLOUD_API_KEY',\n );\n }\n\n return new LLM({\n model: 'gpt-oss-120b',\n baseURL: 'https://oai.endpoints.kepler.ai.cloud.ovh.net/v1',\n ...opts,\n });\n }\n\n /**\n * Create a new instance of a Modal LLM.\n *\n * @remarks\n * `model` is the endpoint hostname, e.g. `my-endpoint.us-west.modal.direct`.\n * `baseURL` defaults to the shared inference gateway in the hostname's region and can be set to\n * a dedicated Endpoint or self-hosted server URL.\n *\n * For authenticated Modal endpoints, pass your proxy token as `apiKey`, or set\n * `MODAL_PROXY_TOKEN` or the `MODAL_PROXY_TOKEN_ID` and `MODAL_PROXY_TOKEN_SECRET` pair.\n * A supplied `client` uses its own URL and credentials.\n */\n static withModal(opts: {\n model: string;\n apiKey?: string;\n baseURL?: string;\n client?: OpenAI;\n user?: string;\n temperature?: number;\n parallelToolCalls?: boolean;\n toolChoice?: llm.ToolChoice;\n reasoningEffort?: LLMOptions['reasoningEffort'];\n safetyIdentifier?: string;\n promptCacheKey?: string;\n topP?: number;\n }): LLM {\n let apiKey = opts.apiKey || process.env.MODAL_PROXY_TOKEN;\n if (!apiKey) {\n const tokenId = process.env.MODAL_PROXY_TOKEN_ID;\n const tokenSecret = process.env.MODAL_PROXY_TOKEN_SECRET;\n if (tokenId && tokenSecret) {\n apiKey = `${tokenId}.${tokenSecret}`;\n }\n }\n\n let baseURL = opts.baseURL;\n if (baseURL === undefined) {\n const region = opts.model.endsWith('.modal.direct')\n ? opts.model.split('.').at(-3)\n : 'us-west';\n baseURL = `https://inference.${region}.modal.direct/v1`;\n }\n\n return new LLM({\n parallelToolCalls: undefined,\n ...opts,\n apiKey: apiKey || 'modal',\n baseURL,\n toolChoice: opts.toolChoice ?? 'auto',\n });\n }\n\n chat({\n chatCtx,\n toolCtx: toolCtxInput,\n connOptions = DEFAULT_API_CONNECT_OPTIONS,\n parallelToolCalls,\n toolChoice,\n extraKwargs,\n }: {\n chatCtx: llm.ChatContext;\n toolCtx?: llm.ToolContextLike;\n connOptions?: APIConnectOptions;\n parallelToolCalls?: boolean;\n toolChoice?: llm.ToolChoice;\n extraKwargs?: Record<string, unknown>;\n }): LLMStream {\n const toolCtx = llm.toToolContext(toolCtxInput);\n const extras: Record<string, unknown> = { ...extraKwargs };\n\n if (this.#opts.metadata) {\n extras.metadata = this.#opts.metadata;\n }\n\n if (this.#opts.user) {\n extras.user = this.#opts.user;\n }\n\n if (this.#opts.maxCompletionTokens) {\n extras.max_completion_tokens = this.#opts.maxCompletionTokens;\n }\n\n if (this.#opts.temperature !== undefined) {\n extras.temperature = this.#opts.temperature;\n }\n\n if (this.#opts.topP !== undefined) {\n extras.top_p = this.#opts.topP;\n }\n\n if (this.#opts.serviceTier) {\n extras.service_tier = this.#opts.serviceTier;\n }\n\n if (this.#opts.store !== undefined) {\n extras.store = this.#opts.store;\n }\n\n if (this.#opts.reasoningEffort !== undefined) {\n extras.reasoning_effort = this.#opts.reasoningEffort;\n }\n\n if (this.#opts.safetyIdentifier !== undefined) {\n extras.safety_identifier = this.#opts.safetyIdentifier;\n }\n\n if (this.#opts.promptCacheKey !== undefined) {\n extras.prompt_cache_key = this.#opts.promptCacheKey;\n }\n\n parallelToolCalls =\n parallelToolCalls !== undefined ? parallelToolCalls : this.#opts.parallelToolCalls;\n if (\n toolCtx &&\n Object.keys(toolCtx.functionTools).length > 0 &&\n parallelToolCalls !== undefined\n ) {\n extras.parallel_tool_calls = parallelToolCalls;\n }\n\n toolChoice = toolChoice !== undefined ? toolChoice : this.#opts.toolChoice;\n if (toolChoice) {\n extras.tool_choice = toolChoice;\n }\n\n return new LLMStream(this as unknown as inference.LLM, {\n model: this.#opts.model,\n providerFmt: this.#providerFmt,\n client: this.#client as any,\n chatCtx,\n toolCtx,\n connOptions,\n modelOptions: extras,\n strictToolSchema: this.#opts.strictToolSchema || false,\n gatewayOptions: undefined, // OpenAI plugin doesn't use gateway authentication\n });\n }\n}\n\nexport class LLMStream extends inference.LLMStream {}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAIA,oBAA4D;AAC5D,oBAAoC;AAcpC,oBAAuC;AAsBvC,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aAAO,cAAc,KAAK,MAAM;AAAA,IAClC;AAEA,QAAI,KAAK,MAAM,SAAS,QAAW;AACjC,aAAO,QAAQ,KAAK,MAAM;AAAA,IAC5B;AAEA,QAAI,KAAK,MAAM,aAAa;AAC1B,aAAO,eAAe,KAAK,MAAM;AAAA,IACnC;AAEA,QAAI,KAAK,MAAM,UAAU,QAAW;AAClC,aAAO,QAAQ,KAAK,MAAM;AAAA,IAC5B;AAEA,QAAI,KAAK,MAAM,oBAAoB,QAAW;AAC5C,aAAO,mBAAmB,KAAK,MAAM;AAAA,IACvC;AAEA,QAAI,KAAK,MAAM,qBAAqB,QAAW;AAC7C,aAAO,oBAAoB,KAAK,MAAM;AAAA,IACxC;AAEA,QAAI,KAAK,MAAM,mBAAmB,QAAW;AAC3C,aAAO,mBAAmB,KAAK,MAAM;AAAA,IACvC;AAEA,wBACE,sBAAsB,SAAY,oBAAoB,KAAK,MAAM;AACnE,QACE,WACA,OAAO,KAAK,QAAQ,aAAa,EAAE,SAAS,KAC5C,sBAAsB,QACtB;AACA,aAAO,sBAAsB;AAAA,IAC/B;AAEA,iBAAa,eAAe,SAAY,aAAa,KAAK,MAAM;AAChE,QAAI,YAAY;AACd,aAAO,cAAc;AAAA,IACvB;AAEA,WAAO,IAAI,UAAU,MAAkC;AAAA,MACrD,OAAO,KAAK,MAAM;AAAA,MAClB,aAAa,KAAK;AAAA,MAClB,QAAQ,KAAK;AAAA,MACb;AAAA,MACA;AAAA,MACA;AAAA,MACA,cAAc;AAAA,MACd,kBAAkB,KAAK,MAAM,oBAAoB;AAAA,MACjD,gBAAgB;AAAA;AAAA,IAClB,CAAC;AAAA,EACH;AACF;AAEO,MAAM,kBAAkB,wBAAU,UAAU;AAAC;","names":[]}
|
package/dist/llm.d.cts
CHANGED
|
@@ -16,7 +16,9 @@ export interface LLMOptions {
|
|
|
16
16
|
maxCompletionTokens?: number;
|
|
17
17
|
serviceTier?: string;
|
|
18
18
|
store?: boolean;
|
|
19
|
-
reasoningEffort?: ReasoningEffort;
|
|
19
|
+
reasoningEffort?: ReasoningEffort | 'xhigh' | 'max';
|
|
20
|
+
safetyIdentifier?: string;
|
|
21
|
+
promptCacheKey?: string;
|
|
20
22
|
strictToolSchema?: boolean;
|
|
21
23
|
}
|
|
22
24
|
export declare class LLM extends llm.LLM {
|
|
@@ -217,6 +219,32 @@ export declare class LLM extends llm.LLM {
|
|
|
217
219
|
* `OVHCLOUD_API_KEY` environment variable.
|
|
218
220
|
*/
|
|
219
221
|
static withOVHcloud(opts?: Partial<LLMOptions>): LLM;
|
|
222
|
+
/**
|
|
223
|
+
* Create a new instance of a Modal LLM.
|
|
224
|
+
*
|
|
225
|
+
* @remarks
|
|
226
|
+
* `model` is the endpoint hostname, e.g. `my-endpoint.us-west.modal.direct`.
|
|
227
|
+
* `baseURL` defaults to the shared inference gateway in the hostname's region and can be set to
|
|
228
|
+
* a dedicated Endpoint or self-hosted server URL.
|
|
229
|
+
*
|
|
230
|
+
* For authenticated Modal endpoints, pass your proxy token as `apiKey`, or set
|
|
231
|
+
* `MODAL_PROXY_TOKEN` or the `MODAL_PROXY_TOKEN_ID` and `MODAL_PROXY_TOKEN_SECRET` pair.
|
|
232
|
+
* A supplied `client` uses its own URL and credentials.
|
|
233
|
+
*/
|
|
234
|
+
static withModal(opts: {
|
|
235
|
+
model: string;
|
|
236
|
+
apiKey?: string;
|
|
237
|
+
baseURL?: string;
|
|
238
|
+
client?: OpenAI;
|
|
239
|
+
user?: string;
|
|
240
|
+
temperature?: number;
|
|
241
|
+
parallelToolCalls?: boolean;
|
|
242
|
+
toolChoice?: llm.ToolChoice;
|
|
243
|
+
reasoningEffort?: LLMOptions['reasoningEffort'];
|
|
244
|
+
safetyIdentifier?: string;
|
|
245
|
+
promptCacheKey?: string;
|
|
246
|
+
topP?: number;
|
|
247
|
+
}): LLM;
|
|
220
248
|
chat({ chatCtx, toolCtx: toolCtxInput, connOptions, parallelToolCalls, toolChoice, extraKwargs, }: {
|
|
221
249
|
chatCtx: llm.ChatContext;
|
|
222
250
|
toolCtx?: llm.ToolContextLike;
|
package/dist/llm.d.ts
CHANGED
|
@@ -16,7 +16,9 @@ export interface LLMOptions {
|
|
|
16
16
|
maxCompletionTokens?: number;
|
|
17
17
|
serviceTier?: string;
|
|
18
18
|
store?: boolean;
|
|
19
|
-
reasoningEffort?: ReasoningEffort;
|
|
19
|
+
reasoningEffort?: ReasoningEffort | 'xhigh' | 'max';
|
|
20
|
+
safetyIdentifier?: string;
|
|
21
|
+
promptCacheKey?: string;
|
|
20
22
|
strictToolSchema?: boolean;
|
|
21
23
|
}
|
|
22
24
|
export declare class LLM extends llm.LLM {
|
|
@@ -217,6 +219,32 @@ export declare class LLM extends llm.LLM {
|
|
|
217
219
|
* `OVHCLOUD_API_KEY` environment variable.
|
|
218
220
|
*/
|
|
219
221
|
static withOVHcloud(opts?: Partial<LLMOptions>): LLM;
|
|
222
|
+
/**
|
|
223
|
+
* Create a new instance of a Modal LLM.
|
|
224
|
+
*
|
|
225
|
+
* @remarks
|
|
226
|
+
* `model` is the endpoint hostname, e.g. `my-endpoint.us-west.modal.direct`.
|
|
227
|
+
* `baseURL` defaults to the shared inference gateway in the hostname's region and can be set to
|
|
228
|
+
* a dedicated Endpoint or self-hosted server URL.
|
|
229
|
+
*
|
|
230
|
+
* For authenticated Modal endpoints, pass your proxy token as `apiKey`, or set
|
|
231
|
+
* `MODAL_PROXY_TOKEN` or the `MODAL_PROXY_TOKEN_ID` and `MODAL_PROXY_TOKEN_SECRET` pair.
|
|
232
|
+
* A supplied `client` uses its own URL and credentials.
|
|
233
|
+
*/
|
|
234
|
+
static withModal(opts: {
|
|
235
|
+
model: string;
|
|
236
|
+
apiKey?: string;
|
|
237
|
+
baseURL?: string;
|
|
238
|
+
client?: OpenAI;
|
|
239
|
+
user?: string;
|
|
240
|
+
temperature?: number;
|
|
241
|
+
parallelToolCalls?: boolean;
|
|
242
|
+
toolChoice?: llm.ToolChoice;
|
|
243
|
+
reasoningEffort?: LLMOptions['reasoningEffort'];
|
|
244
|
+
safetyIdentifier?: string;
|
|
245
|
+
promptCacheKey?: string;
|
|
246
|
+
topP?: number;
|
|
247
|
+
}): LLM;
|
|
220
248
|
chat({ chatCtx, toolCtx: toolCtxInput, connOptions, parallelToolCalls, toolChoice, extraKwargs, }: {
|
|
221
249
|
chatCtx: llm.ChatContext;
|
|
222
250
|
toolCtx?: llm.ToolContextLike;
|
package/dist/llm.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"llm.d.ts","sourceRoot":"","sources":["../src/llm.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AACzD,OAAO,EAA+B,SAAS,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AAC9E,OAAO,EAAe,MAAM,EAAE,MAAM,QAAQ,CAAC;AAC7C,OAAO,KAAK,EACV,kBAAkB,EAClB,UAAU,EACV,kBAAkB,EAClB,cAAc,EACd,cAAc,EACd,cAAc,EACd,oBAAoB,EACpB,eAAe,EACf,gBAAgB,EAChB,kBAAkB,EAClB,aAAa,EACd,MAAM,aAAa,CAAC;AAGrB,MAAM,WAAW,UAAU;IACzB,KAAK,EAAE,MAAM,GAAG,UAAU,CAAC;IAC3B,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,UAAU,CAAC,EAAE,GAAG,CAAC,UAAU,CAAC;IAC5B,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAC5B,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAClC,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B,WAAW,CAAC,EAA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;QAC5B,UAAU,CAAC,EAAE,GAAG,CAAC,UAAU,CAAC;QAC5B,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;KACvC,GAAG,SAAS;CAuEd;AAED,qBAAa,SAAU,SAAQ,SAAS,CAAC,SAAS;CAAG"}
|
package/dist/llm.js
CHANGED
|
@@ -296,6 +296,40 @@ class LLM extends llm.LLM {
|
|
|
296
296
|
...opts
|
|
297
297
|
});
|
|
298
298
|
}
|
|
299
|
+
/**
|
|
300
|
+
* Create a new instance of a Modal LLM.
|
|
301
|
+
*
|
|
302
|
+
* @remarks
|
|
303
|
+
* `model` is the endpoint hostname, e.g. `my-endpoint.us-west.modal.direct`.
|
|
304
|
+
* `baseURL` defaults to the shared inference gateway in the hostname's region and can be set to
|
|
305
|
+
* a dedicated Endpoint or self-hosted server URL.
|
|
306
|
+
*
|
|
307
|
+
* For authenticated Modal endpoints, pass your proxy token as `apiKey`, or set
|
|
308
|
+
* `MODAL_PROXY_TOKEN` or the `MODAL_PROXY_TOKEN_ID` and `MODAL_PROXY_TOKEN_SECRET` pair.
|
|
309
|
+
* A supplied `client` uses its own URL and credentials.
|
|
310
|
+
*/
|
|
311
|
+
static withModal(opts) {
|
|
312
|
+
let apiKey = opts.apiKey || process.env.MODAL_PROXY_TOKEN;
|
|
313
|
+
if (!apiKey) {
|
|
314
|
+
const tokenId = process.env.MODAL_PROXY_TOKEN_ID;
|
|
315
|
+
const tokenSecret = process.env.MODAL_PROXY_TOKEN_SECRET;
|
|
316
|
+
if (tokenId && tokenSecret) {
|
|
317
|
+
apiKey = `${tokenId}.${tokenSecret}`;
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
let baseURL = opts.baseURL;
|
|
321
|
+
if (baseURL === void 0) {
|
|
322
|
+
const region = opts.model.endsWith(".modal.direct") ? opts.model.split(".").at(-3) : "us-west";
|
|
323
|
+
baseURL = `https://inference.${region}.modal.direct/v1`;
|
|
324
|
+
}
|
|
325
|
+
return new LLM({
|
|
326
|
+
parallelToolCalls: void 0,
|
|
327
|
+
...opts,
|
|
328
|
+
apiKey: apiKey || "modal",
|
|
329
|
+
baseURL,
|
|
330
|
+
toolChoice: opts.toolChoice ?? "auto"
|
|
331
|
+
});
|
|
332
|
+
}
|
|
299
333
|
chat({
|
|
300
334
|
chatCtx,
|
|
301
335
|
toolCtx: toolCtxInput,
|
|
@@ -315,7 +349,7 @@ class LLM extends llm.LLM {
|
|
|
315
349
|
if (this.#opts.maxCompletionTokens) {
|
|
316
350
|
extras.max_completion_tokens = this.#opts.maxCompletionTokens;
|
|
317
351
|
}
|
|
318
|
-
if (this.#opts.temperature) {
|
|
352
|
+
if (this.#opts.temperature !== void 0) {
|
|
319
353
|
extras.temperature = this.#opts.temperature;
|
|
320
354
|
}
|
|
321
355
|
if (this.#opts.topP !== void 0) {
|
|
@@ -330,6 +364,12 @@ class LLM extends llm.LLM {
|
|
|
330
364
|
if (this.#opts.reasoningEffort !== void 0) {
|
|
331
365
|
extras.reasoning_effort = this.#opts.reasoningEffort;
|
|
332
366
|
}
|
|
367
|
+
if (this.#opts.safetyIdentifier !== void 0) {
|
|
368
|
+
extras.safety_identifier = this.#opts.safetyIdentifier;
|
|
369
|
+
}
|
|
370
|
+
if (this.#opts.promptCacheKey !== void 0) {
|
|
371
|
+
extras.prompt_cache_key = this.#opts.promptCacheKey;
|
|
372
|
+
}
|
|
333
373
|
parallelToolCalls = parallelToolCalls !== void 0 ? parallelToolCalls : this.#opts.parallelToolCalls;
|
|
334
374
|
if (toolCtx && Object.keys(toolCtx.functionTools).length > 0 && parallelToolCalls !== void 0) {
|
|
335
375
|
extras.parallel_tool_calls = parallelToolCalls;
|
package/dist/llm.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/llm.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2025 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport type { APIConnectOptions } from '@livekit/agents';\nimport { DEFAULT_API_CONNECT_OPTIONS, inference, llm } from '@livekit/agents';\nimport { AzureOpenAI, OpenAI } from 'openai';\nimport type {\n CerebrasChatModels,\n ChatModels,\n DeepSeekChatModels,\n GroqChatModels,\n MetaChatModels,\n OctoChatModels,\n PerplexityChatModels,\n ReasoningEffort,\n TelnyxChatModels,\n TogetherChatModels,\n XAIChatModels,\n} from './models.js';\nimport { defaultReasoningEffort } from './models.js';\n\nexport interface LLMOptions {\n model: string | ChatModels;\n apiKey?: string;\n baseURL?: string;\n user?: string;\n temperature?: number;\n topP?: number;\n client?: OpenAI;\n toolChoice?: llm.ToolChoice;\n parallelToolCalls?: boolean;\n metadata?: Record<string, string>;\n maxCompletionTokens?: number;\n serviceTier?: string;\n store?: boolean;\n reasoningEffort?: ReasoningEffort;\n strictToolSchema?: boolean;\n}\n\nconst defaultLLMOptions: LLMOptions = {\n model: 'gpt-4.1',\n apiKey: process.env.OPENAI_API_KEY,\n parallelToolCalls: true,\n strictToolSchema: false,\n};\n\nconst defaultAzureLLMOptions: LLMOptions = {\n model: 'gpt-4.1',\n apiKey: process.env.AZURE_API_KEY,\n strictToolSchema: false,\n};\n\nexport class LLM extends llm.LLM {\n #opts: LLMOptions;\n #client: OpenAI;\n #providerFmt: llm.ProviderFormat;\n\n /**\n * Create a new instance of OpenAI LLM.\n *\n * @remarks\n * `apiKey` must be set to your OpenAI API key, either using the argument or by setting the\n * `OPENAI_API_KEY` environment variable.\n */\n constructor(\n opts: Partial<LLMOptions> = defaultLLMOptions,\n providerFmt: llm.ProviderFormat = 'openai',\n ) {\n super();\n\n this.#opts = { ...defaultLLMOptions, ...opts };\n this.#opts.reasoningEffort ??= defaultReasoningEffort(this.#opts.model);\n this.#providerFmt = providerFmt;\n if (this.#opts.apiKey === undefined && !this.#opts.client) {\n throw new Error('OpenAI API key is required, whether as an argument or as $OPENAI_API_KEY');\n }\n\n this.#client =\n this.#opts.client ||\n new OpenAI({\n baseURL: this.#opts.baseURL,\n maxRetries: 0,\n apiKey: this.#opts.apiKey,\n });\n }\n\n label(): string {\n return 'openai.LLM';\n }\n\n get model(): string {\n return this.#opts.model;\n }\n\n get provider(): string {\n try {\n const url = new URL(this.#client.baseURL);\n return url.host;\n } catch {\n return 'api.openai.com';\n }\n }\n\n protected override async _prewarmImpl(signal: AbortSignal): Promise<void> {\n await this.#client.models.list({ signal });\n }\n\n /**\n * Create a new instance of OpenAI LLM with Azure.\n *\n * @remarks\n * This automatically infers the following arguments from their corresponding environment variables if they are not provided:\n * - `apiKey` from `AZURE_OPENAI_API_KEY`\n * - `organization` from `OPENAI_ORG_ID`\n * - `project` from `OPENAI_PROJECT_ID`\n * - `azureAdToken` from `AZURE_OPENAI_AD_TOKEN`\n * - `apiVersion` from `OPENAI_API_VERSION`\n * - `azureEndpoint` from `AZURE_OPENAI_ENDPOINT`\n */\n static withAzure(\n opts: {\n model: string | ChatModels;\n azureEndpoint?: string;\n azureDeployment?: string;\n apiVersion?: string;\n apiKey?: string;\n azureAdToken?: string;\n azureAdTokenProvider?: () => Promise<string>;\n organization?: string;\n project?: string;\n baseURL?: string;\n user?: string;\n temperature?: number;\n } = defaultAzureLLMOptions,\n ): LLM {\n opts = { ...defaultAzureLLMOptions, ...opts };\n if (opts.apiKey === undefined) {\n throw new Error('Azure API key is required, whether as an argument or as $AZURE_API_KEY');\n }\n\n return new LLM({\n temperature: opts.temperature,\n user: opts.user,\n client: new AzureOpenAI({ ...opts, maxRetries: 0 }),\n });\n }\n\n /**\n * Create a new instance of Cerebras LLM.\n *\n * @remarks\n * `apiKey` must be set to your Cerebras API key, either using the argument or by setting the\n * `CEREBRAS_API_KEY` environment variable.\n */\n static withCerebras(\n opts: Partial<{\n model: string | CerebrasChatModels;\n apiKey?: string;\n baseURL?: string;\n user?: string;\n temperature?: number;\n client: OpenAI;\n }> = {},\n ): LLM {\n opts.apiKey = opts.apiKey || process.env.CEREBRAS_API_KEY;\n if (opts.apiKey === undefined) {\n throw new Error(\n 'Cerebras API key is required, whether as an argument or as $CEREBRAS_API_KEY',\n );\n }\n\n return new LLM({\n model: 'gpt-oss-120b',\n baseURL: 'https://api.cerebras.ai/v1',\n ...opts,\n });\n }\n\n /**\n * Create a new instance of Fireworks LLM.\n *\n * @remarks\n * `apiKey` must be set to your Fireworks API key, either using the argument or by setting the\n * `FIREWORKS_API_KEY` environment variable.\n */\n static withFireworks(opts: Partial<LLMOptions> = {}): LLM {\n opts.apiKey = opts.apiKey || process.env.FIREWORKS_API_KEY;\n if (opts.apiKey === undefined) {\n throw new Error(\n 'Fireworks API key is required, whether as an argument or as $FIREWORKS_API_KEY',\n );\n }\n\n return new LLM({\n model: 'accounts/fireworks/models/llama-v3p1-70b-instruct',\n baseURL: 'https://api.fireworks.ai/inference/v1',\n ...opts,\n });\n }\n\n /**\n * Create a new instance of xAI LLM.\n *\n * @remarks\n * `apiKey` must be set to your xAI API key, either using the argument or by setting the\n * `XAI_API_KEY` environment variable.\n */\n static withXAI(\n opts: Partial<{\n model: string | XAIChatModels;\n apiKey?: string;\n baseURL?: string;\n user?: string;\n temperature?: number;\n client: OpenAI;\n }> = {},\n ): LLM {\n opts.apiKey = opts.apiKey || process.env.XAI_API_KEY;\n if (opts.apiKey === undefined) {\n throw new Error('xAI API key is required, whether as an argument or as $XAI_API_KEY');\n }\n\n return new LLM({\n model: 'grok-2-public',\n baseURL: 'https://api.x.ai/v1',\n ...opts,\n });\n }\n\n /**\n * Create a new instance of Groq LLM.\n *\n * @remarks\n * `apiKey` must be set to your Groq API key, either using the argument or by setting the\n * `GROQ_API_KEY` environment variable.\n */\n static withGroq(\n opts: Partial<{\n model: string | GroqChatModels;\n apiKey?: string;\n baseURL?: string;\n user?: string;\n temperature?: number;\n client: OpenAI;\n }> = {},\n ): LLM {\n opts.apiKey = opts.apiKey || process.env.GROQ_API_KEY;\n if (opts.apiKey === undefined) {\n throw new Error('Groq API key is required, whether as an argument or as $GROQ_API_KEY');\n }\n\n return new LLM({\n model: 'openai/gpt-oss-120b',\n baseURL: 'https://api.groq.com/openai/v1',\n ...opts,\n });\n }\n\n /**\n * Create a new instance of DeepSeek LLM.\n *\n * @remarks\n * `apiKey` must be set to your DeepSeek API key, either using the argument or by setting the\n * `DEEPSEEK_API_KEY` environment variable.\n */\n static withDeepSeek(\n opts: Partial<{\n model: string | DeepSeekChatModels;\n apiKey?: string;\n baseURL?: string;\n user?: string;\n temperature?: number;\n client: OpenAI;\n }> = {},\n ): LLM {\n opts.apiKey = opts.apiKey || process.env.DEEPSEEK_API_KEY;\n if (opts.apiKey === undefined) {\n throw new Error(\n 'DeepSeek API key is required, whether as an argument or as $DEEPSEEK_API_KEY',\n );\n }\n\n return new LLM({\n model: 'deepseek-chat',\n baseURL: 'https://api.deepseek.com/v1',\n ...opts,\n });\n }\n\n /**\n * Create a new instance of OctoAI LLM.\n *\n * @remarks\n * `apiKey` must be set to your OctoAI API key, either using the argument or by setting the\n * `OCTOAI_TOKEN` environment variable.\n */\n static withOcto(\n opts: Partial<{\n model: string | OctoChatModels;\n apiKey?: string;\n baseURL?: string;\n user?: string;\n temperature?: number;\n client: OpenAI;\n }> = {},\n ): LLM {\n opts.apiKey = opts.apiKey || process.env.OCTOAI_TOKEN;\n if (opts.apiKey === undefined) {\n throw new Error('OctoAI API key is required, whether as an argument or as $OCTOAI_TOKEN');\n }\n\n return new LLM({\n model: 'llama-2-13b-chat',\n baseURL: 'https://text.octoai.run/v1',\n ...opts,\n });\n }\n\n /** Create a new instance of Ollama LLM. */\n static withOllama(\n opts: Partial<{\n model: string;\n baseURL?: string;\n temperature?: number;\n client: OpenAI;\n }> = {},\n ): LLM {\n return new LLM({\n model: 'llama3.1',\n baseURL: 'http://localhost:11434/v1',\n apiKey: 'ollama',\n ...opts,\n });\n }\n\n /**\n * Create a new instance of PerplexityAI LLM.\n *\n * @remarks\n * `apiKey` must be set to your PerplexityAI API key, either using the argument or by setting the\n * `PERPLEXITY_API_KEY` environment variable.\n */\n static withPerplexity(\n opts: Partial<{\n model: string | PerplexityChatModels;\n apiKey?: string;\n baseURL?: string;\n user?: string;\n temperature?: number;\n client: OpenAI;\n }> = {},\n ): LLM {\n opts.apiKey = opts.apiKey || process.env.PERPLEXITY_API_KEY;\n if (opts.apiKey === undefined) {\n throw new Error(\n 'PerplexityAI API key is required, whether as an argument or as $PERPLEXITY_API_KEY',\n );\n }\n\n return new LLM({\n model: 'llama-3.1-sonar-small-128k-chat',\n baseURL: 'https://api.perplexity.ai',\n ...opts,\n });\n }\n\n /**\n * Create a new instance of TogetherAI LLM.\n *\n * @remarks\n * `apiKey` must be set to your TogetherAI API key, either using the argument or by setting the\n * `TOGETHER_API_KEY` environment variable.\n */\n static withTogether(\n opts: Partial<{\n model: string | TogetherChatModels;\n apiKey?: string;\n baseURL?: string;\n user?: string;\n temperature?: number;\n client: OpenAI;\n }> = {},\n ): LLM {\n opts.apiKey = opts.apiKey || process.env.TOGETHER_API_KEY;\n if (opts.apiKey === undefined) {\n throw new Error(\n 'TogetherAI API key is required, whether as an argument or as $TOGETHER_API_KEY',\n );\n }\n\n return new LLM({\n model: 'meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo',\n baseURL: 'https://api.together.xyz/v1',\n ...opts,\n });\n }\n\n /**\n * Create a new instance of Telnyx LLM.\n *\n * @remarks\n * `apiKey` must be set to your Telnyx API key, either using the argument or by setting the\n * `TELNYX_API_KEY` environment variable.\n */\n static withTelnyx(\n opts: Partial<{\n model: string | TelnyxChatModels;\n apiKey?: string;\n baseURL?: string;\n user?: string;\n temperature?: number;\n client: OpenAI;\n }> = {},\n ): LLM {\n opts.apiKey = opts.apiKey || process.env.TELNYX_API_KEY;\n if (opts.apiKey === undefined) {\n throw new Error('Telnyx API key is required, whether as an argument or as $TELNYX_API_KEY');\n }\n\n return new LLM({\n model: 'meta-llama/Meta-Llama-3.1-70B-Instruct',\n baseURL: 'https://api.telnyx.com/v2/ai',\n ...opts,\n });\n }\n\n /**\n * Create a new instance of Meta Llama LLM.\n *\n * @remarks\n * `apiKey` must be set to your Meta Llama API key, either using the argument or by setting the\n * `LLAMA_API_KEY` environment variable.\n */\n static withMeta(\n opts: Partial<{\n apiKey?: string;\n baseURL?: string;\n client?: OpenAI;\n model?: string | MetaChatModels;\n temperature?: number;\n user?: string;\n }> = {},\n ): LLM {\n opts.apiKey = opts.apiKey || process.env.LLAMA_API_KEY;\n opts.baseURL = opts.baseURL || 'https://api.llama.com/compat/v1/';\n opts.model = opts.model || 'Llama-4-Maverick-17B-128E-Instruct-FP8';\n\n if (opts.apiKey === undefined) {\n throw new Error(\n 'Meta Llama API key is required, either as argument or set LLAMA_API_KEY environment variable',\n );\n }\n\n return new LLM(opts);\n }\n\n /**\n * Create a new instance of OVHcloud AI Endpoints LLM.\n *\n * @remarks\n * `apiKey` must be set to your OVHcloud AI Endpoints API key, either using the argument or by setting the\n * `OVHCLOUD_API_KEY` environment variable.\n */\n static withOVHcloud(opts: Partial<LLMOptions> = {}): LLM {\n opts.apiKey = opts.apiKey || process.env.OVHCLOUD_API_KEY;\n if (opts.apiKey === undefined) {\n throw new Error(\n 'OVHcloud AI Endpoints API key is required, whether as an argument or as $OVHCLOUD_API_KEY',\n );\n }\n\n return new LLM({\n model: 'gpt-oss-120b',\n baseURL: 'https://oai.endpoints.kepler.ai.cloud.ovh.net/v1',\n ...opts,\n });\n }\n\n chat({\n chatCtx,\n toolCtx: toolCtxInput,\n connOptions = DEFAULT_API_CONNECT_OPTIONS,\n parallelToolCalls,\n toolChoice,\n extraKwargs,\n }: {\n chatCtx: llm.ChatContext;\n toolCtx?: llm.ToolContextLike;\n connOptions?: APIConnectOptions;\n parallelToolCalls?: boolean;\n toolChoice?: llm.ToolChoice;\n extraKwargs?: Record<string, unknown>;\n }): LLMStream {\n const toolCtx = llm.toToolContext(toolCtxInput);\n const extras: Record<string, unknown> = { ...extraKwargs };\n\n if (this.#opts.metadata) {\n extras.metadata = this.#opts.metadata;\n }\n\n if (this.#opts.user) {\n extras.user = this.#opts.user;\n }\n\n if (this.#opts.maxCompletionTokens) {\n extras.max_completion_tokens = this.#opts.maxCompletionTokens;\n }\n\n if (this.#opts.temperature) {\n extras.temperature = this.#opts.temperature;\n }\n\n if (this.#opts.topP !== undefined) {\n extras.top_p = this.#opts.topP;\n }\n\n if (this.#opts.serviceTier) {\n extras.service_tier = this.#opts.serviceTier;\n }\n\n if (this.#opts.store !== undefined) {\n extras.store = this.#opts.store;\n }\n\n if (this.#opts.reasoningEffort !== undefined) {\n extras.reasoning_effort = this.#opts.reasoningEffort;\n }\n\n parallelToolCalls =\n parallelToolCalls !== undefined ? parallelToolCalls : this.#opts.parallelToolCalls;\n if (\n toolCtx &&\n Object.keys(toolCtx.functionTools).length > 0 &&\n parallelToolCalls !== undefined\n ) {\n extras.parallel_tool_calls = parallelToolCalls;\n }\n\n toolChoice = toolChoice !== undefined ? toolChoice : this.#opts.toolChoice;\n if (toolChoice) {\n extras.tool_choice = toolChoice;\n }\n\n return new LLMStream(this as unknown as inference.LLM, {\n model: this.#opts.model,\n providerFmt: this.#providerFmt,\n client: this.#client as any,\n chatCtx,\n toolCtx,\n connOptions,\n modelOptions: extras,\n strictToolSchema: this.#opts.strictToolSchema || false,\n gatewayOptions: undefined, // OpenAI plugin doesn't use gateway authentication\n });\n }\n}\n\nexport class LLMStream extends inference.LLMStream {}\n"],"mappings":"AAIA,SAAS,6BAA6B,WAAW,WAAW;AAC5D,SAAS,aAAa,cAAc;AAcpC,SAAS,8BAA8B;AAoBvC,MAAM,oBAAgC;AAAA,EACpC,OAAO;AAAA,EACP,QAAQ,QAAQ,IAAI;AAAA,EACpB,mBAAmB;AAAA,EACnB,kBAAkB;AACpB;AAEA,MAAM,yBAAqC;AAAA,EACzC,OAAO;AAAA,EACP,QAAQ,QAAQ,IAAI;AAAA,EACpB,kBAAkB;AACpB;AAEO,MAAM,YAAY,IAAI,IAAI;AAAA,EAC/B;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,YACE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X-License-Identifier: Apache-2.0\nimport type { APIConnectOptions } from '@livekit/agents';\nimport { DEFAULT_API_CONNECT_OPTIONS, inference, llm } from '@livekit/agents';\nimport { AzureOpenAI, OpenAI } from 'openai';\nimport type {\n CerebrasChatModels,\n ChatModels,\n DeepSeekChatModels,\n GroqChatModels,\n MetaChatModels,\n OctoChatModels,\n PerplexityChatModels,\n ReasoningEffort,\n TelnyxChatModels,\n TogetherChatModels,\n XAIChatModels,\n} from './models.js';\nimport { defaultReasoningEffort } from './models.js';\n\nexport interface LLMOptions {\n model: string | ChatModels;\n apiKey?: string;\n baseURL?: string;\n user?: string;\n temperature?: number;\n topP?: number;\n client?: OpenAI;\n toolChoice?: llm.ToolChoice;\n parallelToolCalls?: boolean;\n metadata?: Record<string, string>;\n maxCompletionTokens?: number;\n serviceTier?: string;\n store?: boolean;\n reasoningEffort?: ReasoningEffort | 'xhigh' | 'max';\n safetyIdentifier?: string;\n promptCacheKey?: string;\n strictToolSchema?: boolean;\n}\n\nconst defaultLLMOptions: LLMOptions = {\n model: 'gpt-4.1',\n apiKey: process.env.OPENAI_API_KEY,\n parallelToolCalls: true,\n strictToolSchema: false,\n};\n\nconst defaultAzureLLMOptions: LLMOptions = {\n model: 'gpt-4.1',\n apiKey: process.env.AZURE_API_KEY,\n strictToolSchema: false,\n};\n\nexport class LLM extends llm.LLM {\n #opts: LLMOptions;\n #client: OpenAI;\n #providerFmt: llm.ProviderFormat;\n\n /**\n * Create a new instance of OpenAI LLM.\n *\n * @remarks\n * `apiKey` must be set to your OpenAI API key, either using the argument or by setting the\n * `OPENAI_API_KEY` environment variable.\n */\n constructor(\n opts: Partial<LLMOptions> = defaultLLMOptions,\n providerFmt: llm.ProviderFormat = 'openai',\n ) {\n super();\n\n this.#opts = { ...defaultLLMOptions, ...opts };\n this.#opts.reasoningEffort ??= defaultReasoningEffort(this.#opts.model);\n this.#providerFmt = providerFmt;\n if (this.#opts.apiKey === undefined && !this.#opts.client) {\n throw new Error('OpenAI API key is required, whether as an argument or as $OPENAI_API_KEY');\n }\n\n this.#client =\n this.#opts.client ||\n new OpenAI({\n baseURL: this.#opts.baseURL,\n maxRetries: 0,\n apiKey: this.#opts.apiKey,\n });\n }\n\n label(): string {\n return 'openai.LLM';\n }\n\n get model(): string {\n return this.#opts.model;\n }\n\n get provider(): string {\n try {\n const url = new URL(this.#client.baseURL);\n return url.host;\n } catch {\n return 'api.openai.com';\n }\n }\n\n protected override async _prewarmImpl(signal: AbortSignal): Promise<void> {\n await this.#client.models.list({ signal });\n }\n\n /**\n * Create a new instance of OpenAI LLM with Azure.\n *\n * @remarks\n * This automatically infers the following arguments from their corresponding environment variables if they are not provided:\n * - `apiKey` from `AZURE_OPENAI_API_KEY`\n * - `organization` from `OPENAI_ORG_ID`\n * - `project` from `OPENAI_PROJECT_ID`\n * - `azureAdToken` from `AZURE_OPENAI_AD_TOKEN`\n * - `apiVersion` from `OPENAI_API_VERSION`\n * - `azureEndpoint` from `AZURE_OPENAI_ENDPOINT`\n */\n static withAzure(\n opts: {\n model: string | ChatModels;\n azureEndpoint?: string;\n azureDeployment?: string;\n apiVersion?: string;\n apiKey?: string;\n azureAdToken?: string;\n azureAdTokenProvider?: () => Promise<string>;\n organization?: string;\n project?: string;\n baseURL?: string;\n user?: string;\n temperature?: number;\n } = defaultAzureLLMOptions,\n ): LLM {\n opts = { ...defaultAzureLLMOptions, ...opts };\n if (opts.apiKey === undefined) {\n throw new Error('Azure API key is required, whether as an argument or as $AZURE_API_KEY');\n }\n\n return new LLM({\n temperature: opts.temperature,\n user: opts.user,\n client: new AzureOpenAI({ ...opts, maxRetries: 0 }),\n });\n }\n\n /**\n * Create a new instance of Cerebras LLM.\n *\n * @remarks\n * `apiKey` must be set to your Cerebras API key, either using the argument or by setting the\n * `CEREBRAS_API_KEY` environment variable.\n */\n static withCerebras(\n opts: Partial<{\n model: string | CerebrasChatModels;\n apiKey?: string;\n baseURL?: string;\n user?: string;\n temperature?: number;\n client: OpenAI;\n }> = {},\n ): LLM {\n opts.apiKey = opts.apiKey || process.env.CEREBRAS_API_KEY;\n if (opts.apiKey === undefined) {\n throw new Error(\n 'Cerebras API key is required, whether as an argument or as $CEREBRAS_API_KEY',\n );\n }\n\n return new LLM({\n model: 'gpt-oss-120b',\n baseURL: 'https://api.cerebras.ai/v1',\n ...opts,\n });\n }\n\n /**\n * Create a new instance of Fireworks LLM.\n *\n * @remarks\n * `apiKey` must be set to your Fireworks API key, either using the argument or by setting the\n * `FIREWORKS_API_KEY` environment variable.\n */\n static withFireworks(opts: Partial<LLMOptions> = {}): LLM {\n opts.apiKey = opts.apiKey || process.env.FIREWORKS_API_KEY;\n if (opts.apiKey === undefined) {\n throw new Error(\n 'Fireworks API key is required, whether as an argument or as $FIREWORKS_API_KEY',\n );\n }\n\n return new LLM({\n model: 'accounts/fireworks/models/llama-v3p1-70b-instruct',\n baseURL: 'https://api.fireworks.ai/inference/v1',\n ...opts,\n });\n }\n\n /**\n * Create a new instance of xAI LLM.\n *\n * @remarks\n * `apiKey` must be set to your xAI API key, either using the argument or by setting the\n * `XAI_API_KEY` environment variable.\n */\n static withXAI(\n opts: Partial<{\n model: string | XAIChatModels;\n apiKey?: string;\n baseURL?: string;\n user?: string;\n temperature?: number;\n client: OpenAI;\n }> = {},\n ): LLM {\n opts.apiKey = opts.apiKey || process.env.XAI_API_KEY;\n if (opts.apiKey === undefined) {\n throw new Error('xAI API key is required, whether as an argument or as $XAI_API_KEY');\n }\n\n return new LLM({\n model: 'grok-2-public',\n baseURL: 'https://api.x.ai/v1',\n ...opts,\n });\n }\n\n /**\n * Create a new instance of Groq LLM.\n *\n * @remarks\n * `apiKey` must be set to your Groq API key, either using the argument or by setting the\n * `GROQ_API_KEY` environment variable.\n */\n static withGroq(\n opts: Partial<{\n model: string | GroqChatModels;\n apiKey?: string;\n baseURL?: string;\n user?: string;\n temperature?: number;\n client: OpenAI;\n }> = {},\n ): LLM {\n opts.apiKey = opts.apiKey || process.env.GROQ_API_KEY;\n if (opts.apiKey === undefined) {\n throw new Error('Groq API key is required, whether as an argument or as $GROQ_API_KEY');\n }\n\n return new LLM({\n model: 'openai/gpt-oss-120b',\n baseURL: 'https://api.groq.com/openai/v1',\n ...opts,\n });\n }\n\n /**\n * Create a new instance of DeepSeek LLM.\n *\n * @remarks\n * `apiKey` must be set to your DeepSeek API key, either using the argument or by setting the\n * `DEEPSEEK_API_KEY` environment variable.\n */\n static withDeepSeek(\n opts: Partial<{\n model: string | DeepSeekChatModels;\n apiKey?: string;\n baseURL?: string;\n user?: string;\n temperature?: number;\n client: OpenAI;\n }> = {},\n ): LLM {\n opts.apiKey = opts.apiKey || process.env.DEEPSEEK_API_KEY;\n if (opts.apiKey === undefined) {\n throw new Error(\n 'DeepSeek API key is required, whether as an argument or as $DEEPSEEK_API_KEY',\n );\n }\n\n return new LLM({\n model: 'deepseek-chat',\n baseURL: 'https://api.deepseek.com/v1',\n ...opts,\n });\n }\n\n /**\n * Create a new instance of OctoAI LLM.\n *\n * @remarks\n * `apiKey` must be set to your OctoAI API key, either using the argument or by setting the\n * `OCTOAI_TOKEN` environment variable.\n */\n static withOcto(\n opts: Partial<{\n model: string | OctoChatModels;\n apiKey?: string;\n baseURL?: string;\n user?: string;\n temperature?: number;\n client: OpenAI;\n }> = {},\n ): LLM {\n opts.apiKey = opts.apiKey || process.env.OCTOAI_TOKEN;\n if (opts.apiKey === undefined) {\n throw new Error('OctoAI API key is required, whether as an argument or as $OCTOAI_TOKEN');\n }\n\n return new LLM({\n model: 'llama-2-13b-chat',\n baseURL: 'https://text.octoai.run/v1',\n ...opts,\n });\n }\n\n /** Create a new instance of Ollama LLM. */\n static withOllama(\n opts: Partial<{\n model: string;\n baseURL?: string;\n temperature?: number;\n client: OpenAI;\n }> = {},\n ): LLM {\n return new LLM({\n model: 'llama3.1',\n baseURL: 'http://localhost:11434/v1',\n apiKey: 'ollama',\n ...opts,\n });\n }\n\n /**\n * Create a new instance of PerplexityAI LLM.\n *\n * @remarks\n * `apiKey` must be set to your PerplexityAI API key, either using the argument or by setting the\n * `PERPLEXITY_API_KEY` environment variable.\n */\n static withPerplexity(\n opts: Partial<{\n model: string | PerplexityChatModels;\n apiKey?: string;\n baseURL?: string;\n user?: string;\n temperature?: number;\n client: OpenAI;\n }> = {},\n ): LLM {\n opts.apiKey = opts.apiKey || process.env.PERPLEXITY_API_KEY;\n if (opts.apiKey === undefined) {\n throw new Error(\n 'PerplexityAI API key is required, whether as an argument or as $PERPLEXITY_API_KEY',\n );\n }\n\n return new LLM({\n model: 'llama-3.1-sonar-small-128k-chat',\n baseURL: 'https://api.perplexity.ai',\n ...opts,\n });\n }\n\n /**\n * Create a new instance of TogetherAI LLM.\n *\n * @remarks\n * `apiKey` must be set to your TogetherAI API key, either using the argument or by setting the\n * `TOGETHER_API_KEY` environment variable.\n */\n static withTogether(\n opts: Partial<{\n model: string | TogetherChatModels;\n apiKey?: string;\n baseURL?: string;\n user?: string;\n temperature?: number;\n client: OpenAI;\n }> = {},\n ): LLM {\n opts.apiKey = opts.apiKey || process.env.TOGETHER_API_KEY;\n if (opts.apiKey === undefined) {\n throw new Error(\n 'TogetherAI API key is required, whether as an argument or as $TOGETHER_API_KEY',\n );\n }\n\n return new LLM({\n model: 'meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo',\n baseURL: 'https://api.together.xyz/v1',\n ...opts,\n });\n }\n\n /**\n * Create a new instance of Telnyx LLM.\n *\n * @remarks\n * `apiKey` must be set to your Telnyx API key, either using the argument or by setting the\n * `TELNYX_API_KEY` environment variable.\n */\n static withTelnyx(\n opts: Partial<{\n model: string | TelnyxChatModels;\n apiKey?: string;\n baseURL?: string;\n user?: string;\n temperature?: number;\n client: OpenAI;\n }> = {},\n ): LLM {\n opts.apiKey = opts.apiKey || process.env.TELNYX_API_KEY;\n if (opts.apiKey === undefined) {\n throw new Error('Telnyx API key is required, whether as an argument or as $TELNYX_API_KEY');\n }\n\n return new LLM({\n model: 'meta-llama/Meta-Llama-3.1-70B-Instruct',\n baseURL: 'https://api.telnyx.com/v2/ai',\n ...opts,\n });\n }\n\n /**\n * Create a new instance of Meta Llama LLM.\n *\n * @remarks\n * `apiKey` must be set to your Meta Llama API key, either using the argument or by setting the\n * `LLAMA_API_KEY` environment variable.\n */\n static withMeta(\n opts: Partial<{\n apiKey?: string;\n baseURL?: string;\n client?: OpenAI;\n model?: string | MetaChatModels;\n temperature?: number;\n user?: string;\n }> = {},\n ): LLM {\n opts.apiKey = opts.apiKey || process.env.LLAMA_API_KEY;\n opts.baseURL = opts.baseURL || 'https://api.llama.com/compat/v1/';\n opts.model = opts.model || 'Llama-4-Maverick-17B-128E-Instruct-FP8';\n\n if (opts.apiKey === undefined) {\n throw new Error(\n 'Meta Llama API key is required, either as argument or set LLAMA_API_KEY environment variable',\n );\n }\n\n return new LLM(opts);\n }\n\n /**\n * Create a new instance of OVHcloud AI Endpoints LLM.\n *\n * @remarks\n * `apiKey` must be set to your OVHcloud AI Endpoints API key, either using the argument or by setting the\n * `OVHCLOUD_API_KEY` environment variable.\n */\n static withOVHcloud(opts: Partial<LLMOptions> = {}): LLM {\n opts.apiKey = opts.apiKey || process.env.OVHCLOUD_API_KEY;\n if (opts.apiKey === undefined) {\n throw new Error(\n 'OVHcloud AI Endpoints API key is required, whether as an argument or as $OVHCLOUD_API_KEY',\n );\n }\n\n return new LLM({\n model: 'gpt-oss-120b',\n baseURL: 'https://oai.endpoints.kepler.ai.cloud.ovh.net/v1',\n ...opts,\n });\n }\n\n /**\n * Create a new instance of a Modal LLM.\n *\n * @remarks\n * `model` is the endpoint hostname, e.g. `my-endpoint.us-west.modal.direct`.\n * `baseURL` defaults to the shared inference gateway in the hostname's region and can be set to\n * a dedicated Endpoint or self-hosted server URL.\n *\n * For authenticated Modal endpoints, pass your proxy token as `apiKey`, or set\n * `MODAL_PROXY_TOKEN` or the `MODAL_PROXY_TOKEN_ID` and `MODAL_PROXY_TOKEN_SECRET` pair.\n * A supplied `client` uses its own URL and credentials.\n */\n static withModal(opts: {\n model: string;\n apiKey?: string;\n baseURL?: string;\n client?: OpenAI;\n user?: string;\n temperature?: number;\n parallelToolCalls?: boolean;\n toolChoice?: llm.ToolChoice;\n reasoningEffort?: LLMOptions['reasoningEffort'];\n safetyIdentifier?: string;\n promptCacheKey?: string;\n topP?: number;\n }): LLM {\n let apiKey = opts.apiKey || process.env.MODAL_PROXY_TOKEN;\n if (!apiKey) {\n const tokenId = process.env.MODAL_PROXY_TOKEN_ID;\n const tokenSecret = process.env.MODAL_PROXY_TOKEN_SECRET;\n if (tokenId && tokenSecret) {\n apiKey = `${tokenId}.${tokenSecret}`;\n }\n }\n\n let baseURL = opts.baseURL;\n if (baseURL === undefined) {\n const region = opts.model.endsWith('.modal.direct')\n ? opts.model.split('.').at(-3)\n : 'us-west';\n baseURL = `https://inference.${region}.modal.direct/v1`;\n }\n\n return new LLM({\n parallelToolCalls: undefined,\n ...opts,\n apiKey: apiKey || 'modal',\n baseURL,\n toolChoice: opts.toolChoice ?? 'auto',\n });\n }\n\n chat({\n chatCtx,\n toolCtx: toolCtxInput,\n connOptions = DEFAULT_API_CONNECT_OPTIONS,\n parallelToolCalls,\n toolChoice,\n extraKwargs,\n }: {\n chatCtx: llm.ChatContext;\n toolCtx?: llm.ToolContextLike;\n connOptions?: APIConnectOptions;\n parallelToolCalls?: boolean;\n toolChoice?: llm.ToolChoice;\n extraKwargs?: Record<string, unknown>;\n }): LLMStream {\n const toolCtx = llm.toToolContext(toolCtxInput);\n const extras: Record<string, unknown> = { ...extraKwargs };\n\n if (this.#opts.metadata) {\n extras.metadata = this.#opts.metadata;\n }\n\n if (this.#opts.user) {\n extras.user = this.#opts.user;\n }\n\n if (this.#opts.maxCompletionTokens) {\n extras.max_completion_tokens = this.#opts.maxCompletionTokens;\n }\n\n if (this.#opts.temperature !== undefined) {\n extras.temperature = this.#opts.temperature;\n }\n\n if (this.#opts.topP !== undefined) {\n extras.top_p = this.#opts.topP;\n }\n\n if (this.#opts.serviceTier) {\n extras.service_tier = this.#opts.serviceTier;\n }\n\n if (this.#opts.store !== undefined) {\n extras.store = this.#opts.store;\n }\n\n if (this.#opts.reasoningEffort !== undefined) {\n extras.reasoning_effort = this.#opts.reasoningEffort;\n }\n\n if (this.#opts.safetyIdentifier !== undefined) {\n extras.safety_identifier = this.#opts.safetyIdentifier;\n }\n\n if (this.#opts.promptCacheKey !== undefined) {\n extras.prompt_cache_key = this.#opts.promptCacheKey;\n }\n\n parallelToolCalls =\n parallelToolCalls !== undefined ? parallelToolCalls : this.#opts.parallelToolCalls;\n if (\n toolCtx &&\n Object.keys(toolCtx.functionTools).length > 0 &&\n parallelToolCalls !== undefined\n ) {\n extras.parallel_tool_calls = parallelToolCalls;\n }\n\n toolChoice = toolChoice !== undefined ? toolChoice : this.#opts.toolChoice;\n if (toolChoice) {\n extras.tool_choice = toolChoice;\n }\n\n return new LLMStream(this as unknown as inference.LLM, {\n model: this.#opts.model,\n providerFmt: this.#providerFmt,\n client: this.#client as any,\n chatCtx,\n toolCtx,\n connOptions,\n modelOptions: extras,\n strictToolSchema: this.#opts.strictToolSchema || false,\n gatewayOptions: undefined, // OpenAI plugin doesn't use gateway authentication\n });\n }\n}\n\nexport class LLMStream extends inference.LLMStream {}\n"],"mappings":"AAIA,SAAS,6BAA6B,WAAW,WAAW;AAC5D,SAAS,aAAa,cAAc;AAcpC,SAAS,8BAA8B;AAsBvC,MAAM,oBAAgC;AAAA,EACpC,OAAO;AAAA,EACP,QAAQ,QAAQ,IAAI;AAAA,EACpB,mBAAmB;AAAA,EACnB,kBAAkB;AACpB;AAEA,MAAM,yBAAqC;AAAA,EACzC,OAAO;AAAA,EACP,QAAQ,QAAQ,IAAI;AAAA,EACpB,kBAAkB;AACpB;AAEO,MAAM,YAAY,IAAI,IAAI;AAAA,EAC/B;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,YACE,OAA4B,mBAC5B,cAAkC,UAClC;AACA,UAAM;AAEN,SAAK,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,QAAW;AAC7C,aAAO,oBAAoB,KAAK,MAAM;AAAA,IACxC;AAEA,QAAI,KAAK,MAAM,mBAAmB,QAAW;AAC3C,aAAO,mBAAmB,KAAK,MAAM;AAAA,IACvC;AAEA,wBACE,sBAAsB,SAAY,oBAAoB,KAAK,MAAM;AACnE,QACE,WACA,OAAO,KAAK,QAAQ,aAAa,EAAE,SAAS,KAC5C,sBAAsB,QACtB;AACA,aAAO,sBAAsB;AAAA,IAC/B;AAEA,iBAAa,eAAe,SAAY,aAAa,KAAK,MAAM;AAChE,QAAI,YAAY;AACd,aAAO,cAAc;AAAA,IACvB;AAEA,WAAO,IAAI,UAAU,MAAkC;AAAA,MACrD,OAAO,KAAK,MAAM;AAAA,MAClB,aAAa,KAAK;AAAA,MAClB,QAAQ,KAAK;AAAA,MACb;AAAA,MACA;AAAA,MACA;AAAA,MACA,cAAc;AAAA,MACd,kBAAkB,KAAK,MAAM,oBAAoB;AAAA,MACjD,gBAAgB;AAAA;AAAA,IAClB,CAAC;AAAA,EACH;AACF;AAEO,MAAM,kBAAkB,UAAU,UAAU;AAAC;","names":[]}
|
package/dist/llm.test.cjs
CHANGED
|
@@ -82,6 +82,97 @@ data: [DONE]
|
|
|
82
82
|
(0, import_vitest.expect)((_b = usageChunks[0]) == null ? void 0 : _b.promptTokens).toBe(7);
|
|
83
83
|
(0, import_vitest.expect)((_c = usageChunks[0]) == null ? void 0 : _c.totalTokens).toBe(0);
|
|
84
84
|
});
|
|
85
|
+
(0, import_vitest.describe)("OpenAI LLM with Modal", () => {
|
|
86
|
+
(0, import_vitest.it)("resolves the gateway without modifying the options", async () => {
|
|
87
|
+
const opts = Object.freeze({ model: "test-endpoint.us-east.modal.direct", apiKey: "test-key" });
|
|
88
|
+
const model = import_llm.LLM.withModal(opts);
|
|
89
|
+
try {
|
|
90
|
+
(0, import_vitest.expect)(model.provider).toBe("inference.us-east.modal.direct");
|
|
91
|
+
} finally {
|
|
92
|
+
await model.aclose();
|
|
93
|
+
}
|
|
94
|
+
});
|
|
95
|
+
(0, import_vitest.it)("uses the Modal proxy token for a hosted job request", async () => {
|
|
96
|
+
const fetch = import_vitest.vi.fn(
|
|
97
|
+
async () => new Response(streamWithNullUsage, { headers: { "content-type": "text/event-stream" } })
|
|
98
|
+
);
|
|
99
|
+
const jobCtx = {
|
|
100
|
+
job: { id: "test-job" },
|
|
101
|
+
room: { isConnected: false },
|
|
102
|
+
inferenceHeaders: {}
|
|
103
|
+
};
|
|
104
|
+
import_vitest.vi.stubGlobal("fetch", fetch);
|
|
105
|
+
import_vitest.vi.stubEnv("LIVEKIT_WORKER_TOKEN", "worker-test-token");
|
|
106
|
+
import_vitest.vi.stubEnv("MODAL_PROXY_TOKEN", "modal-test-token");
|
|
107
|
+
try {
|
|
108
|
+
const model = import_llm.LLM.withModal({ model: "test-endpoint.us-east.modal.direct" });
|
|
109
|
+
try {
|
|
110
|
+
await (0, import_agents.runWithJobContextAsync)(jobCtx, async () => {
|
|
111
|
+
const chatCtx = new import_agents.llm.ChatContext();
|
|
112
|
+
chatCtx.addMessage({ role: "user", content: "hi" });
|
|
113
|
+
for await (const chunk of model.chat({ chatCtx })) {
|
|
114
|
+
void chunk;
|
|
115
|
+
}
|
|
116
|
+
});
|
|
117
|
+
} finally {
|
|
118
|
+
await model.aclose();
|
|
119
|
+
}
|
|
120
|
+
(0, import_vitest.expect)(fetch).toHaveBeenCalledOnce();
|
|
121
|
+
const [url, options] = fetch.mock.calls[0];
|
|
122
|
+
(0, import_vitest.expect)(String(url)).toBe("https://inference.us-east.modal.direct/v1/chat/completions");
|
|
123
|
+
const headers = new Headers(options == null ? void 0 : options.headers);
|
|
124
|
+
(0, import_vitest.expect)(headers.get("Authorization")).toBe("Bearer modal-test-token");
|
|
125
|
+
(0, import_vitest.expect)(headers.has("X-LiveKit-Worker-Token")).toBe(false);
|
|
126
|
+
(0, import_vitest.expect)(headers.get("X-LiveKit-Job-Id")).toBe("test-job");
|
|
127
|
+
} finally {
|
|
128
|
+
import_vitest.vi.unstubAllEnvs();
|
|
129
|
+
import_vitest.vi.unstubAllGlobals();
|
|
130
|
+
}
|
|
131
|
+
});
|
|
132
|
+
import_vitest.it.each(["no tools", "a tool context", "raw tools", "a raw tool choice"])(
|
|
133
|
+
"builds a completion request with %s",
|
|
134
|
+
async (toolSource) => {
|
|
135
|
+
var _a, _b;
|
|
136
|
+
const withTools = toolSource === "a tool context" || toolSource === "raw tools";
|
|
137
|
+
const fetch = import_vitest.vi.fn(
|
|
138
|
+
async () => new Response(streamWithNullUsage, { headers: { "content-type": "text/event-stream" } })
|
|
139
|
+
);
|
|
140
|
+
const client = new import_openai.default({ apiKey: "test-key", fetch });
|
|
141
|
+
const model = import_llm.LLM.withModal({
|
|
142
|
+
model: "test-endpoint.us-west.modal.direct",
|
|
143
|
+
client,
|
|
144
|
+
temperature: withTools ? void 0 : 0,
|
|
145
|
+
reasoningEffort: "xhigh"
|
|
146
|
+
});
|
|
147
|
+
const chatCtx = new import_agents.llm.ChatContext();
|
|
148
|
+
chatCtx.addMessage({ role: "user", content: "hi" });
|
|
149
|
+
const toolCtx = toolSource === "a tool context" ? { echo: import_agents.llm.tool({ description: "Echo a message", execute: async () => "ok" }) } : import_agents.llm.ToolContext.empty();
|
|
150
|
+
const stream = model.chat({
|
|
151
|
+
chatCtx,
|
|
152
|
+
toolCtx,
|
|
153
|
+
toolChoice: toolSource === "raw tools" ? "required" : void 0,
|
|
154
|
+
extraKwargs: toolSource === "raw tools" ? { tools: [{ type: "function", function: { name: "echo" } }] } : toolSource === "a raw tool choice" ? { extra_body: { tool_choice: "required" } } : void 0
|
|
155
|
+
});
|
|
156
|
+
try {
|
|
157
|
+
for await (const _chunk of stream) {
|
|
158
|
+
}
|
|
159
|
+
} finally {
|
|
160
|
+
await model.aclose();
|
|
161
|
+
}
|
|
162
|
+
const body = JSON.parse(String((_b = (_a = fetch.mock.calls[0]) == null ? void 0 : _a[1]) == null ? void 0 : _b.body));
|
|
163
|
+
(0, import_vitest.expect)(body.reasoning_effort).toBe("xhigh");
|
|
164
|
+
if (withTools) {
|
|
165
|
+
(0, import_vitest.expect)(body.tools).toHaveLength(1);
|
|
166
|
+
(0, import_vitest.expect)(body.tool_choice).toBe(toolSource === "raw tools" ? "required" : "auto");
|
|
167
|
+
(0, import_vitest.expect)(body).not.toHaveProperty("temperature");
|
|
168
|
+
} else {
|
|
169
|
+
(0, import_vitest.expect)(body).not.toHaveProperty("tools");
|
|
170
|
+
(0, import_vitest.expect)(body).not.toHaveProperty("tool_choice");
|
|
171
|
+
(0, import_vitest.expect)(body.temperature).toBe(0);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
);
|
|
175
|
+
});
|
|
85
176
|
const hasOpenAIApiKey = Boolean(process.env.OPENAI_API_KEY);
|
|
86
177
|
if (hasOpenAIApiKey) {
|
|
87
178
|
(0, import_vitest.describe)("OpenAI", async () => {
|
package/dist/llm.test.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/llm.test.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2024 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport { llm } from '@livekit/agents';\nimport { llmStrict, llm as testLLM } from '@livekit/agents-plugins-test';\nimport OpenAI from 'openai';\nimport { describe, expect, it, vi } from 'vitest';\nimport { LLM } from './llm.js';\n\n// Some OpenAI-compatible proxies send a final chunk whose usage object is present but has null\n// numeric fields. The SDK builds its usage model leniently, so those nulls reach our usage\n// construction. See livekit/agents#6595.\nconst streamWithNullUsage = `data: {\"id\":\"chatcmpl-test\",\"choices\":[{\"delta\":{\"content\":\"ok\",\"role\":\"assistant\"},\"finish_reason\":null,\"index\":0}],\"created\":0,\"model\":\"m\",\"object\":\"chat.completion.chunk\"}\n\ndata: {\"id\":\"chatcmpl-test\",\"choices\":[{\"delta\":{},\"finish_reason\":\"stop\",\"index\":0}],\"created\":0,\"model\":\"m\",\"object\":\"chat.completion.chunk\"}\n\ndata: {\"id\":\"chatcmpl-test\",\"choices\":[],\"created\":0,\"model\":\"m\",\"object\":\"chat.completion.chunk\",\"usage\":{\"completion_tokens\":null,\"prompt_tokens\":7,\"total_tokens\":null}}\n\ndata: [DONE]\n\n`;\n\ndescribe('OpenAI LLM prewarm', () => {\n it('lists models with the prewarm cancellation signal', async () => {\n let prewarmSignal: AbortSignal | undefined;\n const modelsList = vi.fn(async (options: { signal?: AbortSignal }) => {\n prewarmSignal = options.signal;\n });\n const client = {\n baseURL: 'https://api.openai.test/v1',\n models: { list: modelsList },\n } as unknown as OpenAI;\n const llm = new LLM({ model: 'gpt-4.1', client });\n\n llm.prewarm();\n await new Promise<void>((resolve) => setImmediate(resolve));\n\n expect(modelsList).toHaveBeenCalledTimes(1);\n expect(prewarmSignal).toBeInstanceOf(AbortSignal);\n expect(prewarmSignal?.aborted).toBe(false);\n\n await llm.aclose();\n expect(prewarmSignal?.aborted).toBe(true);\n });\n});\n\nit('does not crash the stream when usage token counts are null', async () => {\n // Null fields inside a non-null usage object must not terminate the stream. Missing counts\n // default to zero.\n const client = new OpenAI({\n apiKey: 'test-key',\n fetch: async () =>\n new Response(streamWithNullUsage, {\n headers: { 'content-type': 'text/event-stream' },\n }),\n });\n const model = new LLM({ model: 'm', client });\n const chatCtx = new llm.ChatContext();\n chatCtx.addMessage({ role: 'user', content: 'hi' });\n\n const usageChunks: llm.CompletionUsage[] = [];\n const stream = model.chat({ chatCtx });\n try {\n for await (const chunk of stream) {\n if (chunk.usage) {\n usageChunks.push(chunk.usage);\n }\n }\n } finally {\n await model.aclose();\n }\n\n expect(usageChunks).toHaveLength(1);\n expect(usageChunks[0]?.completionTokens).toBe(0);\n expect(usageChunks[0]?.promptTokens).toBe(7);\n expect(usageChunks[0]?.totalTokens).toBe(0);\n});\n\nconst hasOpenAIApiKey = Boolean(process.env.OPENAI_API_KEY);\n\nif (hasOpenAIApiKey) {\n describe('OpenAI', async () => {\n await testLLM(\n new LLM({\n temperature: 0,\n }),\n false,\n );\n });\n} else {\n describe('OpenAI', () => {\n it.skip('requires OPENAI_API_KEY', () => {});\n });\n}\n\nif (hasOpenAIApiKey) {\n describe('OpenAI strict tool schema', async () => {\n await llmStrict(\n new LLM({\n temperature: 0,\n strictToolSchema: true,\n }),\n );\n });\n} else {\n describe('OpenAI strict tool schema', () => {\n it.skip('requires OPENAI_API_KEY', () => {});\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAGA,oBAAoB;AACpB,iCAA0C;AAC1C,oBAAmB;AACnB,oBAAyC;AACzC,iBAAoB;AAKpB,MAAM,sBAAsB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAU5B,wBAAS,sBAAsB,MAAM;AACnC,wBAAG,qDAAqD,YAAY;AAClE,QAAI;AACJ,UAAM,aAAa,iBAAG,GAAG,OAAO,YAAsC;AACpE,sBAAgB,QAAQ;AAAA,IAC1B,CAAC;AACD,UAAM,SAAS;AAAA,MACb,SAAS;AAAA,MACT,QAAQ,EAAE,MAAM,WAAW;AAAA,IAC7B;AACA,UAAMA,OAAM,IAAI,eAAI,EAAE,OAAO,WAAW,OAAO,CAAC;AAEhD,IAAAA,KAAI,QAAQ;AACZ,UAAM,IAAI,QAAc,CAAC,YAAY,aAAa,OAAO,CAAC;AAE1D,8BAAO,UAAU,EAAE,sBAAsB,CAAC;AAC1C,8BAAO,aAAa,EAAE,eAAe,WAAW;AAChD,8BAAO,+CAAe,OAAO,EAAE,KAAK,KAAK;AAEzC,UAAMA,KAAI,OAAO;AACjB,8BAAO,+CAAe,OAAO,EAAE,KAAK,IAAI;AAAA,EAC1C,CAAC;AACH,CAAC;AAAA,IAED,kBAAG,8DAA8D,YAAY;AA9C7E;AAiDE,QAAM,SAAS,IAAI,cAAAC,QAAO;AAAA,IACxB,QAAQ;AAAA,IACR,OAAO,YACL,IAAI,SAAS,qBAAqB;AAAA,MAChC,SAAS,EAAE,gBAAgB,oBAAoB;AAAA,IACjD,CAAC;AAAA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,CAAC;AAAA,EAC7C,CAAC;AACH;","names":["llm","OpenAI","testLLM"]}
|
|
1
|
+
{"version":3,"sources":["../src/llm.test.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2024 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport { type JobContext, llm, runWithJobContextAsync } from '@livekit/agents';\nimport { llmStrict, llm as testLLM } from '@livekit/agents-plugins-test';\nimport OpenAI from 'openai';\nimport { describe, expect, it, vi } from 'vitest';\nimport { LLM } from './llm.js';\n\n// Some OpenAI-compatible proxies send a final chunk whose usage object is present but has null\n// numeric fields. The SDK builds its usage model leniently, so those nulls reach our usage\n// construction. See livekit/agents#6595.\nconst streamWithNullUsage = `data: {\"id\":\"chatcmpl-test\",\"choices\":[{\"delta\":{\"content\":\"ok\",\"role\":\"assistant\"},\"finish_reason\":null,\"index\":0}],\"created\":0,\"model\":\"m\",\"object\":\"chat.completion.chunk\"}\n\ndata: {\"id\":\"chatcmpl-test\",\"choices\":[{\"delta\":{},\"finish_reason\":\"stop\",\"index\":0}],\"created\":0,\"model\":\"m\",\"object\":\"chat.completion.chunk\"}\n\ndata: {\"id\":\"chatcmpl-test\",\"choices\":[],\"created\":0,\"model\":\"m\",\"object\":\"chat.completion.chunk\",\"usage\":{\"completion_tokens\":null,\"prompt_tokens\":7,\"total_tokens\":null}}\n\ndata: [DONE]\n\n`;\n\ndescribe('OpenAI LLM prewarm', () => {\n it('lists models with the prewarm cancellation signal', async () => {\n let prewarmSignal: AbortSignal | undefined;\n const modelsList = vi.fn(async (options: { signal?: AbortSignal }) => {\n prewarmSignal = options.signal;\n });\n const client = {\n baseURL: 'https://api.openai.test/v1',\n models: { list: modelsList },\n } as unknown as OpenAI;\n const llm = new LLM({ model: 'gpt-4.1', client });\n\n llm.prewarm();\n await new Promise<void>((resolve) => setImmediate(resolve));\n\n expect(modelsList).toHaveBeenCalledTimes(1);\n expect(prewarmSignal).toBeInstanceOf(AbortSignal);\n expect(prewarmSignal?.aborted).toBe(false);\n\n await llm.aclose();\n expect(prewarmSignal?.aborted).toBe(true);\n });\n});\n\nit('does not crash the stream when usage token counts are null', async () => {\n // Null fields inside a non-null usage object must not terminate the stream. Missing counts\n // default to zero.\n const client = new OpenAI({\n apiKey: 'test-key',\n fetch: async () =>\n new Response(streamWithNullUsage, {\n headers: { 'content-type': 'text/event-stream' },\n }),\n });\n const model = new LLM({ model: 'm', client });\n const chatCtx = new llm.ChatContext();\n chatCtx.addMessage({ role: 'user', content: 'hi' });\n\n const usageChunks: llm.CompletionUsage[] = [];\n const stream = model.chat({ chatCtx });\n try {\n for await (const chunk of stream) {\n if (chunk.usage) {\n usageChunks.push(chunk.usage);\n }\n }\n } finally {\n await model.aclose();\n }\n\n expect(usageChunks).toHaveLength(1);\n expect(usageChunks[0]?.completionTokens).toBe(0);\n expect(usageChunks[0]?.promptTokens).toBe(7);\n expect(usageChunks[0]?.totalTokens).toBe(0);\n});\n\ndescribe('OpenAI LLM with Modal', () => {\n it('resolves the gateway without modifying the options', async () => {\n const opts = Object.freeze({ model: 'test-endpoint.us-east.modal.direct', apiKey: 'test-key' });\n const model = LLM.withModal(opts);\n\n try {\n expect(model.provider).toBe('inference.us-east.modal.direct');\n } finally {\n await model.aclose();\n }\n });\n\n it('uses the Modal proxy token for a hosted job request', async () => {\n const fetch = vi.fn<typeof globalThis.fetch>(\n async () =>\n new Response(streamWithNullUsage, { headers: { 'content-type': 'text/event-stream' } }),\n );\n const jobCtx = {\n job: { id: 'test-job' },\n room: { isConnected: false },\n inferenceHeaders: {},\n } as unknown as JobContext;\n vi.stubGlobal('fetch', fetch);\n vi.stubEnv('LIVEKIT_WORKER_TOKEN', 'worker-test-token');\n vi.stubEnv('MODAL_PROXY_TOKEN', 'modal-test-token');\n\n try {\n const model = LLM.withModal({ model: 'test-endpoint.us-east.modal.direct' });\n try {\n await runWithJobContextAsync(jobCtx, async () => {\n const chatCtx = new llm.ChatContext();\n chatCtx.addMessage({ role: 'user', content: 'hi' });\n for await (const chunk of model.chat({ chatCtx })) {\n void chunk;\n }\n });\n } finally {\n await model.aclose();\n }\n\n expect(fetch).toHaveBeenCalledOnce();\n const [url, options] = fetch.mock.calls[0]!;\n expect(String(url)).toBe('https://inference.us-east.modal.direct/v1/chat/completions');\n const headers = new Headers(options?.headers);\n expect(headers.get('Authorization')).toBe('Bearer modal-test-token');\n expect(headers.has('X-LiveKit-Worker-Token')).toBe(false);\n expect(headers.get('X-LiveKit-Job-Id')).toBe('test-job');\n } finally {\n vi.unstubAllEnvs();\n vi.unstubAllGlobals();\n }\n });\n\n it.each(['no tools', 'a tool context', 'raw tools', 'a raw tool choice'] as const)(\n 'builds a completion request with %s',\n async (toolSource) => {\n const withTools = toolSource === 'a tool context' || toolSource === 'raw tools';\n const fetch = vi.fn<typeof globalThis.fetch>(\n async () =>\n new Response(streamWithNullUsage, { headers: { 'content-type': 'text/event-stream' } }),\n );\n const client = new OpenAI({ apiKey: 'test-key', fetch });\n const model = LLM.withModal({\n model: 'test-endpoint.us-west.modal.direct',\n client,\n temperature: withTools ? undefined : 0,\n reasoningEffort: 'xhigh',\n });\n const chatCtx = new llm.ChatContext();\n chatCtx.addMessage({ role: 'user', content: 'hi' });\n const toolCtx =\n toolSource === 'a tool context'\n ? { echo: llm.tool({ description: 'Echo a message', execute: async () => 'ok' }) }\n : llm.ToolContext.empty();\n const stream = model.chat({\n chatCtx,\n toolCtx,\n toolChoice: toolSource === 'raw tools' ? 'required' : undefined,\n extraKwargs:\n toolSource === 'raw tools'\n ? { tools: [{ type: 'function', function: { name: 'echo' } }] }\n : toolSource === 'a raw tool choice'\n ? { extra_body: { tool_choice: 'required' } }\n : undefined,\n });\n\n try {\n for await (const _chunk of stream) {\n // Consume the reply so the request runs.\n }\n } finally {\n await model.aclose();\n }\n\n const body = JSON.parse(String(fetch.mock.calls[0]?.[1]?.body));\n expect(body.reasoning_effort).toBe('xhigh');\n if (withTools) {\n expect(body.tools).toHaveLength(1);\n expect(body.tool_choice).toBe(toolSource === 'raw tools' ? 'required' : 'auto');\n expect(body).not.toHaveProperty('temperature');\n } else {\n expect(body).not.toHaveProperty('tools');\n expect(body).not.toHaveProperty('tool_choice');\n expect(body.temperature).toBe(0);\n }\n },\n );\n});\n\nconst hasOpenAIApiKey = Boolean(process.env.OPENAI_API_KEY);\n\nif (hasOpenAIApiKey) {\n describe('OpenAI', async () => {\n await testLLM(\n new LLM({\n temperature: 0,\n }),\n false,\n );\n });\n} else {\n describe('OpenAI', () => {\n it.skip('requires OPENAI_API_KEY', () => {});\n });\n}\n\nif (hasOpenAIApiKey) {\n describe('OpenAI strict tool schema', async () => {\n await llmStrict(\n new LLM({\n temperature: 0,\n strictToolSchema: true,\n }),\n );\n });\n} else {\n describe('OpenAI strict tool schema', () => {\n it.skip('requires OPENAI_API_KEY', () => {});\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAGA,oBAA6D;AAC7D,iCAA0C;AAC1C,oBAAmB;AACnB,oBAAyC;AACzC,iBAAoB;AAKpB,MAAM,sBAAsB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAU5B,wBAAS,sBAAsB,MAAM;AACnC,wBAAG,qDAAqD,YAAY;AAClE,QAAI;AACJ,UAAM,aAAa,iBAAG,GAAG,OAAO,YAAsC;AACpE,sBAAgB,QAAQ;AAAA,IAC1B,CAAC;AACD,UAAM,SAAS;AAAA,MACb,SAAS;AAAA,MACT,QAAQ,EAAE,MAAM,WAAW;AAAA,IAC7B;AACA,UAAMA,OAAM,IAAI,eAAI,EAAE,OAAO,WAAW,OAAO,CAAC;AAEhD,IAAAA,KAAI,QAAQ;AACZ,UAAM,IAAI,QAAc,CAAC,YAAY,aAAa,OAAO,CAAC;AAE1D,8BAAO,UAAU,EAAE,sBAAsB,CAAC;AAC1C,8BAAO,aAAa,EAAE,eAAe,WAAW;AAChD,8BAAO,+CAAe,OAAO,EAAE,KAAK,KAAK;AAEzC,UAAMA,KAAI,OAAO;AAC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AAE,aAAa,CAAC;AACjC,kCAAO,KAAK,WAAW,EAAE,KAAK,eAAe,cAAc,aAAa,MAAM;AAC9E,kCAAO,IAAI,EAAE,IAAI,eAAe,aAAa;AAAA,MAC/C,OAAO;AACL,kCAAO,IAAI,EAAE,IAAI,eAAe,OAAO;AACvC,kCAAO,IAAI,EAAE,IAAI,eAAe,aAAa;AAC7C,kCAAO,KAAK,WAAW,EAAE,KAAK,CAAC;AAAA,MACjC;AAAA,IACF;AAAA,EACF;AACF,CAAC;AAED,MAAM,kBAAkB,QAAQ,QAAQ,IAAI,cAAc;AAE1D,IAAI,iBAAiB;AACnB,8BAAS,UAAU,YAAY;AAC7B,cAAM,2BAAAC;AAAA,MACJ,IAAI,eAAI;AAAA,QACN,aAAa;AAAA,MACf,CAAC;AAAA,MACD;AAAA,IACF;AAAA,EACF,CAAC;AACH,OAAO;AACL,8BAAS,UAAU,MAAM;AACvB,qBAAG,KAAK,2BAA2B,MAAM;AAAA,IAAC,CAAC;AAAA,EAC7C,CAAC;AACH;AAEA,IAAI,iBAAiB;AACnB,8BAAS,6BAA6B,YAAY;AAChD,cAAM;AAAA,MACJ,IAAI,eAAI;AAAA,QACN,aAAa;AAAA,QACb,kBAAkB;AAAA,MACpB,CAAC;AAAA,IACH;AAAA,EACF,CAAC;AACH,OAAO;AACL,8BAAS,6BAA6B,MAAM;AAC1C,qBAAG,KAAK,2BAA2B,MAAM;AAAA,IAAC,CAAC;AAAA,EAC7C,CAAC;AACH;","names":["llm","OpenAI","testLLM"]}
|
package/dist/llm.test.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { llm } from "@livekit/agents";
|
|
1
|
+
import { llm, runWithJobContextAsync } from "@livekit/agents";
|
|
2
2
|
import { llmStrict, llm as testLLM } from "@livekit/agents-plugins-test";
|
|
3
3
|
import OpenAI from "openai";
|
|
4
4
|
import { describe, expect, it, vi } from "vitest";
|
|
@@ -59,6 +59,97 @@ it("does not crash the stream when usage token counts are null", async () => {
|
|
|
59
59
|
expect((_b = usageChunks[0]) == null ? void 0 : _b.promptTokens).toBe(7);
|
|
60
60
|
expect((_c = usageChunks[0]) == null ? void 0 : _c.totalTokens).toBe(0);
|
|
61
61
|
});
|
|
62
|
+
describe("OpenAI LLM with Modal", () => {
|
|
63
|
+
it("resolves the gateway without modifying the options", async () => {
|
|
64
|
+
const opts = Object.freeze({ model: "test-endpoint.us-east.modal.direct", apiKey: "test-key" });
|
|
65
|
+
const model = LLM.withModal(opts);
|
|
66
|
+
try {
|
|
67
|
+
expect(model.provider).toBe("inference.us-east.modal.direct");
|
|
68
|
+
} finally {
|
|
69
|
+
await model.aclose();
|
|
70
|
+
}
|
|
71
|
+
});
|
|
72
|
+
it("uses the Modal proxy token for a hosted job request", async () => {
|
|
73
|
+
const fetch = vi.fn(
|
|
74
|
+
async () => new Response(streamWithNullUsage, { headers: { "content-type": "text/event-stream" } })
|
|
75
|
+
);
|
|
76
|
+
const jobCtx = {
|
|
77
|
+
job: { id: "test-job" },
|
|
78
|
+
room: { isConnected: false },
|
|
79
|
+
inferenceHeaders: {}
|
|
80
|
+
};
|
|
81
|
+
vi.stubGlobal("fetch", fetch);
|
|
82
|
+
vi.stubEnv("LIVEKIT_WORKER_TOKEN", "worker-test-token");
|
|
83
|
+
vi.stubEnv("MODAL_PROXY_TOKEN", "modal-test-token");
|
|
84
|
+
try {
|
|
85
|
+
const model = LLM.withModal({ model: "test-endpoint.us-east.modal.direct" });
|
|
86
|
+
try {
|
|
87
|
+
await runWithJobContextAsync(jobCtx, async () => {
|
|
88
|
+
const chatCtx = new llm.ChatContext();
|
|
89
|
+
chatCtx.addMessage({ role: "user", content: "hi" });
|
|
90
|
+
for await (const chunk of model.chat({ chatCtx })) {
|
|
91
|
+
void chunk;
|
|
92
|
+
}
|
|
93
|
+
});
|
|
94
|
+
} finally {
|
|
95
|
+
await model.aclose();
|
|
96
|
+
}
|
|
97
|
+
expect(fetch).toHaveBeenCalledOnce();
|
|
98
|
+
const [url, options] = fetch.mock.calls[0];
|
|
99
|
+
expect(String(url)).toBe("https://inference.us-east.modal.direct/v1/chat/completions");
|
|
100
|
+
const headers = new Headers(options == null ? void 0 : options.headers);
|
|
101
|
+
expect(headers.get("Authorization")).toBe("Bearer modal-test-token");
|
|
102
|
+
expect(headers.has("X-LiveKit-Worker-Token")).toBe(false);
|
|
103
|
+
expect(headers.get("X-LiveKit-Job-Id")).toBe("test-job");
|
|
104
|
+
} finally {
|
|
105
|
+
vi.unstubAllEnvs();
|
|
106
|
+
vi.unstubAllGlobals();
|
|
107
|
+
}
|
|
108
|
+
});
|
|
109
|
+
it.each(["no tools", "a tool context", "raw tools", "a raw tool choice"])(
|
|
110
|
+
"builds a completion request with %s",
|
|
111
|
+
async (toolSource) => {
|
|
112
|
+
var _a, _b;
|
|
113
|
+
const withTools = toolSource === "a tool context" || toolSource === "raw tools";
|
|
114
|
+
const fetch = vi.fn(
|
|
115
|
+
async () => new Response(streamWithNullUsage, { headers: { "content-type": "text/event-stream" } })
|
|
116
|
+
);
|
|
117
|
+
const client = new OpenAI({ apiKey: "test-key", fetch });
|
|
118
|
+
const model = LLM.withModal({
|
|
119
|
+
model: "test-endpoint.us-west.modal.direct",
|
|
120
|
+
client,
|
|
121
|
+
temperature: withTools ? void 0 : 0,
|
|
122
|
+
reasoningEffort: "xhigh"
|
|
123
|
+
});
|
|
124
|
+
const chatCtx = new llm.ChatContext();
|
|
125
|
+
chatCtx.addMessage({ role: "user", content: "hi" });
|
|
126
|
+
const toolCtx = toolSource === "a tool context" ? { echo: llm.tool({ description: "Echo a message", execute: async () => "ok" }) } : llm.ToolContext.empty();
|
|
127
|
+
const stream = model.chat({
|
|
128
|
+
chatCtx,
|
|
129
|
+
toolCtx,
|
|
130
|
+
toolChoice: toolSource === "raw tools" ? "required" : void 0,
|
|
131
|
+
extraKwargs: toolSource === "raw tools" ? { tools: [{ type: "function", function: { name: "echo" } }] } : toolSource === "a raw tool choice" ? { extra_body: { tool_choice: "required" } } : void 0
|
|
132
|
+
});
|
|
133
|
+
try {
|
|
134
|
+
for await (const _chunk of stream) {
|
|
135
|
+
}
|
|
136
|
+
} finally {
|
|
137
|
+
await model.aclose();
|
|
138
|
+
}
|
|
139
|
+
const body = JSON.parse(String((_b = (_a = fetch.mock.calls[0]) == null ? void 0 : _a[1]) == null ? void 0 : _b.body));
|
|
140
|
+
expect(body.reasoning_effort).toBe("xhigh");
|
|
141
|
+
if (withTools) {
|
|
142
|
+
expect(body.tools).toHaveLength(1);
|
|
143
|
+
expect(body.tool_choice).toBe(toolSource === "raw tools" ? "required" : "auto");
|
|
144
|
+
expect(body).not.toHaveProperty("temperature");
|
|
145
|
+
} else {
|
|
146
|
+
expect(body).not.toHaveProperty("tools");
|
|
147
|
+
expect(body).not.toHaveProperty("tool_choice");
|
|
148
|
+
expect(body.temperature).toBe(0);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
);
|
|
152
|
+
});
|
|
62
153
|
const hasOpenAIApiKey = Boolean(process.env.OPENAI_API_KEY);
|
|
63
154
|
if (hasOpenAIApiKey) {
|
|
64
155
|
describe("OpenAI", async () => {
|
package/dist/llm.test.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/llm.test.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2024 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport { llm } from '@livekit/agents';\nimport { llmStrict, llm as testLLM } from '@livekit/agents-plugins-test';\nimport OpenAI from 'openai';\nimport { describe, expect, it, vi } from 'vitest';\nimport { LLM } from './llm.js';\n\n// Some OpenAI-compatible proxies send a final chunk whose usage object is present but has null\n// numeric fields. The SDK builds its usage model leniently, so those nulls reach our usage\n// construction. See livekit/agents#6595.\nconst streamWithNullUsage = `data: {\"id\":\"chatcmpl-test\",\"choices\":[{\"delta\":{\"content\":\"ok\",\"role\":\"assistant\"},\"finish_reason\":null,\"index\":0}],\"created\":0,\"model\":\"m\",\"object\":\"chat.completion.chunk\"}\n\ndata: {\"id\":\"chatcmpl-test\",\"choices\":[{\"delta\":{},\"finish_reason\":\"stop\",\"index\":0}],\"created\":0,\"model\":\"m\",\"object\":\"chat.completion.chunk\"}\n\ndata: {\"id\":\"chatcmpl-test\",\"choices\":[],\"created\":0,\"model\":\"m\",\"object\":\"chat.completion.chunk\",\"usage\":{\"completion_tokens\":null,\"prompt_tokens\":7,\"total_tokens\":null}}\n\ndata: [DONE]\n\n`;\n\ndescribe('OpenAI LLM prewarm', () => {\n it('lists models with the prewarm cancellation signal', async () => {\n let prewarmSignal: AbortSignal | undefined;\n const modelsList = vi.fn(async (options: { signal?: AbortSignal }) => {\n prewarmSignal = options.signal;\n });\n const client = {\n baseURL: 'https://api.openai.test/v1',\n models: { list: modelsList },\n } as unknown as OpenAI;\n const llm = new LLM({ model: 'gpt-4.1', client });\n\n llm.prewarm();\n await new Promise<void>((resolve) => setImmediate(resolve));\n\n expect(modelsList).toHaveBeenCalledTimes(1);\n expect(prewarmSignal).toBeInstanceOf(AbortSignal);\n expect(prewarmSignal?.aborted).toBe(false);\n\n await llm.aclose();\n expect(prewarmSignal?.aborted).toBe(true);\n });\n});\n\nit('does not crash the stream when usage token counts are null', async () => {\n // Null fields inside a non-null usage object must not terminate the stream. Missing counts\n // default to zero.\n const client = new OpenAI({\n apiKey: 'test-key',\n fetch: async () =>\n new Response(streamWithNullUsage, {\n headers: { 'content-type': 'text/event-stream' },\n }),\n });\n const model = new LLM({ model: 'm', client });\n const chatCtx = new llm.ChatContext();\n chatCtx.addMessage({ role: 'user', content: 'hi' });\n\n const usageChunks: llm.CompletionUsage[] = [];\n const stream = model.chat({ chatCtx });\n try {\n for await (const chunk of stream) {\n if (chunk.usage) {\n usageChunks.push(chunk.usage);\n }\n }\n } finally {\n await model.aclose();\n }\n\n expect(usageChunks).toHaveLength(1);\n expect(usageChunks[0]?.completionTokens).toBe(0);\n expect(usageChunks[0]?.promptTokens).toBe(7);\n expect(usageChunks[0]?.totalTokens).toBe(0);\n});\n\nconst hasOpenAIApiKey = Boolean(process.env.OPENAI_API_KEY);\n\nif (hasOpenAIApiKey) {\n describe('OpenAI', async () => {\n await testLLM(\n new LLM({\n temperature: 0,\n }),\n false,\n );\n });\n} else {\n describe('OpenAI', () => {\n it.skip('requires OPENAI_API_KEY', () => {});\n });\n}\n\nif (hasOpenAIApiKey) {\n describe('OpenAI strict tool schema', async () => {\n await llmStrict(\n new LLM({\n temperature: 0,\n strictToolSchema: true,\n }),\n );\n });\n} else {\n describe('OpenAI strict tool schema', () => {\n it.skip('requires OPENAI_API_KEY', () => {});\n });\n}\n"],"mappings":"AAGA,SAAS,WAAW;AACpB,SAAS,WAAW,OAAO,eAAe;AAC1C,OAAO,YAAY;AACnB,SAAS,UAAU,QAAQ,IAAI,UAAU;AACzC,SAAS,WAAW;AAKpB,MAAM,sBAAsB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAU5B,SAAS,sBAAsB,MAAM;AACnC,KAAG,qDAAqD,YAAY;AAClE,QAAI;AACJ,UAAM,aAAa,GAAG,GAAG,OAAO,YAAsC;AACpE,sBAAgB,QAAQ;AAAA,IAC1B,CAAC;AACD,UAAM,SAAS;AAAA,MACb,SAAS;AAAA,MACT,QAAQ,EAAE,MAAM,WAAW;AAAA,IAC7B;AACA,UAAMA,OAAM,IAAI,IAAI,EAAE,OAAO,WAAW,OAAO,CAAC;AAEhD,IAAAA,KAAI,QAAQ;AACZ,UAAM,IAAI,QAAc,CAAC,YAAY,aAAa,OAAO,CAAC;AAE1D,WAAO,UAAU,EAAE,sBAAsB,CAAC;AAC1C,WAAO,aAAa,EAAE,eAAe,WAAW;AAChD,WAAO,+CAAe,OAAO,EAAE,KAAK,KAAK;AAEzC,UAAMA,KAAI,OAAO;AACjB,WAAO,+CAAe,OAAO,EAAE,KAAK,IAAI;AAAA,EAC1C,CAAC;AACH,CAAC;AAED,GAAG,8DAA8D,YAAY;AA9C7E;AAiDE,QAAM,SAAS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B,CAAC;AAAA,IACH;AAAA,EACF,CAAC;AACH,OAAO;AACL,WAAS,6BAA6B,MAAM;AAC1C,OAAG,KAAK,2BAA2B,MAAM;AAAA,IAAC,CAAC;AAAA,EAC7C,CAAC;AACH;","names":["llm"]}
|
|
1
|
+
{"version":3,"sources":["../src/llm.test.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2024 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport { type JobContext, llm, runWithJobContextAsync } from '@livekit/agents';\nimport { llmStrict, llm as testLLM } from '@livekit/agents-plugins-test';\nimport OpenAI from 'openai';\nimport { describe, expect, it, vi } from 'vitest';\nimport { LLM } from './llm.js';\n\n// Some OpenAI-compatible proxies send a final chunk whose usage object is present but has null\n// numeric fields. The SDK builds its usage model leniently, so those nulls reach our usage\n// construction. See livekit/agents#6595.\nconst streamWithNullUsage = `data: {\"id\":\"chatcmpl-test\",\"choices\":[{\"delta\":{\"content\":\"ok\",\"role\":\"assistant\"},\"finish_reason\":null,\"index\":0}],\"created\":0,\"model\":\"m\",\"object\":\"chat.completion.chunk\"}\n\ndata: {\"id\":\"chatcmpl-test\",\"choices\":[{\"delta\":{},\"finish_reason\":\"stop\",\"index\":0}],\"created\":0,\"model\":\"m\",\"object\":\"chat.completion.chunk\"}\n\ndata: {\"id\":\"chatcmpl-test\",\"choices\":[],\"created\":0,\"model\":\"m\",\"object\":\"chat.completion.chunk\",\"usage\":{\"completion_tokens\":null,\"prompt_tokens\":7,\"total_tokens\":null}}\n\ndata: [DONE]\n\n`;\n\ndescribe('OpenAI LLM prewarm', () => {\n it('lists models with the prewarm cancellation signal', async () => {\n let prewarmSignal: AbortSignal | undefined;\n const modelsList = vi.fn(async (options: { signal?: AbortSignal }) => {\n prewarmSignal = options.signal;\n });\n const client = {\n baseURL: 'https://api.openai.test/v1',\n models: { list: modelsList },\n } as unknown as OpenAI;\n const llm = new LLM({ model: 'gpt-4.1', client });\n\n llm.prewarm();\n await new Promise<void>((resolve) => setImmediate(resolve));\n\n expect(modelsList).toHaveBeenCalledTimes(1);\n expect(prewarmSignal).toBeInstanceOf(AbortSignal);\n expect(prewarmSignal?.aborted).toBe(false);\n\n await llm.aclose();\n expect(prewarmSignal?.aborted).toBe(true);\n });\n});\n\nit('does not crash the stream when usage token counts are null', async () => {\n // Null fields inside a non-null usage object must not terminate the stream. Missing counts\n // default to zero.\n const client = new OpenAI({\n apiKey: 'test-key',\n fetch: async () =>\n new Response(streamWithNullUsage, {\n headers: { 'content-type': 'text/event-stream' },\n }),\n });\n const model = new LLM({ model: 'm', client });\n const chatCtx = new llm.ChatContext();\n chatCtx.addMessage({ role: 'user', content: 'hi' });\n\n const usageChunks: llm.CompletionUsage[] = [];\n const stream = model.chat({ chatCtx });\n try {\n for await (const chunk of stream) {\n if (chunk.usage) {\n usageChunks.push(chunk.usage);\n }\n }\n } finally {\n await model.aclose();\n }\n\n expect(usageChunks).toHaveLength(1);\n expect(usageChunks[0]?.completionTokens).toBe(0);\n expect(usageChunks[0]?.promptTokens).toBe(7);\n expect(usageChunks[0]?.totalTokens).toBe(0);\n});\n\ndescribe('OpenAI LLM with Modal', () => {\n it('resolves the gateway without modifying the options', async () => {\n const opts = Object.freeze({ model: 'test-endpoint.us-east.modal.direct', apiKey: 'test-key' });\n const model = LLM.withModal(opts);\n\n try {\n expect(model.provider).toBe('inference.us-east.modal.direct');\n } finally {\n await model.aclose();\n }\n });\n\n it('uses the Modal proxy token for a hosted job request', async () => {\n const fetch = vi.fn<typeof globalThis.fetch>(\n async () =>\n new Response(streamWithNullUsage, { headers: { 'content-type': 'text/event-stream' } }),\n );\n const jobCtx = {\n job: { id: 'test-job' },\n room: { isConnected: false },\n inferenceHeaders: {},\n } as unknown as JobContext;\n vi.stubGlobal('fetch', fetch);\n vi.stubEnv('LIVEKIT_WORKER_TOKEN', 'worker-test-token');\n vi.stubEnv('MODAL_PROXY_TOKEN', 'modal-test-token');\n\n try {\n const model = LLM.withModal({ model: 'test-endpoint.us-east.modal.direct' });\n try {\n await runWithJobContextAsync(jobCtx, async () => {\n const chatCtx = new llm.ChatContext();\n chatCtx.addMessage({ role: 'user', content: 'hi' });\n for await (const chunk of model.chat({ chatCtx })) {\n void chunk;\n }\n });\n } finally {\n await model.aclose();\n }\n\n expect(fetch).toHaveBeenCalledOnce();\n const [url, options] = fetch.mock.calls[0]!;\n expect(String(url)).toBe('https://inference.us-east.modal.direct/v1/chat/completions');\n const headers = new Headers(options?.headers);\n expect(headers.get('Authorization')).toBe('Bearer modal-test-token');\n expect(headers.has('X-LiveKit-Worker-Token')).toBe(false);\n expect(headers.get('X-LiveKit-Job-Id')).toBe('test-job');\n } finally {\n vi.unstubAllEnvs();\n vi.unstubAllGlobals();\n }\n });\n\n it.each(['no tools', 'a tool context', 'raw tools', 'a raw tool choice'] as const)(\n 'builds a completion request with %s',\n async (toolSource) => {\n const withTools = toolSource === 'a tool context' || toolSource === 'raw tools';\n const fetch = vi.fn<typeof globalThis.fetch>(\n async () =>\n new Response(streamWithNullUsage, { headers: { 'content-type': 'text/event-stream' } }),\n );\n const client = new OpenAI({ apiKey: 'test-key', fetch });\n const model = LLM.withModal({\n model: 'test-endpoint.us-west.modal.direct',\n client,\n temperature: withTools ? undefined : 0,\n reasoningEffort: 'xhigh',\n });\n const chatCtx = new llm.ChatContext();\n chatCtx.addMessage({ role: 'user', content: 'hi' });\n const toolCtx =\n toolSource === 'a tool context'\n ? { echo: llm.tool({ description: 'Echo a message', execute: async () => 'ok' }) }\n : llm.ToolContext.empty();\n const stream = model.chat({\n chatCtx,\n toolCtx,\n toolChoice: toolSource === 'raw tools' ? 'required' : undefined,\n extraKwargs:\n toolSource === 'raw tools'\n ? { tools: [{ type: 'function', function: { name: 'echo' } }] }\n : toolSource === 'a raw tool choice'\n ? { extra_body: { tool_choice: 'required' } }\n : undefined,\n });\n\n try {\n for await (const _chunk of stream) {\n // Consume the reply so the request runs.\n }\n } finally {\n await model.aclose();\n }\n\n const body = JSON.parse(String(fetch.mock.calls[0]?.[1]?.body));\n expect(body.reasoning_effort).toBe('xhigh');\n if (withTools) {\n expect(body.tools).toHaveLength(1);\n expect(body.tool_choice).toBe(toolSource === 'raw tools' ? 'required' : 'auto');\n expect(body).not.toHaveProperty('temperature');\n } else {\n expect(body).not.toHaveProperty('tools');\n expect(body).not.toHaveProperty('tool_choice');\n expect(body.temperature).toBe(0);\n }\n },\n );\n});\n\nconst hasOpenAIApiKey = Boolean(process.env.OPENAI_API_KEY);\n\nif (hasOpenAIApiKey) {\n describe('OpenAI', async () => {\n await testLLM(\n new LLM({\n temperature: 0,\n }),\n false,\n );\n });\n} else {\n describe('OpenAI', () => {\n it.skip('requires OPENAI_API_KEY', () => {});\n });\n}\n\nif (hasOpenAIApiKey) {\n describe('OpenAI strict tool schema', async () => {\n await llmStrict(\n new LLM({\n temperature: 0,\n strictToolSchema: true,\n }),\n );\n });\n} else {\n describe('OpenAI strict tool schema', () => {\n it.skip('requires OPENAI_API_KEY', () => {});\n });\n}\n"],"mappings":"AAGA,SAA0B,KAAK,8BAA8B;AAC7D,SAAS,WAAW,OAAO,eAAe;AAC1C,OAAO,YAAY;AACnB,SAAS,UAAU,QAAQ,IAAI,UAAU;AACzC,SAAS,WAAW;AAKpB,MAAM,sBAAsB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAU5B,SAAS,sBAAsB,MAAM;AACnC,KAAG,qDAAqD,YAAY;AAClE,QAAI;AACJ,UAAM,aAAa,GAAG,GAAG,OAAO,YAAsC;AACpE,sBAAgB,QAAQ;AAAA,IAC1B,CAAC;AACD,UAAM,SAAS;AAAA,MACb,SAAS;AAAA,MACT,QAAQ,EAAE,MAAM,WAAW;AAAA,IAC7B;AACA,UAAMA,OAAM,IAAI,IAAI,EAAE,OAAO,WAAW,OAAO,CAAC;AAEhD,IAAAA,KAAI,QAAQ;AACZ,UAAM,IAAI,QAAc,CAAC,YAAY,aAAa,OAAO,CAAC;AAE1D,WAAO,UAAU,EAAE,s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AE,KAAK,OAAO;AAC1C,UAAI,WAAW;AACb,eAAO,KAAK,KAAK,EAAE,aAAa,CAAC;AACjC,eAAO,KAAK,WAAW,EAAE,KAAK,eAAe,cAAc,aAAa,MAAM;AAC9E,eAAO,IAAI,EAAE,IAAI,eAAe,aAAa;AAAA,MAC/C,OAAO;AACL,eAAO,IAAI,EAAE,IAAI,eAAe,OAAO;AACvC,eAAO,IAAI,EAAE,IAAI,eAAe,aAAa;AAC7C,eAAO,KAAK,WAAW,EAAE,KAAK,CAAC;AAAA,MACjC;AAAA,IACF;AAAA,EACF;AACF,CAAC;AAED,MAAM,kBAAkB,QAAQ,QAAQ,IAAI,cAAc;AAE1D,IAAI,iBAAiB;AACnB,WAAS,UAAU,YAAY;AAC7B,UAAM;AAAA,MACJ,IAAI,IAAI;AAAA,QACN,aAAa;AAAA,MACf,CAAC;AAAA,MACD;AAAA,IACF;AAAA,EACF,CAAC;AACH,OAAO;AACL,WAAS,UAAU,MAAM;AACvB,OAAG,KAAK,2BAA2B,MAAM;AAAA,IAAC,CAAC;AAAA,EAC7C,CAAC;AACH;AAEA,IAAI,iBAAiB;AACnB,WAAS,6BAA6B,YAAY;AAChD,UAAM;AAAA,MACJ,IAAI,IAAI;AAAA,QACN,aAAa;AAAA,QACb,kBAAkB;AAAA,MACpB,CAAC;AAAA,IACH;AAAA,EACF,CAAC;AACH,OAAO;AACL,WAAS,6BAA6B,MAAM;AAC1C,OAAG,KAAK,2BAA2B,MAAM;AAAA,IAAC,CAAC;AAAA,EAC7C,CAAC;AACH;","names":["llm"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@livekit/agents-plugin-openai",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.11.1",
|
|
4
4
|
"description": "OpenAI plugin for LiveKit Node Agents",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"require": "dist/index.cjs",
|
|
@@ -33,9 +33,9 @@
|
|
|
33
33
|
"@types/ws": "^8.5.10",
|
|
34
34
|
"tsup": "^8.3.5",
|
|
35
35
|
"typescript": "^5.0.0",
|
|
36
|
-
"@livekit/agents": "1.
|
|
37
|
-
"@livekit/agents-plugin-silero": "1.
|
|
38
|
-
"@livekit/agents-plugins-test": "1.
|
|
36
|
+
"@livekit/agents": "1.11.1",
|
|
37
|
+
"@livekit/agents-plugin-silero": "1.11.1",
|
|
38
|
+
"@livekit/agents-plugins-test": "1.11.0"
|
|
39
39
|
},
|
|
40
40
|
"dependencies": {
|
|
41
41
|
"openai": "^6.8.1",
|
|
@@ -44,7 +44,7 @@
|
|
|
44
44
|
"peerDependencies": {
|
|
45
45
|
"@livekit/rtc-node": "^1.2.2",
|
|
46
46
|
"zod": "^3.25.76 || ^4.1.8",
|
|
47
|
-
"@livekit/agents": "1.
|
|
47
|
+
"@livekit/agents": "1.11.1"
|
|
48
48
|
},
|
|
49
49
|
"scripts": {
|
|
50
50
|
"build": "tsup --onSuccess \"pnpm build:types\"",
|
package/src/llm.test.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// SPDX-FileCopyrightText: 2024 LiveKit, Inc.
|
|
2
2
|
//
|
|
3
3
|
// SPDX-License-Identifier: Apache-2.0
|
|
4
|
-
import { llm } from '@livekit/agents';
|
|
4
|
+
import { type JobContext, llm, runWithJobContextAsync } from '@livekit/agents';
|
|
5
5
|
import { llmStrict, llm as testLLM } from '@livekit/agents-plugins-test';
|
|
6
6
|
import OpenAI from 'openai';
|
|
7
7
|
import { describe, expect, it, vi } from 'vitest';
|
|
@@ -76,6 +76,115 @@ it('does not crash the stream when usage token counts are null', async () => {
|
|
|
76
76
|
expect(usageChunks[0]?.totalTokens).toBe(0);
|
|
77
77
|
});
|
|
78
78
|
|
|
79
|
+
describe('OpenAI LLM with Modal', () => {
|
|
80
|
+
it('resolves the gateway without modifying the options', async () => {
|
|
81
|
+
const opts = Object.freeze({ model: 'test-endpoint.us-east.modal.direct', apiKey: 'test-key' });
|
|
82
|
+
const model = LLM.withModal(opts);
|
|
83
|
+
|
|
84
|
+
try {
|
|
85
|
+
expect(model.provider).toBe('inference.us-east.modal.direct');
|
|
86
|
+
} finally {
|
|
87
|
+
await model.aclose();
|
|
88
|
+
}
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
it('uses the Modal proxy token for a hosted job request', async () => {
|
|
92
|
+
const fetch = vi.fn<typeof globalThis.fetch>(
|
|
93
|
+
async () =>
|
|
94
|
+
new Response(streamWithNullUsage, { headers: { 'content-type': 'text/event-stream' } }),
|
|
95
|
+
);
|
|
96
|
+
const jobCtx = {
|
|
97
|
+
job: { id: 'test-job' },
|
|
98
|
+
room: { isConnected: false },
|
|
99
|
+
inferenceHeaders: {},
|
|
100
|
+
} as unknown as JobContext;
|
|
101
|
+
vi.stubGlobal('fetch', fetch);
|
|
102
|
+
vi.stubEnv('LIVEKIT_WORKER_TOKEN', 'worker-test-token');
|
|
103
|
+
vi.stubEnv('MODAL_PROXY_TOKEN', 'modal-test-token');
|
|
104
|
+
|
|
105
|
+
try {
|
|
106
|
+
const model = LLM.withModal({ model: 'test-endpoint.us-east.modal.direct' });
|
|
107
|
+
try {
|
|
108
|
+
await runWithJobContextAsync(jobCtx, async () => {
|
|
109
|
+
const chatCtx = new llm.ChatContext();
|
|
110
|
+
chatCtx.addMessage({ role: 'user', content: 'hi' });
|
|
111
|
+
for await (const chunk of model.chat({ chatCtx })) {
|
|
112
|
+
void chunk;
|
|
113
|
+
}
|
|
114
|
+
});
|
|
115
|
+
} finally {
|
|
116
|
+
await model.aclose();
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
expect(fetch).toHaveBeenCalledOnce();
|
|
120
|
+
const [url, options] = fetch.mock.calls[0]!;
|
|
121
|
+
expect(String(url)).toBe('https://inference.us-east.modal.direct/v1/chat/completions');
|
|
122
|
+
const headers = new Headers(options?.headers);
|
|
123
|
+
expect(headers.get('Authorization')).toBe('Bearer modal-test-token');
|
|
124
|
+
expect(headers.has('X-LiveKit-Worker-Token')).toBe(false);
|
|
125
|
+
expect(headers.get('X-LiveKit-Job-Id')).toBe('test-job');
|
|
126
|
+
} finally {
|
|
127
|
+
vi.unstubAllEnvs();
|
|
128
|
+
vi.unstubAllGlobals();
|
|
129
|
+
}
|
|
130
|
+
});
|
|
131
|
+
|
|
132
|
+
it.each(['no tools', 'a tool context', 'raw tools', 'a raw tool choice'] as const)(
|
|
133
|
+
'builds a completion request with %s',
|
|
134
|
+
async (toolSource) => {
|
|
135
|
+
const withTools = toolSource === 'a tool context' || toolSource === 'raw tools';
|
|
136
|
+
const fetch = vi.fn<typeof globalThis.fetch>(
|
|
137
|
+
async () =>
|
|
138
|
+
new Response(streamWithNullUsage, { headers: { 'content-type': 'text/event-stream' } }),
|
|
139
|
+
);
|
|
140
|
+
const client = new OpenAI({ apiKey: 'test-key', fetch });
|
|
141
|
+
const model = LLM.withModal({
|
|
142
|
+
model: 'test-endpoint.us-west.modal.direct',
|
|
143
|
+
client,
|
|
144
|
+
temperature: withTools ? undefined : 0,
|
|
145
|
+
reasoningEffort: 'xhigh',
|
|
146
|
+
});
|
|
147
|
+
const chatCtx = new llm.ChatContext();
|
|
148
|
+
chatCtx.addMessage({ role: 'user', content: 'hi' });
|
|
149
|
+
const toolCtx =
|
|
150
|
+
toolSource === 'a tool context'
|
|
151
|
+
? { echo: llm.tool({ description: 'Echo a message', execute: async () => 'ok' }) }
|
|
152
|
+
: llm.ToolContext.empty();
|
|
153
|
+
const stream = model.chat({
|
|
154
|
+
chatCtx,
|
|
155
|
+
toolCtx,
|
|
156
|
+
toolChoice: toolSource === 'raw tools' ? 'required' : undefined,
|
|
157
|
+
extraKwargs:
|
|
158
|
+
toolSource === 'raw tools'
|
|
159
|
+
? { tools: [{ type: 'function', function: { name: 'echo' } }] }
|
|
160
|
+
: toolSource === 'a raw tool choice'
|
|
161
|
+
? { extra_body: { tool_choice: 'required' } }
|
|
162
|
+
: undefined,
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
try {
|
|
166
|
+
for await (const _chunk of stream) {
|
|
167
|
+
// Consume the reply so the request runs.
|
|
168
|
+
}
|
|
169
|
+
} finally {
|
|
170
|
+
await model.aclose();
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
const body = JSON.parse(String(fetch.mock.calls[0]?.[1]?.body));
|
|
174
|
+
expect(body.reasoning_effort).toBe('xhigh');
|
|
175
|
+
if (withTools) {
|
|
176
|
+
expect(body.tools).toHaveLength(1);
|
|
177
|
+
expect(body.tool_choice).toBe(toolSource === 'raw tools' ? 'required' : 'auto');
|
|
178
|
+
expect(body).not.toHaveProperty('temperature');
|
|
179
|
+
} else {
|
|
180
|
+
expect(body).not.toHaveProperty('tools');
|
|
181
|
+
expect(body).not.toHaveProperty('tool_choice');
|
|
182
|
+
expect(body.temperature).toBe(0);
|
|
183
|
+
}
|
|
184
|
+
},
|
|
185
|
+
);
|
|
186
|
+
});
|
|
187
|
+
|
|
79
188
|
const hasOpenAIApiKey = Boolean(process.env.OPENAI_API_KEY);
|
|
80
189
|
|
|
81
190
|
if (hasOpenAIApiKey) {
|
package/src/llm.ts
CHANGED
|
@@ -33,7 +33,9 @@ export interface LLMOptions {
|
|
|
33
33
|
maxCompletionTokens?: number;
|
|
34
34
|
serviceTier?: string;
|
|
35
35
|
store?: boolean;
|
|
36
|
-
reasoningEffort?: ReasoningEffort;
|
|
36
|
+
reasoningEffort?: ReasoningEffort | 'xhigh' | 'max';
|
|
37
|
+
safetyIdentifier?: string;
|
|
38
|
+
promptCacheKey?: string;
|
|
37
39
|
strictToolSchema?: boolean;
|
|
38
40
|
}
|
|
39
41
|
|
|
@@ -476,6 +478,58 @@ export class LLM extends llm.LLM {
|
|
|
476
478
|
});
|
|
477
479
|
}
|
|
478
480
|
|
|
481
|
+
/**
|
|
482
|
+
* Create a new instance of a Modal LLM.
|
|
483
|
+
*
|
|
484
|
+
* @remarks
|
|
485
|
+
* `model` is the endpoint hostname, e.g. `my-endpoint.us-west.modal.direct`.
|
|
486
|
+
* `baseURL` defaults to the shared inference gateway in the hostname's region and can be set to
|
|
487
|
+
* a dedicated Endpoint or self-hosted server URL.
|
|
488
|
+
*
|
|
489
|
+
* For authenticated Modal endpoints, pass your proxy token as `apiKey`, or set
|
|
490
|
+
* `MODAL_PROXY_TOKEN` or the `MODAL_PROXY_TOKEN_ID` and `MODAL_PROXY_TOKEN_SECRET` pair.
|
|
491
|
+
* A supplied `client` uses its own URL and credentials.
|
|
492
|
+
*/
|
|
493
|
+
static withModal(opts: {
|
|
494
|
+
model: string;
|
|
495
|
+
apiKey?: string;
|
|
496
|
+
baseURL?: string;
|
|
497
|
+
client?: OpenAI;
|
|
498
|
+
user?: string;
|
|
499
|
+
temperature?: number;
|
|
500
|
+
parallelToolCalls?: boolean;
|
|
501
|
+
toolChoice?: llm.ToolChoice;
|
|
502
|
+
reasoningEffort?: LLMOptions['reasoningEffort'];
|
|
503
|
+
safetyIdentifier?: string;
|
|
504
|
+
promptCacheKey?: string;
|
|
505
|
+
topP?: number;
|
|
506
|
+
}): LLM {
|
|
507
|
+
let apiKey = opts.apiKey || process.env.MODAL_PROXY_TOKEN;
|
|
508
|
+
if (!apiKey) {
|
|
509
|
+
const tokenId = process.env.MODAL_PROXY_TOKEN_ID;
|
|
510
|
+
const tokenSecret = process.env.MODAL_PROXY_TOKEN_SECRET;
|
|
511
|
+
if (tokenId && tokenSecret) {
|
|
512
|
+
apiKey = `${tokenId}.${tokenSecret}`;
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
let baseURL = opts.baseURL;
|
|
517
|
+
if (baseURL === undefined) {
|
|
518
|
+
const region = opts.model.endsWith('.modal.direct')
|
|
519
|
+
? opts.model.split('.').at(-3)
|
|
520
|
+
: 'us-west';
|
|
521
|
+
baseURL = `https://inference.${region}.modal.direct/v1`;
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
return new LLM({
|
|
525
|
+
parallelToolCalls: undefined,
|
|
526
|
+
...opts,
|
|
527
|
+
apiKey: apiKey || 'modal',
|
|
528
|
+
baseURL,
|
|
529
|
+
toolChoice: opts.toolChoice ?? 'auto',
|
|
530
|
+
});
|
|
531
|
+
}
|
|
532
|
+
|
|
479
533
|
chat({
|
|
480
534
|
chatCtx,
|
|
481
535
|
toolCtx: toolCtxInput,
|
|
@@ -506,7 +560,7 @@ export class LLM extends llm.LLM {
|
|
|
506
560
|
extras.max_completion_tokens = this.#opts.maxCompletionTokens;
|
|
507
561
|
}
|
|
508
562
|
|
|
509
|
-
if (this.#opts.temperature) {
|
|
563
|
+
if (this.#opts.temperature !== undefined) {
|
|
510
564
|
extras.temperature = this.#opts.temperature;
|
|
511
565
|
}
|
|
512
566
|
|
|
@@ -526,6 +580,14 @@ export class LLM extends llm.LLM {
|
|
|
526
580
|
extras.reasoning_effort = this.#opts.reasoningEffort;
|
|
527
581
|
}
|
|
528
582
|
|
|
583
|
+
if (this.#opts.safetyIdentifier !== undefined) {
|
|
584
|
+
extras.safety_identifier = this.#opts.safetyIdentifier;
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
if (this.#opts.promptCacheKey !== undefined) {
|
|
588
|
+
extras.prompt_cache_key = this.#opts.promptCacheKey;
|
|
589
|
+
}
|
|
590
|
+
|
|
529
591
|
parallelToolCalls =
|
|
530
592
|
parallelToolCalls !== undefined ? parallelToolCalls : this.#opts.parallelToolCalls;
|
|
531
593
|
if (
|