Skip to content

Commit abfee43

Browse files
committed
feat: generate session title in parallel
1 parent 3808c73 commit abfee43

File tree

1 file changed

+21
-12
lines changed

1 file changed

+21
-12
lines changed

packages/agent-api/src/functions/chats-post.ts

Lines changed: 21 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,23 @@ export async function postChats(request: HttpRequest, context: InvocationContext
142142
},
143143
);
144144

145+
// Create a short title for this chat session
146+
const generateSessionTitle = async () => {
147+
const { title } = await chatHistory.getContext();
148+
if (!title) {
149+
const response = await model.invoke([
150+
['system', titleSystemPrompt],
151+
['human', question],
152+
]);
153+
context.log(`Title for session: ${response.text}`);
154+
chatHistory.setContext({ title: response.text });
155+
}
156+
}
157+
158+
// We don't await this yet, to allow parallel execution.
159+
// We'll await it later, after the response is fully sent.
160+
const sessionTitlePromise = generateSessionTitle();
161+
145162
// Update chat history when the response is complete
146163
const onResponseComplete = async (content: string) => {
147164
try {
@@ -152,25 +169,17 @@ export async function postChats(request: HttpRequest, context: InvocationContext
152169
new AIMessage(content),
153170
]);
154171
context.log('Chat history updated successfully');
172+
173+
// Ensure the session title has finished generating
174+
await sessionTitlePromise;
155175
}
156176
} catch (error) {
157-
context.error('Error updating chat history:', error);
177+
context.error('Error after response completion:', error);
158178
}
159179
}
160180

161181
const jsonStream = Readable.from(createJsonStream(responseStream, sessionId, onResponseComplete));
162182

163-
// Create a short title for this chat session
164-
const { title } = await chatHistory.getContext();
165-
if (!title) {
166-
const response = await model.invoke([
167-
['system', titleSystemPrompt],
168-
['human', question],
169-
]);
170-
context.log(`Title for session: ${response.text}`);
171-
chatHistory.setContext({ title: response.text });
172-
}
173-
174183
return {
175184
headers: {
176185
'Content-Type': 'application/x-ndjson',

0 commit comments

Comments
 (0)