Skip to content

Commit 546551a

Browse files
committed
refactor: simplify api responses
1 parent 353565c commit 546551a

File tree

4 files changed

+54
-64
lines changed

4 files changed

+54
-64
lines changed

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

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ import process from 'node:process';
22
import { HttpRequest, HttpResponseInit, InvocationContext, app } from '@azure/functions';
33
import { AzureCosmsosDBNoSQLChatMessageHistory } from '@langchain/azure-cosmosdb';
44
import 'dotenv/config';
5-
import { badRequest, ok, notFound } from '../http-response.js';
65
import { getCredentials, getUserId } from '../auth.js';
76

87
async function deleteChats(request: HttpRequest, context: InvocationContext): Promise<HttpResponseInit> {
@@ -11,11 +10,21 @@ async function deleteChats(request: HttpRequest, context: InvocationContext): Pr
1110
const userId = getUserId(request);
1211

1312
if (!userId) {
14-
return badRequest('Invalid or missing userId in the request');
13+
return {
14+
status: 400,
15+
jsonBody: {
16+
error: 'Invalid or missing userId in the request',
17+
},
18+
}
1519
}
1620

1721
if (!sessionId) {
18-
return badRequest('Invalid or missing sessionId in the request');
22+
return {
23+
status: 400,
24+
jsonBody: {
25+
error: 'Invalid or missing sessionId in the request',
26+
},
27+
}
1928
}
2029

2130
try {
@@ -42,12 +51,17 @@ async function deleteChats(request: HttpRequest, context: InvocationContext): Pr
4251
});
4352

4453
await chatHistory.clear();
45-
return ok();
54+
return { status: 204 };
4655
} catch (_error: unknown) {
4756
const error = _error as Error;
4857
context.error(`Error when processing chats-delete request: ${error.message}`);
4958

50-
return notFound('Session not found');
59+
return {
60+
status: 404,
61+
jsonBody: {
62+
error: 'Session not found',
63+
},
64+
}
5165
}
5266
}
5367

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

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ import process from 'node:process';
22
import { HttpRequest, HttpResponseInit, InvocationContext, app } from '@azure/functions';
33
import { AzureCosmsosDBNoSQLChatMessageHistory } from '@langchain/azure-cosmosdb';
44
import 'dotenv/config';
5-
import { badRequest, ok, notFound } from '../http-response.js';
65
import { getCredentials, getUserId } from '../auth.js';
76

87
async function getChats(request: HttpRequest, context: InvocationContext): Promise<HttpResponseInit> {
@@ -11,7 +10,12 @@ async function getChats(request: HttpRequest, context: InvocationContext): Promi
1110
const userId = getUserId(request);
1211

1312
if (!userId) {
14-
return badRequest('Invalid or missing userId in the request');
13+
return {
14+
status: 400,
15+
jsonBody: {
16+
error: 'Invalid or missing userId in the request',
17+
},
18+
}
1519
}
1620

1721
try {
@@ -43,20 +47,25 @@ async function getChats(request: HttpRequest, context: InvocationContext): Promi
4347
role: message.getType() === 'human' ? 'user' : 'assistant',
4448
content: message.content,
4549
}));
46-
return ok(chatMessages);
50+
return { jsonBody: chatMessages }
4751
}
4852

4953
const sessions = await chatHistory.getAllSessions();
5054
const chatSessions = sessions.map((session) => ({
5155
id: session.id,
5256
title: session.context?.title,
5357
}));
54-
return ok(chatSessions);
58+
return { jsonBody: chatSessions };
5559
} catch (_error: unknown) {
5660
const error = _error as Error;
5761
context.error(`Error when processing chats-get request: ${error.message}`);
5862

59-
return notFound('Session not found');
63+
return {
64+
status: 404,
65+
jsonBody: {
66+
error: 'Session not found',
67+
},
68+
}
6069
}
6170
}
6271

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

Lines changed: 21 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -12,15 +12,14 @@ import { loadMcpTools } from '@langchain/mcp-adapters';
1212
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
1313
import { v4 as uuidv4 } from 'uuid';
1414
import 'dotenv/config';
15-
import { badRequest, data, serviceUnavailable } from '../http-response.js';
1615
import { getAzureOpenAiTokenProvider, getCredentials, getUserId } from '../auth.js';
1716
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
1817
import { ChainValues } from '@langchain/core/utils/types.js';
1918

2019
const agentSystemPrompt = `
2120
# Role
2221
You an expert assistant that helps users with managing burger orders. Use the provided tools to get the information you need and perform actions on behalf of the user.
23-
Only anwser to requests that are related to burger orders and the menu. If the user asks for something else, politely inform them that you can only assist with burger orders.
22+
Only answer to requests that are related to burger orders and the menu. If the user asks for something else, politely inform them that you can only assist with burger orders.
2423
2524
# Task
2625
1. Help the user with their request, ask any clarifying questions if needed.
@@ -51,7 +50,12 @@ export async function postChats(request: HttpRequest, context: InvocationContext
5150
const userId = getUserId(request, requestBody);
5251

5352
if (!messages || messages.length === 0 || !messages.at(-1)?.content) {
54-
return badRequest('Invalid or missing messages in the request body');
53+
return {
54+
status: 400,
55+
jsonBody: {
56+
error: 'Invalid or missing messages in the request body',
57+
},
58+
}
5559
}
5660

5761
let model: BaseChatModel;
@@ -140,7 +144,7 @@ export async function postChats(request: HttpRequest, context: InvocationContext
140144
historyMessagesKey: 'chat_history',
141145
getMessageHistory: async () => chatHistory,
142146
});
143-
// Retriever to search for the documents in the database
147+
// Add question and start the agent
144148
const question = messages.at(-1)!.content;
145149
const responseStream = await agentChainWithHistory.stream({ userId, question }, { configurable: { sessionId } });
146150
const jsonStream = Readable.from(createJsonStream(responseStream, sessionId));
@@ -158,15 +162,23 @@ export async function postChats(request: HttpRequest, context: InvocationContext
158162
chatHistory.setContext({ title: response.content });
159163
}
160164

161-
return data(jsonStream, {
162-
'Content-Type': 'application/x-ndjson',
163-
'Transfer-Encoding': 'chunked',
164-
});
165+
return {
166+
headers: {
167+
'Content-Type': 'application/x-ndjson',
168+
'Transfer-Encoding': 'chunked',
169+
},
170+
body: jsonStream,
171+
}
165172
} catch (_error: unknown) {
166173
const error = _error as Error;
167174
context.error(`Error when processing chat-post request: ${error.message}`);
168175

169-
return serviceUnavailable('Service temporarily unavailable. Please try again later.');
176+
return {
177+
status: 500,
178+
jsonBody: {
179+
error: 'Internal server error while processing the request',
180+
},
181+
}
170182
}
171183
}
172184

packages/agent-api/src/http-response.ts

Lines changed: 0 additions & 45 deletions
This file was deleted.

0 commit comments

Comments
 (0)