@livekit/agents-plugin-lemonslice 1.4.2 → 1.4.4
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/avatar.cjs +8 -2
- package/dist/avatar.cjs.map +1 -1
- package/dist/avatar.d.cts +2 -0
- package/dist/avatar.d.ts +2 -0
- package/dist/avatar.d.ts.map +1 -1
- package/dist/avatar.js +8 -2
- package/dist/avatar.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/package.json +3 -3
- package/src/avatar.ts +10 -2
package/dist/avatar.cjs
CHANGED
|
@@ -79,6 +79,12 @@ class AvatarSession extends import_agents.voice.AvatarSession {
|
|
|
79
79
|
this.avatarParticipantName = options.avatarParticipantName || AVATAR_AGENT_NAME;
|
|
80
80
|
this.connOptions = options.connOptions || import_agents.DEFAULT_API_CONNECT_OPTIONS;
|
|
81
81
|
}
|
|
82
|
+
get avatarIdentity() {
|
|
83
|
+
return this.avatarParticipantIdentity;
|
|
84
|
+
}
|
|
85
|
+
get provider() {
|
|
86
|
+
return "lemonslice";
|
|
87
|
+
}
|
|
82
88
|
/**
|
|
83
89
|
* Starts the avatar session and connects it to the agent.
|
|
84
90
|
*
|
|
@@ -121,7 +127,7 @@ class AvatarSession extends import_agents.voice.AvatarSession {
|
|
|
121
127
|
throw new LemonSliceException("failed to get local participant identity");
|
|
122
128
|
}
|
|
123
129
|
const at = new import_livekit_server_sdk.AccessToken(livekitApiKey, livekitApiSecret, {
|
|
124
|
-
identity: this.
|
|
130
|
+
identity: this.avatarIdentity,
|
|
125
131
|
name: this.avatarParticipantName
|
|
126
132
|
});
|
|
127
133
|
at.kind = "agent";
|
|
@@ -137,7 +143,7 @@ class AvatarSession extends import_agents.voice.AvatarSession {
|
|
|
137
143
|
const sessionId = await this.startAgent(livekitUrl, livekitToken);
|
|
138
144
|
agentSession.output.audio = new import_agents.voice.DataStreamAudioOutput({
|
|
139
145
|
room,
|
|
140
|
-
destinationIdentity: this.
|
|
146
|
+
destinationIdentity: this.avatarIdentity,
|
|
141
147
|
sampleRate: SAMPLE_RATE,
|
|
142
148
|
waitRemoteTrack: import_rtc_node.TrackKind.KIND_VIDEO,
|
|
143
149
|
waitPlaybackStart: true
|
package/dist/avatar.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/avatar.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2025 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport {\n type APIConnectOptions,\n APIConnectionError,\n APIStatusError,\n DEFAULT_API_CONNECT_OPTIONS,\n getJobContext,\n intervalForRetry,\n voice,\n} from '@livekit/agents';\nimport type { Room } from '@livekit/rtc-node';\nimport { TrackKind } from '@livekit/rtc-node';\nimport type { VideoGrant } from 'livekit-server-sdk';\nimport { AccessToken } from 'livekit-server-sdk';\nimport { log } from './log.js';\n\nconst ATTRIBUTE_PUBLISH_ON_BEHALF = 'lk.publish_on_behalf';\nconst DEFAULT_API_URL = 'https://lemonslice.com/api/liveai/sessions';\nconst SAMPLE_RATE = 16000;\nconst AVATAR_AGENT_IDENTITY = 'lemonslice-avatar-agent';\nconst AVATAR_AGENT_NAME = 'lemonslice-avatar-agent';\n\n/**\n * Exception thrown when there are errors with the LemonSlice API.\n */\nexport class LemonSliceException extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'LemonSliceException';\n }\n}\n\n/**\n * Options for configuring an AvatarSession.\n */\nexport interface AvatarSessionOptions {\n /**\n * The ID of the LemonSlice agent to add to the session.\n * Either agentId or agentImageUrl must be provided.\n */\n agentId?: string | null;\n /**\n * The URL of the image to use as the agent's avatar.\n * Either agentId or agentImageUrl must be provided.\n */\n agentImageUrl?: string | null;\n /**\n * A prompt that subtly influences the avatar's movements and expressions.\n */\n agentPrompt?: string | null;\n /**\n * The idle timeout, in seconds. Defaults to 60 seconds.\n */\n idleTimeout?: number | null;\n /**\n * Additional payload fields to merge into the LemonSlice session creation request.\n */\n extraPayload?: Record<string, unknown> | null;\n /**\n * The LemonSlice API URL. Defaults to https://lemonslice.com/api/liveai/sessions\n * or LEMONSLICE_API_URL environment variable.\n */\n apiUrl?: string;\n /**\n * The LemonSlice API key. Can also be set via LEMONSLICE_API_KEY environment variable.\n */\n apiKey?: string;\n /**\n * The identity of the avatar participant in the room. Defaults to 'lemonslice-avatar-agent'.\n */\n avatarParticipantIdentity?: string;\n /**\n * The name of the avatar participant in the room. Defaults to 'lemonslice-avatar-agent'.\n */\n avatarParticipantName?: string;\n /**\n * Connection options for API requests.\n */\n connOptions?: APIConnectOptions;\n}\n\n/**\n * Options for starting an avatar session.\n */\nexport interface StartOptions {\n /**\n * LiveKit server URL. Falls back to LIVEKIT_URL environment variable.\n */\n livekitUrl?: string;\n /**\n * LiveKit API key. Falls back to LIVEKIT_API_KEY environment variable.\n */\n livekitApiKey?: string;\n /**\n * LiveKit API secret. Falls back to LIVEKIT_API_SECRET environment variable.\n */\n livekitApiSecret?: string;\n}\n\n/**\n * A LemonSlice avatar session.\n *\n * This class manages the connection between a LiveKit agent and a LemonSlice avatar,\n * routing agent audio output to the avatar for visual representation.\n *\n * @example\n * ```typescript\n * // Using an agent ID\n * const avatar = new AvatarSession({\n * agentId: 'your-agent-id',\n * apiKey: 'your-lemonslice-api-key',\n * });\n * await avatar.start(agentSession, room);\n *\n * // Using a custom avatar image\n * const avatar = new AvatarSession({\n * agentImageUrl: 'your-image-url',\n * apiKey: 'your-lemonslice-api-key',\n * });\n * await avatar.start(agentSession, room);\n * ```\n */\nexport class AvatarSession extends voice.AvatarSession {\n private agentId: string | null;\n private agentImageUrl: string | null;\n private agentPrompt: string | null;\n private idleTimeout: number | null;\n private extraPayload: Record<string, unknown> | null;\n private apiUrl: string;\n private apiKey: string;\n private avatarParticipantIdentity: string;\n private avatarParticipantName: string;\n private connOptions: APIConnectOptions;\n\n #logger = log();\n\n /**\n * Creates a new AvatarSession.\n *\n * @param options - Configuration options for the avatar session\n * @throws LemonSliceException if invalid agentId or agentImageUrl is provided, or if LemonSlice API key is not set\n */\n constructor(options: AvatarSessionOptions = {}) {\n super();\n this.agentId = options.agentId ?? null;\n this.agentImageUrl = options.agentImageUrl ?? null;\n\n if (!this.agentId && !this.agentImageUrl) {\n throw new LemonSliceException('Missing agentId or agentImageUrl');\n }\n if (this.agentId && this.agentImageUrl) {\n throw new LemonSliceException('Only one of agentId or agentImageUrl can be provided');\n }\n\n this.agentPrompt = options.agentPrompt ?? null;\n this.idleTimeout = options.idleTimeout ?? null;\n this.extraPayload = options.extraPayload ?? null;\n\n this.apiUrl = options.apiUrl || process.env.LEMONSLICE_API_URL || DEFAULT_API_URL;\n this.apiKey = options.apiKey || process.env.LEMONSLICE_API_KEY || '';\n\n if (!this.apiKey) {\n throw new LemonSliceException(\n 'The api_key must be set either by passing apiKey to the client or ' +\n 'by setting the LEMONSLICE_API_KEY environment variable',\n );\n }\n\n this.avatarParticipantIdentity = options.avatarParticipantIdentity || AVATAR_AGENT_IDENTITY;\n this.avatarParticipantName = options.avatarParticipantName || AVATAR_AGENT_NAME;\n this.connOptions = options.connOptions || DEFAULT_API_CONNECT_OPTIONS;\n }\n\n /**\n * Starts the avatar session and connects it to the agent.\n *\n * This method:\n * 1. Creates a LiveKit token for the avatar participant\n * 2. Calls the LemonSlice API to start the avatar session\n * 3. Configures the agent's audio output to stream to the avatar\n *\n * @param agentSession - The agent session to connect to the avatar\n * @param room - The LiveKit room where the avatar will join\n * @param options - Optional LiveKit credentials (falls back to environment variables)\n * @throws LemonSliceException if LiveKit credentials are not available or if the avatar session fails to start\n * @returns The session ID of the LemonSlice session\n */\n async start(\n agentSession: voice.AgentSession,\n room: Room,\n options: StartOptions = {},\n ): Promise<string> {\n await super.start(agentSession, room);\n\n const livekitUrl = options.livekitUrl || process.env.LIVEKIT_URL;\n const livekitApiKey = options.livekitApiKey || process.env.LIVEKIT_API_KEY;\n const livekitApiSecret = options.livekitApiSecret || process.env.LIVEKIT_API_SECRET;\n\n if (!livekitUrl || !livekitApiKey || !livekitApiSecret) {\n throw new LemonSliceException(\n 'livekitUrl, livekitApiKey, and livekitApiSecret must be set ' +\n 'by arguments or environment variables',\n );\n }\n\n let localParticipantIdentity: string;\n try {\n const jobCtx = getJobContext();\n localParticipantIdentity = jobCtx.agent?.identity || '';\n if (!localParticipantIdentity && room.localParticipant) {\n localParticipantIdentity = room.localParticipant.identity;\n }\n } catch {\n if (!room.isConnected || !room.localParticipant) {\n throw new LemonSliceException('failed to get local participant identity');\n }\n localParticipantIdentity = room.localParticipant.identity;\n }\n\n if (!localParticipantIdentity) {\n throw new LemonSliceException('failed to get local participant identity');\n }\n\n const at = new AccessToken(livekitApiKey, livekitApiSecret, {\n identity: this.avatarParticipantIdentity,\n name: this.avatarParticipantName,\n });\n at.kind = 'agent';\n\n at.addGrant({\n roomJoin: true,\n room: room.name,\n } as VideoGrant);\n\n // allow the avatar agent to publish audio and video on behalf of your local agent\n at.attributes = {\n [ATTRIBUTE_PUBLISH_ON_BEHALF]: localParticipantIdentity,\n };\n\n const livekitToken = await at.toJwt();\n\n this.#logger.debug('starting avatar session');\n const sessionId = await this.startAgent(livekitUrl, livekitToken);\n\n agentSession.output.audio = new voice.DataStreamAudioOutput({\n room,\n destinationIdentity: this.avatarParticipantIdentity,\n sampleRate: SAMPLE_RATE,\n waitRemoteTrack: TrackKind.KIND_VIDEO,\n waitPlaybackStart: true,\n });\n\n return sessionId;\n }\n\n private async startAgent(livekitUrl: string, livekitToken: string): Promise<string> {\n for (let i = 0; i <= this.connOptions.maxRetry; i++) {\n try {\n const payload: Record<string, any> = {\n transport_type: 'livekit',\n properties: {\n livekit_url: livekitUrl,\n livekit_token: livekitToken,\n },\n };\n\n if (this.agentId) {\n payload.agent_id = this.agentId;\n }\n\n if (this.agentImageUrl) {\n payload.agent_image_url = this.agentImageUrl;\n }\n\n if (this.agentPrompt) {\n payload.agent_prompt = this.agentPrompt;\n }\n\n if (this.idleTimeout !== null) {\n payload.idle_timeout = this.idleTimeout;\n }\n\n if (this.extraPayload) {\n Object.assign(payload, this.extraPayload);\n }\n\n const response = await fetch(this.apiUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'X-API-Key': this.apiKey,\n },\n body: JSON.stringify(payload),\n signal: AbortSignal.timeout(this.connOptions.timeoutMs),\n });\n\n if (!response.ok) {\n const text = await response.text();\n throw new APIStatusError({\n message: 'Server returned an error',\n options: { statusCode: response.status, body: { error: text } },\n });\n }\n const data = (await response.json()) as { session_id: string };\n return data.session_id;\n } catch (e) {\n if (e instanceof APIStatusError && !e.retryable) {\n throw e;\n }\n if (e instanceof APIConnectionError) {\n this.#logger.warn({ error: String(e) }, 'failed to call lemonslice api');\n } else {\n this.#logger.error({ error: e }, 'failed to call lemonslice api');\n }\n\n if (i <= this.connOptions.maxRetry - 1) {\n await new Promise((resolve) =>\n setTimeout(resolve, intervalForRetry(this.connOptions, i)),\n );\n }\n }\n }\n\n throw new APIConnectionError({\n message: 'Failed to start LemonSlice Avatar Session after all retries',\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,oBAQO;AAEP,sBAA0B;AAE1B,gCAA4B;AAC5B,iBAAoB;AAEpB,MAAM,8BAA8B;AACpC,MAAM,kBAAkB;AACxB,MAAM,cAAc;AACpB,MAAM,wBAAwB;AAC9B,MAAM,oBAAoB;AAKnB,MAAM,4BAA4B,MAAM;AAAA,EAC7C,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AA4FO,MAAM,sBAAsB,oBAAM,cAAc;AAAA,EAC7C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAER,cAAU,gBAAI;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQd,YAAY,UAAgC,CAAC,GAAG;AAC9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"sources":["../src/avatar.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2025 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport {\n type APIConnectOptions,\n APIConnectionError,\n APIStatusError,\n DEFAULT_API_CONNECT_OPTIONS,\n getJobContext,\n intervalForRetry,\n voice,\n} from '@livekit/agents';\nimport type { Room } from '@livekit/rtc-node';\nimport { TrackKind } from '@livekit/rtc-node';\nimport type { VideoGrant } from 'livekit-server-sdk';\nimport { AccessToken } from 'livekit-server-sdk';\nimport { log } from './log.js';\n\nconst ATTRIBUTE_PUBLISH_ON_BEHALF = 'lk.publish_on_behalf';\nconst DEFAULT_API_URL = 'https://lemonslice.com/api/liveai/sessions';\nconst SAMPLE_RATE = 16000;\nconst AVATAR_AGENT_IDENTITY = 'lemonslice-avatar-agent';\nconst AVATAR_AGENT_NAME = 'lemonslice-avatar-agent';\n\n/**\n * Exception thrown when there are errors with the LemonSlice API.\n */\nexport class LemonSliceException extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'LemonSliceException';\n }\n}\n\n/**\n * Options for configuring an AvatarSession.\n */\nexport interface AvatarSessionOptions {\n /**\n * The ID of the LemonSlice agent to add to the session.\n * Either agentId or agentImageUrl must be provided.\n */\n agentId?: string | null;\n /**\n * The URL of the image to use as the agent's avatar.\n * Either agentId or agentImageUrl must be provided.\n */\n agentImageUrl?: string | null;\n /**\n * A prompt that subtly influences the avatar's movements and expressions.\n */\n agentPrompt?: string | null;\n /**\n * The idle timeout, in seconds. Defaults to 60 seconds.\n */\n idleTimeout?: number | null;\n /**\n * Additional payload fields to merge into the LemonSlice session creation request.\n */\n extraPayload?: Record<string, unknown> | null;\n /**\n * The LemonSlice API URL. Defaults to https://lemonslice.com/api/liveai/sessions\n * or LEMONSLICE_API_URL environment variable.\n */\n apiUrl?: string;\n /**\n * The LemonSlice API key. Can also be set via LEMONSLICE_API_KEY environment variable.\n */\n apiKey?: string;\n /**\n * The identity of the avatar participant in the room. Defaults to 'lemonslice-avatar-agent'.\n */\n avatarParticipantIdentity?: string;\n /**\n * The name of the avatar participant in the room. Defaults to 'lemonslice-avatar-agent'.\n */\n avatarParticipantName?: string;\n /**\n * Connection options for API requests.\n */\n connOptions?: APIConnectOptions;\n}\n\n/**\n * Options for starting an avatar session.\n */\nexport interface StartOptions {\n /**\n * LiveKit server URL. Falls back to LIVEKIT_URL environment variable.\n */\n livekitUrl?: string;\n /**\n * LiveKit API key. Falls back to LIVEKIT_API_KEY environment variable.\n */\n livekitApiKey?: string;\n /**\n * LiveKit API secret. Falls back to LIVEKIT_API_SECRET environment variable.\n */\n livekitApiSecret?: string;\n}\n\n/**\n * A LemonSlice avatar session.\n *\n * This class manages the connection between a LiveKit agent and a LemonSlice avatar,\n * routing agent audio output to the avatar for visual representation.\n *\n * @example\n * ```typescript\n * // Using an agent ID\n * const avatar = new AvatarSession({\n * agentId: 'your-agent-id',\n * apiKey: 'your-lemonslice-api-key',\n * });\n * await avatar.start(agentSession, room);\n *\n * // Using a custom avatar image\n * const avatar = new AvatarSession({\n * agentImageUrl: 'your-image-url',\n * apiKey: 'your-lemonslice-api-key',\n * });\n * await avatar.start(agentSession, room);\n * ```\n */\nexport class AvatarSession extends voice.AvatarSession {\n private agentId: string | null;\n private agentImageUrl: string | null;\n private agentPrompt: string | null;\n private idleTimeout: number | null;\n private extraPayload: Record<string, unknown> | null;\n private apiUrl: string;\n private apiKey: string;\n private avatarParticipantIdentity: string;\n private avatarParticipantName: string;\n private connOptions: APIConnectOptions;\n\n #logger = log();\n\n /**\n * Creates a new AvatarSession.\n *\n * @param options - Configuration options for the avatar session\n * @throws LemonSliceException if invalid agentId or agentImageUrl is provided, or if LemonSlice API key is not set\n */\n constructor(options: AvatarSessionOptions = {}) {\n super();\n this.agentId = options.agentId ?? null;\n this.agentImageUrl = options.agentImageUrl ?? null;\n\n if (!this.agentId && !this.agentImageUrl) {\n throw new LemonSliceException('Missing agentId or agentImageUrl');\n }\n if (this.agentId && this.agentImageUrl) {\n throw new LemonSliceException('Only one of agentId or agentImageUrl can be provided');\n }\n\n this.agentPrompt = options.agentPrompt ?? null;\n this.idleTimeout = options.idleTimeout ?? null;\n this.extraPayload = options.extraPayload ?? null;\n\n this.apiUrl = options.apiUrl || process.env.LEMONSLICE_API_URL || DEFAULT_API_URL;\n this.apiKey = options.apiKey || process.env.LEMONSLICE_API_KEY || '';\n\n if (!this.apiKey) {\n throw new LemonSliceException(\n 'The api_key must be set either by passing apiKey to the client or ' +\n 'by setting the LEMONSLICE_API_KEY environment variable',\n );\n }\n\n this.avatarParticipantIdentity = options.avatarParticipantIdentity || AVATAR_AGENT_IDENTITY;\n this.avatarParticipantName = options.avatarParticipantName || AVATAR_AGENT_NAME;\n this.connOptions = options.connOptions || DEFAULT_API_CONNECT_OPTIONS;\n }\n\n override get avatarIdentity(): string {\n return this.avatarParticipantIdentity;\n }\n\n override get provider(): string {\n return 'lemonslice';\n }\n\n /**\n * Starts the avatar session and connects it to the agent.\n *\n * This method:\n * 1. Creates a LiveKit token for the avatar participant\n * 2. Calls the LemonSlice API to start the avatar session\n * 3. Configures the agent's audio output to stream to the avatar\n *\n * @param agentSession - The agent session to connect to the avatar\n * @param room - The LiveKit room where the avatar will join\n * @param options - Optional LiveKit credentials (falls back to environment variables)\n * @throws LemonSliceException if LiveKit credentials are not available or if the avatar session fails to start\n * @returns The session ID of the LemonSlice session\n */\n async start(\n agentSession: voice.AgentSession,\n room: Room,\n options: StartOptions = {},\n ): Promise<string> {\n await super.start(agentSession, room);\n\n const livekitUrl = options.livekitUrl || process.env.LIVEKIT_URL;\n const livekitApiKey = options.livekitApiKey || process.env.LIVEKIT_API_KEY;\n const livekitApiSecret = options.livekitApiSecret || process.env.LIVEKIT_API_SECRET;\n\n if (!livekitUrl || !livekitApiKey || !livekitApiSecret) {\n throw new LemonSliceException(\n 'livekitUrl, livekitApiKey, and livekitApiSecret must be set ' +\n 'by arguments or environment variables',\n );\n }\n\n let localParticipantIdentity: string;\n try {\n const jobCtx = getJobContext();\n localParticipantIdentity = jobCtx.agent?.identity || '';\n if (!localParticipantIdentity && room.localParticipant) {\n localParticipantIdentity = room.localParticipant.identity;\n }\n } catch {\n if (!room.isConnected || !room.localParticipant) {\n throw new LemonSliceException('failed to get local participant identity');\n }\n localParticipantIdentity = room.localParticipant.identity;\n }\n\n if (!localParticipantIdentity) {\n throw new LemonSliceException('failed to get local participant identity');\n }\n\n const at = new AccessToken(livekitApiKey, livekitApiSecret, {\n identity: this.avatarIdentity,\n name: this.avatarParticipantName,\n });\n at.kind = 'agent';\n\n at.addGrant({\n roomJoin: true,\n room: room.name,\n } as VideoGrant);\n\n // allow the avatar agent to publish audio and video on behalf of your local agent\n at.attributes = {\n [ATTRIBUTE_PUBLISH_ON_BEHALF]: localParticipantIdentity,\n };\n\n const livekitToken = await at.toJwt();\n\n this.#logger.debug('starting avatar session');\n const sessionId = await this.startAgent(livekitUrl, livekitToken);\n\n agentSession.output.audio = new voice.DataStreamAudioOutput({\n room,\n destinationIdentity: this.avatarIdentity,\n sampleRate: SAMPLE_RATE,\n waitRemoteTrack: TrackKind.KIND_VIDEO,\n waitPlaybackStart: true,\n });\n\n return sessionId;\n }\n\n private async startAgent(livekitUrl: string, livekitToken: string): Promise<string> {\n for (let i = 0; i <= this.connOptions.maxRetry; i++) {\n try {\n const payload: Record<string, any> = {\n transport_type: 'livekit',\n properties: {\n livekit_url: livekitUrl,\n livekit_token: livekitToken,\n },\n };\n\n if (this.agentId) {\n payload.agent_id = this.agentId;\n }\n\n if (this.agentImageUrl) {\n payload.agent_image_url = this.agentImageUrl;\n }\n\n if (this.agentPrompt) {\n payload.agent_prompt = this.agentPrompt;\n }\n\n if (this.idleTimeout !== null) {\n payload.idle_timeout = this.idleTimeout;\n }\n\n if (this.extraPayload) {\n Object.assign(payload, this.extraPayload);\n }\n\n const response = await fetch(this.apiUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'X-API-Key': this.apiKey,\n },\n body: JSON.stringify(payload),\n signal: AbortSignal.timeout(this.connOptions.timeoutMs),\n });\n\n if (!response.ok) {\n const text = await response.text();\n throw new APIStatusError({\n message: 'Server returned an error',\n options: { statusCode: response.status, body: { error: text } },\n });\n }\n const data = (await response.json()) as { session_id: string };\n return data.session_id;\n } catch (e) {\n if (e instanceof APIStatusError && !e.retryable) {\n throw e;\n }\n if (e instanceof APIConnectionError) {\n this.#logger.warn({ error: String(e) }, 'failed to call lemonslice api');\n } else {\n this.#logger.error({ error: e }, 'failed to call lemonslice api');\n }\n\n if (i <= this.connOptions.maxRetry - 1) {\n await new Promise((resolve) =>\n setTimeout(resolve, intervalForRetry(this.connOptions, i)),\n );\n }\n }\n }\n\n throw new APIConnectionError({\n message: 'Failed to start LemonSlice Avatar Session after all retries',\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAGA,oBAQO;AAEP,sBAA0B;AAE1B,gCAA4B;AAC5B,iBAAoB;AAEpB,MAAM,8BAA8B;AACpC,MAAM,kBAAkB;AACxB,MAAM,cAAc;AACpB,MAAM,wBAAwB;AAC9B,MAAM,oBAAoB;AAKnB,MAAM,4BAA4B,MAAM;AAAA,EAC7C,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AA4FO,MAAM,sBAAsB,oBAAM,cAAc;AAAA,EAC7C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAER,cAAU,gBAAI;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQd,YAAY,UAAgC,CAAC,GAAG;AAC9C,UAAM;AACN,SAAK,UAAU,QAAQ,WAAW;AAClC,SAAK,gBAAgB,QAAQ,iBAAiB;AAE9C,QAAI,CAAC,KAAK,WAAW,CAAC,KAAK,eAAe;AACxC,YAAM,IAAI,oBAAoB,kCAAkC;AA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|
|
|
113
113
|
* @throws LemonSliceException if invalid agentId or agentImageUrl is provided, or if LemonSlice API key is not set
|
|
114
114
|
*/
|
|
115
115
|
constructor(options?: AvatarSessionOptions);
|
|
116
|
+
get avatarIdentity(): string;
|
|
117
|
+
get provider(): string;
|
|
116
118
|
/**
|
|
117
119
|
* Starts the avatar session and connects it to the agent.
|
|
118
120
|
*
|
package/dist/avatar.d.ts
CHANGED
|
@@ -113,6 +113,8 @@ export declare class AvatarSession extends voice.AvatarSession {
|
|
|
113
113
|
* @throws LemonSliceException if invalid agentId or agentImageUrl is provided, or if LemonSlice API key is not set
|
|
114
114
|
*/
|
|
115
115
|
constructor(options?: AvatarSessionOptions);
|
|
116
|
+
get avatarIdentity(): string;
|
|
117
|
+
get provider(): string;
|
|
116
118
|
/**
|
|
117
119
|
* Starts the avatar session and connects it to the agent.
|
|
118
120
|
*
|
package/dist/avatar.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"avatar.d.ts","sourceRoot":"","sources":["../src/avatar.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,KAAK,iBAAiB,EAMtB,KAAK,EACN,MAAM,iBAAiB,CAAC;AACzB,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,mBAAmB,CAAC;AAY9C;;GAEG;AACH,qBAAa,mBAAoB,SAAQ,KAAK;gBAChC,OAAO,EAAE,MAAM;CAI5B;AAED;;GAEG;AACH,MAAM,WAAW,oBAAoB;IACnC;;;OAGG;IACH,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB;;;OAGG;IACH,aAAa,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC9B;;OAEG;IACH,WAAW,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B;;OAEG;IACH,WAAW,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAA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AAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,yBAAyB,CAAS;IAC1C,OAAO,CAAC,qBAAqB,CAAS;IACtC,OAAO,CAAC,WAAW,CAAoB;IAIvC;;;;;OAKG;gBACS,OAAO,GAAE,oBAAyB;IA+B9C,IAAa,cAAc,IAAI,MAAM,CAEpC;IAED,IAAa,QAAQ,IAAI,MAAM,CAE9B;IAED;;;;;;;;;;;;;OAaG;IACG,KAAK,CACT,YAAY,EAAE,KAAK,CAAC,YAAY,EAChC,IAAI,EAAE,IAAI,EACV,OAAO,GAAE,YAAiB,GACzB,OAAO,CAAC,MAAM,CAAC;YAgEJ,UAAU;CAwEzB"}
|
package/dist/avatar.js
CHANGED
|
@@ -62,6 +62,12 @@ class AvatarSession extends voice.AvatarSession {
|
|
|
62
62
|
this.avatarParticipantName = options.avatarParticipantName || AVATAR_AGENT_NAME;
|
|
63
63
|
this.connOptions = options.connOptions || DEFAULT_API_CONNECT_OPTIONS;
|
|
64
64
|
}
|
|
65
|
+
get avatarIdentity() {
|
|
66
|
+
return this.avatarParticipantIdentity;
|
|
67
|
+
}
|
|
68
|
+
get provider() {
|
|
69
|
+
return "lemonslice";
|
|
70
|
+
}
|
|
65
71
|
/**
|
|
66
72
|
* Starts the avatar session and connects it to the agent.
|
|
67
73
|
*
|
|
@@ -104,7 +110,7 @@ class AvatarSession extends voice.AvatarSession {
|
|
|
104
110
|
throw new LemonSliceException("failed to get local participant identity");
|
|
105
111
|
}
|
|
106
112
|
const at = new AccessToken(livekitApiKey, livekitApiSecret, {
|
|
107
|
-
identity: this.
|
|
113
|
+
identity: this.avatarIdentity,
|
|
108
114
|
name: this.avatarParticipantName
|
|
109
115
|
});
|
|
110
116
|
at.kind = "agent";
|
|
@@ -120,7 +126,7 @@ class AvatarSession extends voice.AvatarSession {
|
|
|
120
126
|
const sessionId = await this.startAgent(livekitUrl, livekitToken);
|
|
121
127
|
agentSession.output.audio = new voice.DataStreamAudioOutput({
|
|
122
128
|
room,
|
|
123
|
-
destinationIdentity: this.
|
|
129
|
+
destinationIdentity: this.avatarIdentity,
|
|
124
130
|
sampleRate: SAMPLE_RATE,
|
|
125
131
|
waitRemoteTrack: TrackKind.KIND_VIDEO,
|
|
126
132
|
waitPlaybackStart: true
|
package/dist/avatar.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/avatar.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2025 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport {\n type APIConnectOptions,\n APIConnectionError,\n APIStatusError,\n DEFAULT_API_CONNECT_OPTIONS,\n getJobContext,\n intervalForRetry,\n voice,\n} from '@livekit/agents';\nimport type { Room } from '@livekit/rtc-node';\nimport { TrackKind } from '@livekit/rtc-node';\nimport type { VideoGrant } from 'livekit-server-sdk';\nimport { AccessToken } from 'livekit-server-sdk';\nimport { log } from './log.js';\n\nconst ATTRIBUTE_PUBLISH_ON_BEHALF = 'lk.publish_on_behalf';\nconst DEFAULT_API_URL = 'https://lemonslice.com/api/liveai/sessions';\nconst SAMPLE_RATE = 16000;\nconst AVATAR_AGENT_IDENTITY = 'lemonslice-avatar-agent';\nconst AVATAR_AGENT_NAME = 'lemonslice-avatar-agent';\n\n/**\n * Exception thrown when there are errors with the LemonSlice API.\n */\nexport class LemonSliceException extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'LemonSliceException';\n }\n}\n\n/**\n * Options for configuring an AvatarSession.\n */\nexport interface AvatarSessionOptions {\n /**\n * The ID of the LemonSlice agent to add to the session.\n * Either agentId or agentImageUrl must be provided.\n */\n agentId?: string | null;\n /**\n * The URL of the image to use as the agent's avatar.\n * Either agentId or agentImageUrl must be provided.\n */\n agentImageUrl?: string | null;\n /**\n * A prompt that subtly influences the avatar's movements and expressions.\n */\n agentPrompt?: string | null;\n /**\n * The idle timeout, in seconds. Defaults to 60 seconds.\n */\n idleTimeout?: number | null;\n /**\n * Additional payload fields to merge into the LemonSlice session creation request.\n */\n extraPayload?: Record<string, unknown> | null;\n /**\n * The LemonSlice API URL. Defaults to https://lemonslice.com/api/liveai/sessions\n * or LEMONSLICE_API_URL environment variable.\n */\n apiUrl?: string;\n /**\n * The LemonSlice API key. Can also be set via LEMONSLICE_API_KEY environment variable.\n */\n apiKey?: string;\n /**\n * The identity of the avatar participant in the room. Defaults to 'lemonslice-avatar-agent'.\n */\n avatarParticipantIdentity?: string;\n /**\n * The name of the avatar participant in the room. Defaults to 'lemonslice-avatar-agent'.\n */\n avatarParticipantName?: string;\n /**\n * Connection options for API requests.\n */\n connOptions?: APIConnectOptions;\n}\n\n/**\n * Options for starting an avatar session.\n */\nexport interface StartOptions {\n /**\n * LiveKit server URL. Falls back to LIVEKIT_URL environment variable.\n */\n livekitUrl?: string;\n /**\n * LiveKit API key. Falls back to LIVEKIT_API_KEY environment variable.\n */\n livekitApiKey?: string;\n /**\n * LiveKit API secret. Falls back to LIVEKIT_API_SECRET environment variable.\n */\n livekitApiSecret?: string;\n}\n\n/**\n * A LemonSlice avatar session.\n *\n * This class manages the connection between a LiveKit agent and a LemonSlice avatar,\n * routing agent audio output to the avatar for visual representation.\n *\n * @example\n * ```typescript\n * // Using an agent ID\n * const avatar = new AvatarSession({\n * agentId: 'your-agent-id',\n * apiKey: 'your-lemonslice-api-key',\n * });\n * await avatar.start(agentSession, room);\n *\n * // Using a custom avatar image\n * const avatar = new AvatarSession({\n * agentImageUrl: 'your-image-url',\n * apiKey: 'your-lemonslice-api-key',\n * });\n * await avatar.start(agentSession, room);\n * ```\n */\nexport class AvatarSession extends voice.AvatarSession {\n private agentId: string | null;\n private agentImageUrl: string | null;\n private agentPrompt: string | null;\n private idleTimeout: number | null;\n private extraPayload: Record<string, unknown> | null;\n private apiUrl: string;\n private apiKey: string;\n private avatarParticipantIdentity: string;\n private avatarParticipantName: string;\n private connOptions: APIConnectOptions;\n\n #logger = log();\n\n /**\n * Creates a new AvatarSession.\n *\n * @param options - Configuration options for the avatar session\n * @throws LemonSliceException if invalid agentId or agentImageUrl is provided, or if LemonSlice API key is not set\n */\n constructor(options: AvatarSessionOptions = {}) {\n super();\n this.agentId = options.agentId ?? null;\n this.agentImageUrl = options.agentImageUrl ?? null;\n\n if (!this.agentId && !this.agentImageUrl) {\n throw new LemonSliceException('Missing agentId or agentImageUrl');\n }\n if (this.agentId && this.agentImageUrl) {\n throw new LemonSliceException('Only one of agentId or agentImageUrl can be provided');\n }\n\n this.agentPrompt = options.agentPrompt ?? null;\n this.idleTimeout = options.idleTimeout ?? null;\n this.extraPayload = options.extraPayload ?? null;\n\n this.apiUrl = options.apiUrl || process.env.LEMONSLICE_API_URL || DEFAULT_API_URL;\n this.apiKey = options.apiKey || process.env.LEMONSLICE_API_KEY || '';\n\n if (!this.apiKey) {\n throw new LemonSliceException(\n 'The api_key must be set either by passing apiKey to the client or ' +\n 'by setting the LEMONSLICE_API_KEY environment variable',\n );\n }\n\n this.avatarParticipantIdentity = options.avatarParticipantIdentity || AVATAR_AGENT_IDENTITY;\n this.avatarParticipantName = options.avatarParticipantName || AVATAR_AGENT_NAME;\n this.connOptions = options.connOptions || DEFAULT_API_CONNECT_OPTIONS;\n }\n\n /**\n * Starts the avatar session and connects it to the agent.\n *\n * This method:\n * 1. Creates a LiveKit token for the avatar participant\n * 2. Calls the LemonSlice API to start the avatar session\n * 3. Configures the agent's audio output to stream to the avatar\n *\n * @param agentSession - The agent session to connect to the avatar\n * @param room - The LiveKit room where the avatar will join\n * @param options - Optional LiveKit credentials (falls back to environment variables)\n * @throws LemonSliceException if LiveKit credentials are not available or if the avatar session fails to start\n * @returns The session ID of the LemonSlice session\n */\n async start(\n agentSession: voice.AgentSession,\n room: Room,\n options: StartOptions = {},\n ): Promise<string> {\n await super.start(agentSession, room);\n\n const livekitUrl = options.livekitUrl || process.env.LIVEKIT_URL;\n const livekitApiKey = options.livekitApiKey || process.env.LIVEKIT_API_KEY;\n const livekitApiSecret = options.livekitApiSecret || process.env.LIVEKIT_API_SECRET;\n\n if (!livekitUrl || !livekitApiKey || !livekitApiSecret) {\n throw new LemonSliceException(\n 'livekitUrl, livekitApiKey, and livekitApiSecret must be set ' +\n 'by arguments or environment variables',\n );\n }\n\n let localParticipantIdentity: string;\n try {\n const jobCtx = getJobContext();\n localParticipantIdentity = jobCtx.agent?.identity || '';\n if (!localParticipantIdentity && room.localParticipant) {\n localParticipantIdentity = room.localParticipant.identity;\n }\n } catch {\n if (!room.isConnected || !room.localParticipant) {\n throw new LemonSliceException('failed to get local participant identity');\n }\n localParticipantIdentity = room.localParticipant.identity;\n }\n\n if (!localParticipantIdentity) {\n throw new LemonSliceException('failed to get local participant identity');\n }\n\n const at = new AccessToken(livekitApiKey, livekitApiSecret, {\n identity: this.avatarParticipantIdentity,\n name: this.avatarParticipantName,\n });\n at.kind = 'agent';\n\n at.addGrant({\n roomJoin: true,\n room: room.name,\n } as VideoGrant);\n\n // allow the avatar agent to publish audio and video on behalf of your local agent\n at.attributes = {\n [ATTRIBUTE_PUBLISH_ON_BEHALF]: localParticipantIdentity,\n };\n\n const livekitToken = await at.toJwt();\n\n this.#logger.debug('starting avatar session');\n const sessionId = await this.startAgent(livekitUrl, livekitToken);\n\n agentSession.output.audio = new voice.DataStreamAudioOutput({\n room,\n destinationIdentity: this.avatarParticipantIdentity,\n sampleRate: SAMPLE_RATE,\n waitRemoteTrack: TrackKind.KIND_VIDEO,\n waitPlaybackStart: true,\n });\n\n return sessionId;\n }\n\n private async startAgent(livekitUrl: string, livekitToken: string): Promise<string> {\n for (let i = 0; i <= this.connOptions.maxRetry; i++) {\n try {\n const payload: Record<string, any> = {\n transport_type: 'livekit',\n properties: {\n livekit_url: livekitUrl,\n livekit_token: livekitToken,\n },\n };\n\n if (this.agentId) {\n payload.agent_id = this.agentId;\n }\n\n if (this.agentImageUrl) {\n payload.agent_image_url = this.agentImageUrl;\n }\n\n if (this.agentPrompt) {\n payload.agent_prompt = this.agentPrompt;\n }\n\n if (this.idleTimeout !== null) {\n payload.idle_timeout = this.idleTimeout;\n }\n\n if (this.extraPayload) {\n Object.assign(payload, this.extraPayload);\n }\n\n const response = await fetch(this.apiUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'X-API-Key': this.apiKey,\n },\n body: JSON.stringify(payload),\n signal: AbortSignal.timeout(this.connOptions.timeoutMs),\n });\n\n if (!response.ok) {\n const text = await response.text();\n throw new APIStatusError({\n message: 'Server returned an error',\n options: { statusCode: response.status, body: { error: text } },\n });\n }\n const data = (await response.json()) as { session_id: string };\n return data.session_id;\n } catch (e) {\n if (e instanceof APIStatusError && !e.retryable) {\n throw e;\n }\n if (e instanceof APIConnectionError) {\n this.#logger.warn({ error: String(e) }, 'failed to call lemonslice api');\n } else {\n this.#logger.error({ error: e }, 'failed to call lemonslice api');\n }\n\n if (i <= this.connOptions.maxRetry - 1) {\n await new Promise((resolve) =>\n setTimeout(resolve, intervalForRetry(this.connOptions, i)),\n );\n }\n }\n }\n\n throw new APIConnectionError({\n message: 'Failed to start LemonSlice Avatar Session after all retries',\n });\n }\n}\n"],"mappings":"AAGA;AAAA,EAEE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,iBAAiB;AAE1B,SAAS,mBAAmB;AAC5B,SAAS,WAAW;AAEpB,MAAM,8BAA8B;AACpC,MAAM,kBAAkB;AACxB,MAAM,cAAc;AACpB,MAAM,wBAAwB;AAC9B,MAAM,oBAAoB;AAKnB,MAAM,4BAA4B,MAAM;AAAA,EAC7C,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AA4FO,MAAM,sBAAsB,MAAM,cAAc;AAAA,EAC7C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAER,UAAU,IAAI;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQd,YAAY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|
|
1
|
+
{"version":3,"sources":["../src/avatar.ts"],"sourcesContent":["// SPDX-FileCopyrightText: 2025 LiveKit, Inc.\n//\n// SPDX-License-Identifier: Apache-2.0\nimport {\n type APIConnectOptions,\n APIConnectionError,\n APIStatusError,\n DEFAULT_API_CONNECT_OPTIONS,\n getJobContext,\n intervalForRetry,\n voice,\n} from '@livekit/agents';\nimport type { Room } from '@livekit/rtc-node';\nimport { TrackKind } from '@livekit/rtc-node';\nimport type { VideoGrant } from 'livekit-server-sdk';\nimport { AccessToken } from 'livekit-server-sdk';\nimport { log } from './log.js';\n\nconst ATTRIBUTE_PUBLISH_ON_BEHALF = 'lk.publish_on_behalf';\nconst DEFAULT_API_URL = 'https://lemonslice.com/api/liveai/sessions';\nconst SAMPLE_RATE = 16000;\nconst AVATAR_AGENT_IDENTITY = 'lemonslice-avatar-agent';\nconst AVATAR_AGENT_NAME = 'lemonslice-avatar-agent';\n\n/**\n * Exception thrown when there are errors with the LemonSlice API.\n */\nexport class LemonSliceException extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'LemonSliceException';\n }\n}\n\n/**\n * Options for configuring an AvatarSession.\n */\nexport interface AvatarSessionOptions {\n /**\n * The ID of the LemonSlice agent to add to the session.\n * Either agentId or agentImageUrl must be provided.\n */\n agentId?: string | null;\n /**\n * The URL of the image to use as the agent's avatar.\n * Either agentId or agentImageUrl must be provided.\n */\n agentImageUrl?: string | null;\n /**\n * A prompt that subtly influences the avatar's movements and expressions.\n */\n agentPrompt?: string | null;\n /**\n * The idle timeout, in seconds. Defaults to 60 seconds.\n */\n idleTimeout?: number | null;\n /**\n * Additional payload fields to merge into the LemonSlice session creation request.\n */\n extraPayload?: Record<string, unknown> | null;\n /**\n * The LemonSlice API URL. Defaults to https://lemonslice.com/api/liveai/sessions\n * or LEMONSLICE_API_URL environment variable.\n */\n apiUrl?: string;\n /**\n * The LemonSlice API key. Can also be set via LEMONSLICE_API_KEY environment variable.\n */\n apiKey?: string;\n /**\n * The identity of the avatar participant in the room. Defaults to 'lemonslice-avatar-agent'.\n */\n avatarParticipantIdentity?: string;\n /**\n * The name of the avatar participant in the room. Defaults to 'lemonslice-avatar-agent'.\n */\n avatarParticipantName?: string;\n /**\n * Connection options for API requests.\n */\n connOptions?: APIConnectOptions;\n}\n\n/**\n * Options for starting an avatar session.\n */\nexport interface StartOptions {\n /**\n * LiveKit server URL. Falls back to LIVEKIT_URL environment variable.\n */\n livekitUrl?: string;\n /**\n * LiveKit API key. Falls back to LIVEKIT_API_KEY environment variable.\n */\n livekitApiKey?: string;\n /**\n * LiveKit API secret. Falls back to LIVEKIT_API_SECRET environment variable.\n */\n livekitApiSecret?: string;\n}\n\n/**\n * A LemonSlice avatar session.\n *\n * This class manages the connection between a LiveKit agent and a LemonSlice avatar,\n * routing agent audio output to the avatar for visual representation.\n *\n * @example\n * ```typescript\n * // Using an agent ID\n * const avatar = new AvatarSession({\n * agentId: 'your-agent-id',\n * apiKey: 'your-lemonslice-api-key',\n * });\n * await avatar.start(agentSession, room);\n *\n * // Using a custom avatar image\n * const avatar = new AvatarSession({\n * agentImageUrl: 'your-image-url',\n * apiKey: 'your-lemonslice-api-key',\n * });\n * await avatar.start(agentSession, room);\n * ```\n */\nexport class AvatarSession extends voice.AvatarSession {\n private agentId: string | null;\n private agentImageUrl: string | null;\n private agentPrompt: string | null;\n private idleTimeout: number | null;\n private extraPayload: Record<string, unknown> | null;\n private apiUrl: string;\n private apiKey: string;\n private avatarParticipantIdentity: string;\n private avatarParticipantName: string;\n private connOptions: APIConnectOptions;\n\n #logger = log();\n\n /**\n * Creates a new AvatarSession.\n *\n * @param options - Configuration options for the avatar session\n * @throws LemonSliceException if invalid agentId or agentImageUrl is provided, or if LemonSlice API key is not set\n */\n constructor(options: AvatarSessionOptions = {}) {\n super();\n this.agentId = options.agentId ?? null;\n this.agentImageUrl = options.agentImageUrl ?? null;\n\n if (!this.agentId && !this.agentImageUrl) {\n throw new LemonSliceException('Missing agentId or agentImageUrl');\n }\n if (this.agentId && this.agentImageUrl) {\n throw new LemonSliceException('Only one of agentId or agentImageUrl can be provided');\n }\n\n this.agentPrompt = options.agentPrompt ?? null;\n this.idleTimeout = options.idleTimeout ?? null;\n this.extraPayload = options.extraPayload ?? null;\n\n this.apiUrl = options.apiUrl || process.env.LEMONSLICE_API_URL || DEFAULT_API_URL;\n this.apiKey = options.apiKey || process.env.LEMONSLICE_API_KEY || '';\n\n if (!this.apiKey) {\n throw new LemonSliceException(\n 'The api_key must be set either by passing apiKey to the client or ' +\n 'by setting the LEMONSLICE_API_KEY environment variable',\n );\n }\n\n this.avatarParticipantIdentity = options.avatarParticipantIdentity || AVATAR_AGENT_IDENTITY;\n this.avatarParticipantName = options.avatarParticipantName || AVATAR_AGENT_NAME;\n this.connOptions = options.connOptions || DEFAULT_API_CONNECT_OPTIONS;\n }\n\n override get avatarIdentity(): string {\n return this.avatarParticipantIdentity;\n }\n\n override get provider(): string {\n return 'lemonslice';\n }\n\n /**\n * Starts the avatar session and connects it to the agent.\n *\n * This method:\n * 1. Creates a LiveKit token for the avatar participant\n * 2. Calls the LemonSlice API to start the avatar session\n * 3. Configures the agent's audio output to stream to the avatar\n *\n * @param agentSession - The agent session to connect to the avatar\n * @param room - The LiveKit room where the avatar will join\n * @param options - Optional LiveKit credentials (falls back to environment variables)\n * @throws LemonSliceException if LiveKit credentials are not available or if the avatar session fails to start\n * @returns The session ID of the LemonSlice session\n */\n async start(\n agentSession: voice.AgentSession,\n room: Room,\n options: StartOptions = {},\n ): Promise<string> {\n await super.start(agentSession, room);\n\n const livekitUrl = options.livekitUrl || process.env.LIVEKIT_URL;\n const livekitApiKey = options.livekitApiKey || process.env.LIVEKIT_API_KEY;\n const livekitApiSecret = options.livekitApiSecret || process.env.LIVEKIT_API_SECRET;\n\n if (!livekitUrl || !livekitApiKey || !livekitApiSecret) {\n throw new LemonSliceException(\n 'livekitUrl, livekitApiKey, and livekitApiSecret must be set ' +\n 'by arguments or environment variables',\n );\n }\n\n let localParticipantIdentity: string;\n try {\n const jobCtx = getJobContext();\n localParticipantIdentity = jobCtx.agent?.identity || '';\n if (!localParticipantIdentity && room.localParticipant) {\n localParticipantIdentity = room.localParticipant.identity;\n }\n } catch {\n if (!room.isConnected || !room.localParticipant) {\n throw new LemonSliceException('failed to get local participant identity');\n }\n localParticipantIdentity = room.localParticipant.identity;\n }\n\n if (!localParticipantIdentity) {\n throw new LemonSliceException('failed to get local participant identity');\n }\n\n const at = new AccessToken(livekitApiKey, livekitApiSecret, {\n identity: this.avatarIdentity,\n name: this.avatarParticipantName,\n });\n at.kind = 'agent';\n\n at.addGrant({\n roomJoin: true,\n room: room.name,\n } as VideoGrant);\n\n // allow the avatar agent to publish audio and video on behalf of your local agent\n at.attributes = {\n [ATTRIBUTE_PUBLISH_ON_BEHALF]: localParticipantIdentity,\n };\n\n const livekitToken = await at.toJwt();\n\n this.#logger.debug('starting avatar session');\n const sessionId = await this.startAgent(livekitUrl, livekitToken);\n\n agentSession.output.audio = new voice.DataStreamAudioOutput({\n room,\n destinationIdentity: this.avatarIdentity,\n sampleRate: SAMPLE_RATE,\n waitRemoteTrack: TrackKind.KIND_VIDEO,\n waitPlaybackStart: true,\n });\n\n return sessionId;\n }\n\n private async startAgent(livekitUrl: string, livekitToken: string): Promise<string> {\n for (let i = 0; i <= this.connOptions.maxRetry; i++) {\n try {\n const payload: Record<string, any> = {\n transport_type: 'livekit',\n properties: {\n livekit_url: livekitUrl,\n livekit_token: livekitToken,\n },\n };\n\n if (this.agentId) {\n payload.agent_id = this.agentId;\n }\n\n if (this.agentImageUrl) {\n payload.agent_image_url = this.agentImageUrl;\n }\n\n if (this.agentPrompt) {\n payload.agent_prompt = this.agentPrompt;\n }\n\n if (this.idleTimeout !== null) {\n payload.idle_timeout = this.idleTimeout;\n }\n\n if (this.extraPayload) {\n Object.assign(payload, this.extraPayload);\n }\n\n const response = await fetch(this.apiUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'X-API-Key': this.apiKey,\n },\n body: JSON.stringify(payload),\n signal: AbortSignal.timeout(this.connOptions.timeoutMs),\n });\n\n if (!response.ok) {\n const text = await response.text();\n throw new APIStatusError({\n message: 'Server returned an error',\n options: { statusCode: response.status, body: { error: text } },\n });\n }\n const data = (await response.json()) as { session_id: string };\n return data.session_id;\n } catch (e) {\n if (e instanceof APIStatusError && !e.retryable) {\n throw e;\n }\n if (e instanceof APIConnectionError) {\n this.#logger.warn({ error: String(e) }, 'failed to call lemonslice api');\n } else {\n this.#logger.error({ error: e }, 'failed to call lemonslice api');\n }\n\n if (i <= this.connOptions.maxRetry - 1) {\n await new Promise((resolve) =>\n setTimeout(resolve, intervalForRetry(this.connOptions, i)),\n );\n }\n }\n }\n\n throw new APIConnectionError({\n message: 'Failed to start LemonSlice Avatar Session after all retries',\n });\n }\n}\n"],"mappings":"AAGA;AAAA,EAEE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,iBAAiB;AAE1B,SAAS,mBAAmB;AAC5B,SAAS,WAAW;AAEpB,MAAM,8BAA8B;AACpC,MAAM,kBAAkB;AACxB,MAAM,cAAc;AACpB,MAAM,wBAAwB;AAC9B,MAAM,oBAAoB;AAKnB,MAAM,4BAA4B,MAAM;AAAA,EAC7C,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AA4FO,MAAM,sBAAsB,MAAM,cAAc;AAAA,EAC7C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAER,UAAU,IAAI;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQd,YAAY,UAAgC,CAAC,GAAG;AAC9C,UAAM;AACN,SAAK,UAAU,QAAQ,WAAW;AAClC,SAAK,gBAAgB,QAAQ,iBAAiB;AAE9C,QAAI,CAAC,KAAK,WAAW,CAAC,KAA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ANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@livekit/agents-plugin-lemonslice",
|
|
3
|
-
"version": "1.4.
|
|
3
|
+
"version": "1.4.4",
|
|
4
4
|
"description": "LemonSlice avatar plugin for LiveKit Node Agents",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"require": "dist/index.cjs",
|
|
@@ -30,14 +30,14 @@
|
|
|
30
30
|
"pino": "^8.19.0",
|
|
31
31
|
"tsup": "^8.3.5",
|
|
32
32
|
"typescript": "^5.0.0",
|
|
33
|
-
"@livekit/agents": "1.4.
|
|
33
|
+
"@livekit/agents": "1.4.4"
|
|
34
34
|
},
|
|
35
35
|
"dependencies": {
|
|
36
36
|
"livekit-server-sdk": "^2.13.3"
|
|
37
37
|
},
|
|
38
38
|
"peerDependencies": {
|
|
39
39
|
"@livekit/rtc-node": "^0.13.27",
|
|
40
|
-
"@livekit/agents": "1.4.
|
|
40
|
+
"@livekit/agents": "1.4.4"
|
|
41
41
|
},
|
|
42
42
|
"scripts": {
|
|
43
43
|
"build": "tsup --onSuccess \"pnpm build:types\"",
|
package/src/avatar.ts
CHANGED
|
@@ -173,6 +173,14 @@ export class AvatarSession extends voice.AvatarSession {
|
|
|
173
173
|
this.connOptions = options.connOptions || DEFAULT_API_CONNECT_OPTIONS;
|
|
174
174
|
}
|
|
175
175
|
|
|
176
|
+
override get avatarIdentity(): string {
|
|
177
|
+
return this.avatarParticipantIdentity;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
override get provider(): string {
|
|
181
|
+
return 'lemonslice';
|
|
182
|
+
}
|
|
183
|
+
|
|
176
184
|
/**
|
|
177
185
|
* Starts the avatar session and connects it to the agent.
|
|
178
186
|
*
|
|
@@ -224,7 +232,7 @@ export class AvatarSession extends voice.AvatarSession {
|
|
|
224
232
|
}
|
|
225
233
|
|
|
226
234
|
const at = new AccessToken(livekitApiKey, livekitApiSecret, {
|
|
227
|
-
identity: this.
|
|
235
|
+
identity: this.avatarIdentity,
|
|
228
236
|
name: this.avatarParticipantName,
|
|
229
237
|
});
|
|
230
238
|
at.kind = 'agent';
|
|
@@ -246,7 +254,7 @@ export class AvatarSession extends voice.AvatarSession {
|
|
|
246
254
|
|
|
247
255
|
agentSession.output.audio = new voice.DataStreamAudioOutput({
|
|
248
256
|
room,
|
|
249
|
-
destinationIdentity: this.
|
|
257
|
+
destinationIdentity: this.avatarIdentity,
|
|
250
258
|
sampleRate: SAMPLE_RATE,
|
|
251
259
|
waitRemoteTrack: TrackKind.KIND_VIDEO,
|
|
252
260
|
waitPlaybackStart: true,
|