-
Notifications
You must be signed in to change notification settings - Fork 195
preemptive generation feature #783
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -43,6 +43,7 @@ import { type AgentSession, type TurnDetectionMode } from './agent_session.js'; | |
| import { | ||
| AudioRecognition, | ||
| type EndOfTurnInfo, | ||
| type PreemptiveGenerationInfo, | ||
| type RecognitionHooks, | ||
| type _TurnDetector, | ||
| } from './audio_recognition.js'; | ||
|
|
@@ -71,6 +72,15 @@ import { SpeechHandle } from './speech_handle.js'; | |
| // equivalent to Python's contextvars | ||
| const speechHandleStorage = new AsyncLocalStorage<SpeechHandle>(); | ||
|
|
||
| interface PreemptiveGeneration { | ||
| speechHandle: SpeechHandle; | ||
| info: PreemptiveGenerationInfo; | ||
| chatCtx: ChatContext; | ||
| tools: ToolContext; | ||
| toolChoice: ToolChoice | null; | ||
| createdAt: number; | ||
| } | ||
|
|
||
| export class AgentActivity implements RecognitionHooks { | ||
| private static readonly REPLY_TASK_CANCEL_TIMEOUT = 5000; | ||
| private started = false; | ||
|
|
@@ -87,6 +97,7 @@ export class AgentActivity implements RecognitionHooks { | |
| private audioStream = new DeferredReadableStream<AudioFrame>(); | ||
| // default to null as None, which maps to the default provider tool choice value | ||
| private toolChoice: ToolChoice | null = null; | ||
| private preemptiveGeneration?: PreemptiveGeneration; | ||
|
|
||
| agent: Agent; | ||
| agentSession: AgentSession; | ||
|
|
@@ -664,6 +675,64 @@ export class AgentActivity implements RecognitionHooks { | |
| ); | ||
| } | ||
|
|
||
| onPreemptiveGeneration(info: PreemptiveGenerationInfo): void { | ||
| if (!this.agentSession.options.preemptiveGeneration) { | ||
| return; | ||
| } | ||
|
|
||
| if (this.draining) { | ||
| this.logger.debug('skipping preemptive generation, agent is draining'); | ||
| return; | ||
| } | ||
|
|
||
| if (this._currentSpeech && !this._currentSpeech.interrupted) { | ||
| this.logger.debug('skipping preemptive generation, current speech is not interrupted'); | ||
| return; | ||
| } | ||
|
|
||
| if (!(this.llm instanceof LLM)) { | ||
| this.logger.debug('skipping preemptive generation, LLM is not a standard LLM instance'); | ||
| return; | ||
| } | ||
|
|
||
| // Cancel any existing preemptive generation | ||
| this.cancelPreemptiveGeneration(); | ||
|
|
||
| const chatCtx = this.agent.chatCtx.copy(); | ||
| const userMessage = ChatMessage.create({ | ||
| role: 'user', | ||
| content: info.newTranscript, | ||
| }); | ||
|
|
||
| this.logger.info( | ||
| { transcript: info.newTranscript, confidence: info.transcriptConfidence }, | ||
| 'starting preemptive generation', | ||
| ); | ||
|
|
||
| const speechHandle = this.generateReply({ | ||
| userMessage, | ||
| chatCtx, | ||
| scheduleSpeech: false, // Don't schedule yet! | ||
| }); | ||
|
|
||
| this.preemptiveGeneration = { | ||
| speechHandle, | ||
| info, | ||
| chatCtx, | ||
| tools: this.agent.toolCtx, | ||
| toolChoice: this.toolChoice, | ||
| createdAt: Date.now(), | ||
| }; | ||
| } | ||
|
|
||
| private cancelPreemptiveGeneration(): void { | ||
| if (this.preemptiveGeneration) { | ||
| this.logger.debug('cancelling existing preemptive generation'); | ||
| this.preemptiveGeneration.speechHandle._cancel(); | ||
| this.preemptiveGeneration = undefined; | ||
| } | ||
| } | ||
|
|
||
| private createSpeechTask(options: { | ||
| task: Task<void>; | ||
| ownedSpeechHandle?: SpeechHandle; | ||
|
|
@@ -775,13 +844,15 @@ export class AgentActivity implements RecognitionHooks { | |
| instructions?: string; | ||
| toolChoice?: ToolChoice | null; | ||
| allowInterruptions?: boolean; | ||
| scheduleSpeech?: boolean; | ||
| }): SpeechHandle { | ||
| const { | ||
| userMessage, | ||
| chatCtx, | ||
| instructions: defaultInstructions, | ||
| toolChoice: defaultToolChoice, | ||
| allowInterruptions: defaultAllowInterruptions, | ||
| scheduleSpeech = true, | ||
| } = options; | ||
|
|
||
| let instructions = defaultInstructions; | ||
|
|
@@ -871,7 +942,9 @@ export class AgentActivity implements RecognitionHooks { | |
| task.finally(() => this.onPipelineReplyDone()); | ||
| } | ||
|
|
||
| this.scheduleSpeech(handle, SpeechHandle.SPEECH_PRIORITY_NORMAL); | ||
| if (scheduleSpeech) { | ||
| this.scheduleSpeech(handle, SpeechHandle.SPEECH_PRIORITY_NORMAL); | ||
| } | ||
| return handle; | ||
| } | ||
|
|
||
|
|
@@ -977,6 +1050,70 @@ export class AgentActivity implements RecognitionHooks { | |
| return; | ||
| } | ||
|
|
||
| // Check if we can use preemptive generation | ||
| const preemptive = this.preemptiveGeneration; | ||
| if (preemptive) { | ||
| // Add the user message to the chat context for comparison | ||
| const validationChatCtx = this.agent.chatCtx.copy(); | ||
| if (userMessage) { | ||
| validationChatCtx.insert(userMessage); | ||
| } | ||
|
|
||
| // Validate: transcript matches, context equivalent, tools unchanged, toolChoice unchanged | ||
| const transcriptMatches = preemptive.info.newTranscript === info.newTranscript; | ||
| const contextEquivalent = preemptive.chatCtx.isEquivalent(validationChatCtx); | ||
| const toolsUnchanged = preemptive.tools === this.agent.toolCtx; | ||
| const toolChoiceUnchanged = preemptive.toolChoice === this.toolChoice; | ||
|
|
||
| if (transcriptMatches && contextEquivalent && toolsUnchanged && toolChoiceUnchanged) { | ||
| // Use preemptive generation! | ||
| const speechHandle = preemptive.speechHandle; | ||
| this.preemptiveGeneration = undefined; | ||
|
|
||
| const leadTime = Date.now() - preemptive.createdAt; | ||
| this.logger.info( | ||
| { | ||
| transcript: info.newTranscript, | ||
| leadTimeMs: leadTime, | ||
| confidence: preemptive.info.transcriptConfidence, | ||
| }, | ||
| 'using preemptive generation', | ||
| ); | ||
|
|
||
| // Schedule the preemptive speech | ||
| this.scheduleSpeech(speechHandle, SpeechHandle.SPEECH_PRIORITY_NORMAL); | ||
|
|
||
| // Emit metrics | ||
| const eouMetrics: EOUMetrics = { | ||
|
Comment on lines
+1054
to
+1087
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Can we make sure we have the parity implementation as in python agent framework? https://github.com/livekit/agents/blob/a9bc03562f498f3666978ad008fc93b2cbbd22a9/livekit-agents/livekit/agents/voice/agent_activity.py#L1384-L1420 |
||
| type: 'eou_metrics', | ||
| timestamp: Date.now(), | ||
| endOfUtteranceDelayMs: info.endOfUtteranceDelay, | ||
| transcriptionDelayMs: info.transcriptionDelay, | ||
| onUserTurnCompletedDelayMs: callbackDuration, | ||
| speechId: speechHandle.id, | ||
| }; | ||
|
|
||
| this.agentSession.emit( | ||
| AgentSessionEventTypes.MetricsCollected, | ||
| createMetricsCollectedEvent({ metrics: eouMetrics }), | ||
| ); | ||
|
|
||
| return; | ||
| } else { | ||
| // Context changed, discard and regenerate | ||
| this.logger.warn( | ||
| { | ||
| transcriptMatches, | ||
| contextEquivalent, | ||
| toolsUnchanged, | ||
| toolChoiceUnchanged, | ||
| }, | ||
| 'preemptive generation invalidated, regenerating', | ||
| ); | ||
| this.cancelPreemptiveGeneration(); | ||
| } | ||
| } | ||
|
|
||
| // Ensure the new message is passed to generateReply | ||
| // This preserves the original message id, making it easier for users to track responses | ||
| const speechHandle = this.generateReply({ userMessage, chatCtx }); | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is nice, can you also add a unittest for this function? Inside
chat_context.test.ts?