/
chat-simple-api.ts
63 lines (54 loc) 路 2.02 KB
/
chat-simple-api.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import { userHashedId } from "@/features/auth/helpers";
import { CosmosDBChatMessageHistory } from "@/features/langchain/memory/cosmosdb/cosmosdb";
import { AI_NAME } from "@/features/theme/customise";
import { LangChainStream, StreamingTextResponse } from "ai";
import { ConversationChain } from "langchain/chains";
import { ChatOpenAI } from "langchain/chat_models/openai";
import { BufferWindowMemory } from "langchain/memory";
import {
ChatPromptTemplate,
HumanMessagePromptTemplate,
MessagesPlaceholder,
SystemMessagePromptTemplate,
} from "langchain/prompts";
import { initAndGuardChatSession } from "../chat-services/chat-thread-service";
import { PromptGPTProps } from "../chat-services/models";
import { transformConversationStyleToTemperature } from "../chat-services/utils";
export const ChatSimple = async (props: PromptGPTProps) => {
const { lastHumanMessage, id, chatThread } = await initAndGuardChatSession(
props
);
const { stream, handlers } = LangChainStream();
const userId = await userHashedId();
const chat = new ChatOpenAI({
temperature: transformConversationStyleToTemperature(
chatThread.conversationStyle
),
streaming: true,
});
const memory = new BufferWindowMemory({
k: 100,
returnMessages: true,
memoryKey: "history",
chatHistory: new CosmosDBChatMessageHistory({
sessionId: id,
userId: userId,
}),
});
const chatPrompt = ChatPromptTemplate.fromPromptMessages([
SystemMessagePromptTemplate.fromTemplate(
`-You are ${AI_NAME} who is a helpful AI Assistant.
- You will provide clear and concise queries, and you will respond with polite and professional answers.
- You will answer questions truthfully and accurately.`
),
new MessagesPlaceholder("history"),
HumanMessagePromptTemplate.fromTemplate("{input}"),
]);
const chain = new ConversationChain({
llm: chat,
memory,
prompt: chatPrompt,
});
chain.call({ input: lastHumanMessage.content }, [handlers]);
return new StreamingTextResponse(stream);
};