@livekit/agents 1.0.6 → 1.0.7
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 +3 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/inference/api_protos.cjs +104 -0
- package/dist/inference/api_protos.cjs.map +1 -0
- package/dist/inference/api_protos.d.cts +222 -0
- package/dist/inference/api_protos.d.ts +222 -0
- package/dist/inference/api_protos.d.ts.map +1 -0
- package/dist/inference/api_protos.js +70 -0
- package/dist/inference/api_protos.js.map +1 -0
- package/dist/inference/index.cjs +56 -0
- package/dist/inference/index.cjs.map +1 -0
- package/dist/inference/index.d.cts +8 -0
- package/dist/inference/index.d.ts +8 -0
- package/dist/inference/index.d.ts.map +1 -0
- package/dist/inference/index.js +23 -0
- package/dist/inference/index.js.map +1 -0
- package/dist/inference/llm.cjs +299 -0
- package/dist/inference/llm.cjs.map +1 -0
- package/dist/inference/llm.d.cts +107 -0
- package/dist/inference/llm.d.ts +107 -0
- package/dist/inference/llm.d.ts.map +1 -0
- package/dist/inference/llm.js +270 -0
- package/dist/inference/llm.js.map +1 -0
- package/dist/inference/stt.cjs +313 -0
- package/dist/inference/stt.cjs.map +1 -0
- package/dist/inference/stt.d.cts +87 -0
- package/dist/inference/stt.d.ts +87 -0
- package/dist/inference/stt.d.ts.map +1 -0
- package/dist/inference/stt.js +292 -0
- package/dist/inference/stt.js.map +1 -0
- package/dist/inference/tts.cjs +324 -0
- package/dist/inference/tts.cjs.map +1 -0
- package/dist/inference/tts.d.cts +77 -0
- package/dist/inference/tts.d.ts +77 -0
- package/dist/inference/tts.d.ts.map +1 -0
- package/dist/inference/tts.js +306 -0
- package/dist/inference/tts.js.map +1 -0
- package/dist/inference/utils.cjs +76 -0
- package/dist/inference/utils.cjs.map +1 -0
- package/dist/inference/utils.d.cts +5 -0
- package/dist/inference/utils.d.ts +5 -0
- package/dist/inference/utils.d.ts.map +1 -0
- package/dist/inference/utils.js +51 -0
- package/dist/inference/utils.js.map +1 -0
- package/dist/llm/remote_chat_context.cjs.map +1 -1
- package/dist/llm/remote_chat_context.d.cts +2 -0
- package/dist/llm/remote_chat_context.d.ts +2 -0
- package/dist/llm/remote_chat_context.d.ts.map +1 -1
- package/dist/llm/remote_chat_context.js.map +1 -1
- package/dist/tts/tts.cjs +1 -1
- package/dist/tts/tts.cjs.map +1 -1
- package/dist/tts/tts.js +1 -1
- package/dist/tts/tts.js.map +1 -1
- package/dist/utils.cjs +11 -0
- package/dist/utils.cjs.map +1 -1
- package/dist/utils.d.cts +1 -0
- package/dist/utils.d.ts +1 -0
- package/dist/utils.d.ts.map +1 -1
- package/dist/utils.js +10 -0
- package/dist/utils.js.map +1 -1
- package/dist/voice/agent.cjs +16 -3
- package/dist/voice/agent.cjs.map +1 -1
- package/dist/voice/agent.d.cts +5 -3
- package/dist/voice/agent.d.ts +5 -3
- package/dist/voice/agent.d.ts.map +1 -1
- package/dist/voice/agent.js +20 -3
- package/dist/voice/agent.js.map +1 -1
- package/dist/voice/agent_activity.cjs +4 -2
- package/dist/voice/agent_activity.cjs.map +1 -1
- package/dist/voice/agent_activity.d.ts.map +1 -1
- package/dist/voice/agent_activity.js +4 -2
- package/dist/voice/agent_activity.js.map +1 -1
- package/dist/voice/agent_session.cjs +16 -3
- package/dist/voice/agent_session.cjs.map +1 -1
- package/dist/voice/agent_session.d.cts +4 -3
- package/dist/voice/agent_session.d.ts +4 -3
- package/dist/voice/agent_session.d.ts.map +1 -1
- package/dist/voice/agent_session.js +20 -3
- package/dist/voice/agent_session.js.map +1 -1
- package/dist/voice/events.cjs +2 -0
- package/dist/voice/events.cjs.map +1 -1
- package/dist/voice/events.d.cts +4 -1
- package/dist/voice/events.d.ts +4 -1
- package/dist/voice/events.d.ts.map +1 -1
- package/dist/voice/events.js +2 -0
- package/dist/voice/events.js.map +1 -1
- package/dist/voice/generation.cjs.map +1 -1
- package/dist/voice/generation.d.cts +1 -0
- package/dist/voice/generation.d.ts +1 -0
- package/dist/voice/generation.d.ts.map +1 -1
- package/dist/voice/generation.js.map +1 -1
- package/dist/voice/room_io/_input.cjs.map +1 -1
- package/dist/voice/room_io/_input.d.ts.map +1 -1
- package/dist/voice/room_io/_input.js +1 -0
- package/dist/voice/room_io/_input.js.map +1 -1
- package/dist/voice/room_io/_output.cjs +1 -1
- package/dist/voice/room_io/_output.cjs.map +1 -1
- package/dist/voice/room_io/_output.d.cts +1 -0
- package/dist/voice/room_io/_output.d.ts +1 -0
- package/dist/voice/room_io/_output.d.ts.map +1 -1
- package/dist/voice/room_io/_output.js +1 -1
- package/dist/voice/room_io/_output.js.map +1 -1
- package/dist/voice/room_io/room_io.cjs +1 -1
- package/dist/voice/room_io/room_io.cjs.map +1 -1
- package/dist/voice/room_io/room_io.d.cts +20 -0
- package/dist/voice/room_io/room_io.d.ts +20 -0
- package/dist/voice/room_io/room_io.d.ts.map +1 -1
- package/dist/voice/room_io/room_io.js +1 -1
- package/dist/voice/room_io/room_io.js.map +1 -1
- package/dist/voice/transcription/synchronizer.cjs +1 -1
- package/dist/voice/transcription/synchronizer.cjs.map +1 -1
- package/dist/voice/transcription/synchronizer.d.cts +1 -0
- package/dist/voice/transcription/synchronizer.d.ts +1 -0
- package/dist/voice/transcription/synchronizer.d.ts.map +1 -1
- package/dist/voice/transcription/synchronizer.js +1 -1
- package/dist/voice/transcription/synchronizer.js.map +1 -1
- package/dist/worker.cjs +3 -3
- package/dist/worker.cjs.map +1 -1
- package/dist/worker.d.cts +3 -0
- package/dist/worker.d.ts +3 -0
- package/dist/worker.d.ts.map +1 -1
- package/dist/worker.js +4 -4
- package/dist/worker.js.map +1 -1
- package/package.json +3 -2
- package/src/index.ts +2 -1
- package/src/inference/api_protos.ts +82 -0
- package/src/inference/index.ts +32 -0
- package/src/inference/llm.ts +463 -0
- package/src/inference/stt.ts +444 -0
- package/src/inference/tts.ts +432 -0
- package/src/inference/utils.ts +66 -0
- package/src/llm/remote_chat_context.ts +2 -2
- package/src/tts/tts.ts +1 -1
- package/src/utils.ts +11 -0
- package/src/voice/agent.ts +31 -7
- package/src/voice/agent_activity.ts +2 -0
- package/src/voice/agent_session.ts +30 -6
- package/src/voice/events.ts +6 -0
- package/src/voice/generation.ts +1 -1
- package/src/voice/room_io/_input.ts +1 -1
- package/src/voice/room_io/_output.ts +1 -1
- package/src/voice/room_io/room_io.ts +21 -2
- package/src/voice/transcription/synchronizer.ts +1 -1
- package/src/worker.ts +5 -10
package/src/index.ts
CHANGED
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
* @packageDocumentation
|
|
11
11
|
*/
|
|
12
12
|
import * as cli from './cli.js';
|
|
13
|
+
import * as inference from './inference/index.js';
|
|
13
14
|
import * as ipc from './ipc/index.js';
|
|
14
15
|
import * as llm from './llm/index.js';
|
|
15
16
|
import * as metrics from './metrics/index.js';
|
|
@@ -33,4 +34,4 @@ export * from './vad.js';
|
|
|
33
34
|
export * from './version.js';
|
|
34
35
|
export * from './worker.js';
|
|
35
36
|
|
|
36
|
-
export { cli, ipc, llm, metrics, stream, stt, tokenize, tts, voice };
|
|
37
|
+
export { cli, inference, ipc, llm, metrics, stream, stt, tokenize, tts, voice };
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2025 LiveKit, Inc.
|
|
2
|
+
//
|
|
3
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
import { z } from 'zod';
|
|
5
|
+
|
|
6
|
+
export const ttsSessionCreateEventSchema = z.object({
|
|
7
|
+
type: z.literal('session.create'),
|
|
8
|
+
sample_rate: z.string(),
|
|
9
|
+
encoding: z.string(),
|
|
10
|
+
model: z.string().optional(),
|
|
11
|
+
voice: z.string().optional(),
|
|
12
|
+
language: z.string().optional(),
|
|
13
|
+
extra: z.record(z.string(), z.unknown()),
|
|
14
|
+
transcript: z.string().optional(),
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
export const ttsInputTranscriptEventSchema = z.object({
|
|
18
|
+
type: z.literal('input_transcript'),
|
|
19
|
+
transcript: z.string(),
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
export const ttsSessionFlushEventSchema = z.object({
|
|
23
|
+
type: z.literal('session.flush'),
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
export const ttsSessionCloseEventSchema = z.object({
|
|
27
|
+
type: z.literal('session.close'),
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
export const ttsSessionCreatedEventSchema = z.object({
|
|
31
|
+
type: z.literal('session.created'),
|
|
32
|
+
session_id: z.string(),
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
export const ttsOutputAudioEventSchema = z.object({
|
|
36
|
+
type: z.literal('output_audio'),
|
|
37
|
+
audio: z.string(),
|
|
38
|
+
session_id: z.string(),
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
export const ttsDoneEventSchema = z.object({
|
|
42
|
+
type: z.literal('done'),
|
|
43
|
+
session_id: z.string(),
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
export const ttsSessionClosedEventSchema = z.object({
|
|
47
|
+
type: z.literal('session.closed'),
|
|
48
|
+
session_id: z.string(),
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
export const ttsErrorEventSchema = z.object({
|
|
52
|
+
type: z.literal('error'),
|
|
53
|
+
message: z.string(),
|
|
54
|
+
session_id: z.string(),
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
export const ttsClientEventSchema = z.discriminatedUnion('type', [
|
|
58
|
+
ttsSessionCreateEventSchema,
|
|
59
|
+
ttsInputTranscriptEventSchema,
|
|
60
|
+
ttsSessionFlushEventSchema,
|
|
61
|
+
ttsSessionCloseEventSchema,
|
|
62
|
+
]);
|
|
63
|
+
|
|
64
|
+
export const ttsServerEventSchema = z.discriminatedUnion('type', [
|
|
65
|
+
ttsSessionCreatedEventSchema,
|
|
66
|
+
ttsOutputAudioEventSchema,
|
|
67
|
+
ttsDoneEventSchema,
|
|
68
|
+
ttsSessionClosedEventSchema,
|
|
69
|
+
ttsErrorEventSchema,
|
|
70
|
+
]);
|
|
71
|
+
|
|
72
|
+
export type TtsSessionCreateEvent = z.infer<typeof ttsSessionCreateEventSchema>;
|
|
73
|
+
export type TtsInputTranscriptEvent = z.infer<typeof ttsInputTranscriptEventSchema>;
|
|
74
|
+
export type TtsSessionFlushEvent = z.infer<typeof ttsSessionFlushEventSchema>;
|
|
75
|
+
export type TtsSessionCloseEvent = z.infer<typeof ttsSessionCloseEventSchema>;
|
|
76
|
+
export type TtsSessionCreatedEvent = z.infer<typeof ttsSessionCreatedEventSchema>;
|
|
77
|
+
export type TtsOutputAudioEvent = z.infer<typeof ttsOutputAudioEventSchema>;
|
|
78
|
+
export type TtsDoneEvent = z.infer<typeof ttsDoneEventSchema>;
|
|
79
|
+
export type TtsSessionClosedEvent = z.infer<typeof ttsSessionClosedEventSchema>;
|
|
80
|
+
export type TtsErrorEvent = z.infer<typeof ttsErrorEventSchema>;
|
|
81
|
+
export type TtsClientEvent = z.infer<typeof ttsClientEventSchema>;
|
|
82
|
+
export type TtsServerEvent = z.infer<typeof ttsServerEventSchema>;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2025 LiveKit, Inc.
|
|
2
|
+
//
|
|
3
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
import * as llm from './llm.js';
|
|
5
|
+
import * as stt from './stt.js';
|
|
6
|
+
import * as tts from './tts.js';
|
|
7
|
+
|
|
8
|
+
export {
|
|
9
|
+
LLM,
|
|
10
|
+
LLMStream,
|
|
11
|
+
type ChatCompletionOptions,
|
|
12
|
+
type GatewayOptions,
|
|
13
|
+
type InferenceLLMOptions,
|
|
14
|
+
type LLMModels,
|
|
15
|
+
} from './llm.js';
|
|
16
|
+
|
|
17
|
+
export {
|
|
18
|
+
STT,
|
|
19
|
+
type STTLanguages,
|
|
20
|
+
type STTModels,
|
|
21
|
+
type ModelWithLanguage as STTModelString,
|
|
22
|
+
type STTOptions,
|
|
23
|
+
} from './stt.js';
|
|
24
|
+
|
|
25
|
+
export {
|
|
26
|
+
TTS,
|
|
27
|
+
type TTSModels,
|
|
28
|
+
type ModelWithVoice as TTSModelString,
|
|
29
|
+
type TTSOptions,
|
|
30
|
+
} from './tts.js';
|
|
31
|
+
|
|
32
|
+
export { llm, stt, tts };
|
|
@@ -0,0 +1,463 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: 2025 LiveKit, Inc.
|
|
2
|
+
//
|
|
3
|
+
// SPDX-License-Identifier: Apache-2.0
|
|
4
|
+
import OpenAI from 'openai';
|
|
5
|
+
import {
|
|
6
|
+
APIConnectionError,
|
|
7
|
+
APIStatusError,
|
|
8
|
+
APITimeoutError,
|
|
9
|
+
DEFAULT_API_CONNECT_OPTIONS,
|
|
10
|
+
toError,
|
|
11
|
+
} from '../index.js';
|
|
12
|
+
import * as llm from '../llm/index.js';
|
|
13
|
+
import type { APIConnectOptions } from '../types.js';
|
|
14
|
+
import { type AnyString, createAccessToken } from './utils.js';
|
|
15
|
+
|
|
16
|
+
const DEFAULT_BASE_URL = 'https://agent-gateway.livekit.cloud/v1';
|
|
17
|
+
|
|
18
|
+
export type OpenAIModels =
|
|
19
|
+
| 'openai/gpt-5'
|
|
20
|
+
| 'openai/gpt-5-mini'
|
|
21
|
+
| 'openai/gpt-5-nano'
|
|
22
|
+
| 'openai/gpt-4.1'
|
|
23
|
+
| 'openai/gpt-4.1-mini'
|
|
24
|
+
| 'openai/gpt-4.1-nano'
|
|
25
|
+
| 'openai/gpt-4o'
|
|
26
|
+
| 'openai/gpt-4o-mini'
|
|
27
|
+
| 'openai/gpt-oss-120b';
|
|
28
|
+
|
|
29
|
+
export type GoogleModels = 'google/gemini-2.0-flash-lite';
|
|
30
|
+
|
|
31
|
+
export type QwenModels = 'qwen/qwen3-235b-a22b-instruct';
|
|
32
|
+
|
|
33
|
+
export type KimiModels = 'moonshotai/kimi-k2-instruct';
|
|
34
|
+
|
|
35
|
+
export type DeepSeekModels = 'deepseek-ai/deepseek-v3';
|
|
36
|
+
|
|
37
|
+
type ChatCompletionPredictionContentParam = OpenAI.Chat.Completions.ChatCompletionPredictionContent;
|
|
38
|
+
type WebSearchOptions = OpenAI.Chat.Completions.ChatCompletionCreateParams.WebSearchOptions;
|
|
39
|
+
type ToolChoice = OpenAI.Chat.Completions.ChatCompletionCreateParams['tool_choice'];
|
|
40
|
+
type Verbosity = 'low' | 'medium' | 'high';
|
|
41
|
+
|
|
42
|
+
export interface ChatCompletionOptions extends Record<string, unknown> {
|
|
43
|
+
frequency_penalty?: number;
|
|
44
|
+
logit_bias?: Record<string, number>;
|
|
45
|
+
logprobs?: boolean;
|
|
46
|
+
max_completion_tokens?: number;
|
|
47
|
+
max_tokens?: number;
|
|
48
|
+
metadata?: Record<string, string>;
|
|
49
|
+
modalities?: Array<'text' | 'audio'>;
|
|
50
|
+
n?: number;
|
|
51
|
+
parallel_tool_calls?: boolean;
|
|
52
|
+
prediction?: ChatCompletionPredictionContentParam | null;
|
|
53
|
+
presence_penalty?: number;
|
|
54
|
+
prompt_cache_key?: string;
|
|
55
|
+
reasoning_effort?: 'minimal' | 'low' | 'medium' | 'high';
|
|
56
|
+
safety_identifier?: string;
|
|
57
|
+
seed?: number;
|
|
58
|
+
service_tier?: 'auto' | 'default' | 'flex' | 'scale' | 'priority';
|
|
59
|
+
stop?: string | string[];
|
|
60
|
+
store?: boolean;
|
|
61
|
+
temperature?: number;
|
|
62
|
+
top_logprobs?: number;
|
|
63
|
+
top_p?: number;
|
|
64
|
+
user?: string;
|
|
65
|
+
verbosity?: Verbosity;
|
|
66
|
+
web_search_options?: WebSearchOptions;
|
|
67
|
+
|
|
68
|
+
// livekit-typed arguments
|
|
69
|
+
tool_choice?: ToolChoice;
|
|
70
|
+
// TODO(brian): support response format
|
|
71
|
+
// response_format?: OpenAI.Chat.Completions.ChatCompletionCreateParams['response_format']
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export type LLMModels =
|
|
75
|
+
| OpenAIModels
|
|
76
|
+
| GoogleModels
|
|
77
|
+
| QwenModels
|
|
78
|
+
| KimiModels
|
|
79
|
+
| DeepSeekModels
|
|
80
|
+
| AnyString;
|
|
81
|
+
|
|
82
|
+
export interface InferenceLLMOptions {
|
|
83
|
+
model: LLMModels;
|
|
84
|
+
provider?: string;
|
|
85
|
+
baseURL: string;
|
|
86
|
+
apiKey: string;
|
|
87
|
+
apiSecret: string;
|
|
88
|
+
modelOptions: ChatCompletionOptions;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export interface GatewayOptions {
|
|
92
|
+
apiKey: string;
|
|
93
|
+
apiSecret: string;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Livekit Cloud Inference LLM
|
|
98
|
+
*/
|
|
99
|
+
export class LLM extends llm.LLM {
|
|
100
|
+
private client: OpenAI;
|
|
101
|
+
private opts: InferenceLLMOptions;
|
|
102
|
+
|
|
103
|
+
constructor(opts: {
|
|
104
|
+
model: LLMModels;
|
|
105
|
+
provider?: string;
|
|
106
|
+
baseURL?: string;
|
|
107
|
+
apiKey?: string;
|
|
108
|
+
apiSecret?: string;
|
|
109
|
+
modelOptions?: InferenceLLMOptions['modelOptions'];
|
|
110
|
+
}) {
|
|
111
|
+
super();
|
|
112
|
+
|
|
113
|
+
const { model, provider, baseURL, apiKey, apiSecret, modelOptions } = opts;
|
|
114
|
+
|
|
115
|
+
const lkBaseURL = baseURL || process.env.LIVEKIT_INFERENCE_URL || DEFAULT_BASE_URL;
|
|
116
|
+
const lkApiKey = apiKey || process.env.LIVEKIT_INFERENCE_API_KEY || process.env.LIVEKIT_API_KEY;
|
|
117
|
+
if (!lkApiKey) {
|
|
118
|
+
throw new Error('apiKey is required: pass apiKey or set LIVEKIT_API_KEY');
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const lkApiSecret =
|
|
122
|
+
apiSecret || process.env.LIVEKIT_INFERENCE_API_SECRET || process.env.LIVEKIT_API_SECRET;
|
|
123
|
+
if (!lkApiSecret) {
|
|
124
|
+
throw new Error('apiSecret is required: pass apiSecret or set LIVEKIT_API_SECRET');
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
this.opts = {
|
|
128
|
+
model,
|
|
129
|
+
provider,
|
|
130
|
+
baseURL: lkBaseURL,
|
|
131
|
+
apiKey: lkApiKey,
|
|
132
|
+
apiSecret: lkApiSecret,
|
|
133
|
+
modelOptions: modelOptions || {},
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
this.client = new OpenAI({
|
|
137
|
+
baseURL: this.opts.baseURL,
|
|
138
|
+
timeout: 15000,
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
label(): string {
|
|
143
|
+
return 'inference.LLM';
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
get model(): string {
|
|
147
|
+
return this.opts.model;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
static fromModelString(modelString: string): LLM {
|
|
151
|
+
return new LLM({ model: modelString });
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
chat({
|
|
155
|
+
chatCtx,
|
|
156
|
+
toolCtx,
|
|
157
|
+
connOptions = DEFAULT_API_CONNECT_OPTIONS,
|
|
158
|
+
parallelToolCalls,
|
|
159
|
+
toolChoice,
|
|
160
|
+
// TODO(AJS-270): Add response_format parameter support
|
|
161
|
+
extraKwargs,
|
|
162
|
+
}: {
|
|
163
|
+
chatCtx: llm.ChatContext;
|
|
164
|
+
toolCtx?: llm.ToolContext;
|
|
165
|
+
connOptions?: APIConnectOptions;
|
|
166
|
+
parallelToolCalls?: boolean;
|
|
167
|
+
toolChoice?: llm.ToolChoice;
|
|
168
|
+
// TODO(AJS-270): Add responseFormat parameter
|
|
169
|
+
extraKwargs?: Record<string, unknown>;
|
|
170
|
+
}): LLMStream {
|
|
171
|
+
let modelOptions: Record<string, unknown> = { ...(extraKwargs || {}) };
|
|
172
|
+
|
|
173
|
+
parallelToolCalls =
|
|
174
|
+
parallelToolCalls !== undefined
|
|
175
|
+
? parallelToolCalls
|
|
176
|
+
: this.opts.modelOptions.parallel_tool_calls;
|
|
177
|
+
|
|
178
|
+
if (toolCtx && Object.keys(toolCtx).length > 0 && parallelToolCalls !== undefined) {
|
|
179
|
+
modelOptions.parallel_tool_calls = parallelToolCalls;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
toolChoice = toolChoice !== undefined ? toolChoice : this.opts.modelOptions.tool_choice;
|
|
183
|
+
if (toolChoice) {
|
|
184
|
+
modelOptions.tool_choice = toolChoice;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// TODO(AJS-270): Add response_format support here
|
|
188
|
+
|
|
189
|
+
modelOptions = { ...modelOptions, ...this.opts.modelOptions };
|
|
190
|
+
|
|
191
|
+
return new LLMStream(this, {
|
|
192
|
+
model: this.opts.model,
|
|
193
|
+
provider: this.opts.provider,
|
|
194
|
+
client: this.client,
|
|
195
|
+
chatCtx,
|
|
196
|
+
toolCtx,
|
|
197
|
+
connOptions,
|
|
198
|
+
modelOptions,
|
|
199
|
+
gatewayOptions: {
|
|
200
|
+
apiKey: this.opts.apiKey,
|
|
201
|
+
apiSecret: this.opts.apiSecret,
|
|
202
|
+
},
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
export class LLMStream extends llm.LLMStream {
|
|
208
|
+
private model: LLMModels;
|
|
209
|
+
private provider?: string;
|
|
210
|
+
private providerFmt: llm.ProviderFormat;
|
|
211
|
+
private client: OpenAI;
|
|
212
|
+
private modelOptions: Record<string, unknown>;
|
|
213
|
+
|
|
214
|
+
private gatewayOptions?: GatewayOptions;
|
|
215
|
+
private toolCallId?: string;
|
|
216
|
+
private toolIndex?: number;
|
|
217
|
+
private fncName?: string;
|
|
218
|
+
private fncRawArguments?: string;
|
|
219
|
+
|
|
220
|
+
constructor(
|
|
221
|
+
llm: LLM,
|
|
222
|
+
{
|
|
223
|
+
model,
|
|
224
|
+
provider,
|
|
225
|
+
client,
|
|
226
|
+
chatCtx,
|
|
227
|
+
toolCtx,
|
|
228
|
+
gatewayOptions,
|
|
229
|
+
connOptions,
|
|
230
|
+
modelOptions,
|
|
231
|
+
providerFmt,
|
|
232
|
+
}: {
|
|
233
|
+
model: LLMModels;
|
|
234
|
+
provider?: string;
|
|
235
|
+
client: OpenAI;
|
|
236
|
+
chatCtx: llm.ChatContext;
|
|
237
|
+
toolCtx?: llm.ToolContext;
|
|
238
|
+
gatewayOptions?: GatewayOptions;
|
|
239
|
+
connOptions: APIConnectOptions;
|
|
240
|
+
modelOptions: Record<string, any>;
|
|
241
|
+
providerFmt?: llm.ProviderFormat;
|
|
242
|
+
},
|
|
243
|
+
) {
|
|
244
|
+
super(llm, { chatCtx, toolCtx, connOptions });
|
|
245
|
+
this.client = client;
|
|
246
|
+
this.gatewayOptions = gatewayOptions;
|
|
247
|
+
this.provider = provider;
|
|
248
|
+
this.providerFmt = providerFmt || 'openai';
|
|
249
|
+
this.modelOptions = modelOptions;
|
|
250
|
+
this.model = model;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
protected async run(): Promise<void> {
|
|
254
|
+
// current function call that we're waiting for full completion (args are streamed)
|
|
255
|
+
// (defined inside the run method to make sure the state is reset for each run/attempt)
|
|
256
|
+
let retryable = true;
|
|
257
|
+
this.toolCallId = this.fncName = this.fncRawArguments = this.toolIndex = undefined;
|
|
258
|
+
|
|
259
|
+
try {
|
|
260
|
+
const messages = (await this.chatCtx.toProviderFormat(
|
|
261
|
+
this.providerFmt,
|
|
262
|
+
)) as OpenAI.ChatCompletionMessageParam[];
|
|
263
|
+
|
|
264
|
+
const tools = this.toolCtx
|
|
265
|
+
? Object.entries(this.toolCtx).map(([name, func]) => ({
|
|
266
|
+
type: 'function' as const,
|
|
267
|
+
function: {
|
|
268
|
+
name,
|
|
269
|
+
description: func.description,
|
|
270
|
+
parameters: llm.toJsonSchema(
|
|
271
|
+
func.parameters,
|
|
272
|
+
) as unknown as OpenAI.Chat.Completions.ChatCompletionTool['function']['parameters'],
|
|
273
|
+
},
|
|
274
|
+
}))
|
|
275
|
+
: undefined;
|
|
276
|
+
|
|
277
|
+
const requestOptions: Record<string, unknown> = { ...this.modelOptions };
|
|
278
|
+
if (!tools) {
|
|
279
|
+
delete requestOptions.tool_choice;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// Dynamically set the access token for the LiveKit Agent Gateway API
|
|
283
|
+
if (this.gatewayOptions) {
|
|
284
|
+
this.client.apiKey = await createAccessToken(
|
|
285
|
+
this.gatewayOptions.apiKey,
|
|
286
|
+
this.gatewayOptions.apiSecret,
|
|
287
|
+
);
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
if (this.provider) {
|
|
291
|
+
const extraHeaders = requestOptions.extra_headers
|
|
292
|
+
? (requestOptions.extra_headers as Record<string, string>)
|
|
293
|
+
: {};
|
|
294
|
+
extraHeaders['X-LiveKit-Inference-Provider'] = this.provider;
|
|
295
|
+
requestOptions.extra_headers = extraHeaders;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
const stream = await this.client.chat.completions.create(
|
|
299
|
+
{
|
|
300
|
+
model: this.model,
|
|
301
|
+
messages,
|
|
302
|
+
tools,
|
|
303
|
+
stream: true,
|
|
304
|
+
stream_options: { include_usage: true },
|
|
305
|
+
...requestOptions,
|
|
306
|
+
},
|
|
307
|
+
{
|
|
308
|
+
timeout: this.connOptions.timeoutMs,
|
|
309
|
+
},
|
|
310
|
+
);
|
|
311
|
+
|
|
312
|
+
for await (const chunk of stream) {
|
|
313
|
+
for (const choice of chunk.choices) {
|
|
314
|
+
if (this.abortController.signal.aborted) {
|
|
315
|
+
break;
|
|
316
|
+
}
|
|
317
|
+
const chatChunk = this.parseChoice(chunk.id, choice);
|
|
318
|
+
if (chatChunk) {
|
|
319
|
+
retryable = false;
|
|
320
|
+
this.queue.put(chatChunk);
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
if (chunk.usage) {
|
|
325
|
+
const usage = chunk.usage;
|
|
326
|
+
retryable = false;
|
|
327
|
+
this.queue.put({
|
|
328
|
+
id: chunk.id,
|
|
329
|
+
usage: {
|
|
330
|
+
completionTokens: usage.completion_tokens,
|
|
331
|
+
promptTokens: usage.prompt_tokens,
|
|
332
|
+
promptCachedTokens: usage.prompt_tokens_details?.cached_tokens || 0,
|
|
333
|
+
totalTokens: usage.total_tokens,
|
|
334
|
+
},
|
|
335
|
+
});
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
} catch (error) {
|
|
339
|
+
if (error instanceof OpenAI.APIConnectionTimeoutError) {
|
|
340
|
+
throw new APITimeoutError({ options: { retryable } });
|
|
341
|
+
} else if (error instanceof OpenAI.APIError) {
|
|
342
|
+
throw new APIStatusError({
|
|
343
|
+
message: error.message,
|
|
344
|
+
options: {
|
|
345
|
+
statusCode: error.status,
|
|
346
|
+
body: error.error,
|
|
347
|
+
requestId: error.request_id,
|
|
348
|
+
retryable,
|
|
349
|
+
},
|
|
350
|
+
});
|
|
351
|
+
} else {
|
|
352
|
+
throw new APIConnectionError({
|
|
353
|
+
message: toError(error).message,
|
|
354
|
+
options: { retryable },
|
|
355
|
+
});
|
|
356
|
+
}
|
|
357
|
+
} finally {
|
|
358
|
+
this.queue.close();
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
private parseChoice(
|
|
363
|
+
id: string,
|
|
364
|
+
choice: OpenAI.ChatCompletionChunk.Choice,
|
|
365
|
+
): llm.ChatChunk | undefined {
|
|
366
|
+
const delta = choice.delta;
|
|
367
|
+
|
|
368
|
+
// https://github.com/livekit/agents/issues/688
|
|
369
|
+
// the delta can be None when using Azure OpenAI (content filtering)
|
|
370
|
+
if (delta === undefined) return undefined;
|
|
371
|
+
|
|
372
|
+
if (delta.tool_calls) {
|
|
373
|
+
// check if we have functions to calls
|
|
374
|
+
for (const tool of delta.tool_calls) {
|
|
375
|
+
if (!tool.function) {
|
|
376
|
+
continue; // oai may add other tools in the future
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/**
|
|
380
|
+
* The way OpenAI streams tool calls is a bit tricky.
|
|
381
|
+
*
|
|
382
|
+
* For any new tool call, it first emits a delta tool call with id, and function name,
|
|
383
|
+
* the rest of the delta chunks will only stream the remaining arguments string,
|
|
384
|
+
* until a new tool call is started or the tool call is finished.
|
|
385
|
+
* See below for an example.
|
|
386
|
+
*
|
|
387
|
+
* Choice(delta=ChoiceDelta(content=None, function_call=None, refusal=None, role='assistant', tool_calls=None), finish_reason=None, index=0, logprobs=None)
|
|
388
|
+
* [ChoiceDeltaToolCall(index=0, id='call_LaVeHWUHpef9K1sd5UO8TtLg', function=ChoiceDeltaToolCallFunction(arguments='', name='get_weather'), type='function')]
|
|
389
|
+
* [ChoiceDeltaToolCall(index=0, id=None, function=ChoiceDeltaToolCallFunction(arguments='{"location": "P', name=None), type=None)]
|
|
390
|
+
* [ChoiceDeltaToolCall(index=0, id=None, function=ChoiceDeltaToolCallFunction(arguments='aris}', name=None), type=None)]
|
|
391
|
+
* [ChoiceDeltaToolCall(index=1, id='call_ThU4OmMdQXnnVmpXGOCknXIB', function=ChoiceDeltaToolCallFunction(arguments='', name='get_weather'), type='function')]
|
|
392
|
+
* [ChoiceDeltaToolCall(index=1, id=None, function=ChoiceDeltaToolCallFunction(arguments='{"location": "T', name=None), type=None)]
|
|
393
|
+
* [ChoiceDeltaToolCall(index=1, id=None, function=ChoiceDeltaToolCallFunction(arguments='okyo', name=None), type=None)]
|
|
394
|
+
* Choice(delta=ChoiceDelta(content=None, function_call=None, refusal=None, role=None, tool_calls=None), finish_reason='tool_calls', index=0, logprobs=None)
|
|
395
|
+
*/
|
|
396
|
+
let callChunk: llm.ChatChunk | undefined;
|
|
397
|
+
// If we have a previous tool call and this is a new one, emit the previous
|
|
398
|
+
if (this.toolCallId && tool.id && tool.index !== this.toolIndex) {
|
|
399
|
+
callChunk = this.createRunningToolCallChunk(id, delta);
|
|
400
|
+
this.toolCallId = this.fncName = this.fncRawArguments = undefined;
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
// Start or continue building the current tool call
|
|
404
|
+
if (tool.function.name) {
|
|
405
|
+
this.toolIndex = tool.index;
|
|
406
|
+
this.toolCallId = tool.id;
|
|
407
|
+
this.fncName = tool.function.name;
|
|
408
|
+
this.fncRawArguments = tool.function.arguments || '';
|
|
409
|
+
} else if (tool.function.arguments) {
|
|
410
|
+
this.fncRawArguments = (this.fncRawArguments || '') + tool.function.arguments;
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
if (callChunk) {
|
|
414
|
+
return callChunk;
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
// If we're done with tool calls, emit the final one
|
|
420
|
+
if (
|
|
421
|
+
choice.finish_reason &&
|
|
422
|
+
['tool_calls', 'stop'].includes(choice.finish_reason) &&
|
|
423
|
+
this.toolCallId !== undefined
|
|
424
|
+
) {
|
|
425
|
+
const callChunk = this.createRunningToolCallChunk(id, delta);
|
|
426
|
+
this.toolCallId = this.fncName = this.fncRawArguments = undefined;
|
|
427
|
+
return callChunk;
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
// Regular content message
|
|
431
|
+
if (!delta.content) {
|
|
432
|
+
return undefined;
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
return {
|
|
436
|
+
id,
|
|
437
|
+
delta: {
|
|
438
|
+
role: 'assistant',
|
|
439
|
+
content: delta.content,
|
|
440
|
+
},
|
|
441
|
+
};
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
private createRunningToolCallChunk(
|
|
445
|
+
id: string,
|
|
446
|
+
delta: OpenAI.Chat.Completions.ChatCompletionChunk.Choice.Delta,
|
|
447
|
+
): llm.ChatChunk {
|
|
448
|
+
return {
|
|
449
|
+
id,
|
|
450
|
+
delta: {
|
|
451
|
+
role: 'assistant',
|
|
452
|
+
content: delta.content || undefined,
|
|
453
|
+
toolCalls: [
|
|
454
|
+
llm.FunctionCall.create({
|
|
455
|
+
callId: this.toolCallId || '',
|
|
456
|
+
name: this.fncName || '',
|
|
457
|
+
args: this.fncRawArguments || '',
|
|
458
|
+
}),
|
|
459
|
+
],
|
|
460
|
+
},
|
|
461
|
+
};
|
|
462
|
+
}
|
|
463
|
+
}
|