Thanks for your messages here! Along similar lines as my query to dkupeli above:
Do you mind sharing how exactly you’re keeping track of the session’s pending responses (along with their statuses)?
I would imagine it probably involves keeping track of responses created on the client-side and then updating the status when a change is detected in events received from the server, but I’m not sure. Is that it or is there more to it? I’m especially unclear how to keep track of ‘pending’ responses
.
Really appreciate your help!
You’re spot one! It’s basically keeping track of all the conversation items and storing the status. If a response is done, you can update it from in_progress to done. We use LiveKit agents, which abstracts this for you. You do need some custom code here and there.
I’ve implemented this react hook that solves the problem for me. Instead of ever sending a response.create event, I just call enqueueResponseCreate which avoids to send multiple response.create after tool calls or item.create events.
You should also clear the queue like this for incoming ws events:
case "response.done":
// Clear the active response and process any queued events.
onResponseDone(sendEvent);
this is the code for the hook (but it can be any function that holds some queue value in memory thought the program).
import { useCallback, useRef } from "react";
import {
RealTimeClientEvents,
WebSocketOutEventType,
} from "../../types/events.types";
// This hook is used to queue up response create events to prevent spamming the server.
// Without this, the server would receive a response create event for every message sent by the user and eventually get an error.
export const useResponseCreateQueue = () => {
const activeResponseRef = useRef<boolean>(false);
const queuedResponseRef = useRef<boolean>(false);
const lastResponseCreateTimeRef = useRef<number>(0);
const minInterval = 200;
const enqueueResponseCreate = useCallback(
(sendEvent: (event: RealTimeClientEvents) => void) => {
const now = Date.now();
const timeSinceLast = now - lastResponseCreateTimeRef.current;
if (timeSinceLast < minInterval) {
setTimeout(enqueueResponseCreate, minInterval - timeSinceLast);
return;
}
if (!activeResponseRef.current) {
activeResponseRef.current = true;
lastResponseCreateTimeRef.current = Date.now();
sendEvent({
type: "response.create",
});
} else {
queuedResponseRef.current = true;
}
},
[]
);
const onResponseDone = useCallback(
(sendEvent: (event: RealTimeClientEvents) => void) => {
activeResponseRef.current = false;
// If there was a queued call, fire it now.
if (queuedResponseRef.current) {
queuedResponseRef.current = false;
enqueueResponseCreate(sendEvent);
}
},
[enqueueResponseCreate]
);
return { enqueueResponseCreate, onResponseDone };
};