2023-07-27 23:22:07 +08:00
|
|
|
|
from fastapi import Body
|
2023-12-13 16:08:58 +08:00
|
|
|
|
from sse_starlette.sse import EventSourceResponse
|
2023-11-22 18:38:26 +08:00
|
|
|
|
from configs import LLM_MODELS, TEMPERATURE
|
2023-09-17 16:19:50 +08:00
|
|
|
|
from server.utils import wrap_done, get_ChatOpenAI
|
2023-09-27 21:53:47 +08:00
|
|
|
|
from langchain.chains import LLMChain
|
2023-07-27 23:22:07 +08:00
|
|
|
|
from langchain.callbacks import AsyncIteratorCallbackHandler
|
|
|
|
|
|
from typing import AsyncIterable
|
|
|
|
|
|
import asyncio
|
2023-11-03 11:31:45 +08:00
|
|
|
|
import json
|
2023-08-08 23:54:51 +08:00
|
|
|
|
from langchain.prompts.chat import ChatPromptTemplate
|
2023-11-22 18:38:26 +08:00
|
|
|
|
from typing import List, Optional, Union
|
2023-08-08 23:54:51 +08:00
|
|
|
|
from server.chat.utils import History
|
2023-11-22 18:38:26 +08:00
|
|
|
|
from langchain.prompts import PromptTemplate
|
2023-09-17 13:27:11 +08:00
|
|
|
|
from server.utils import get_prompt_template
|
2023-11-22 18:38:26 +08:00
|
|
|
|
from server.memory.conversation_db_buffer_memory import ConversationBufferDBMemory
|
|
|
|
|
|
from server.db.repository import add_message_to_db
|
|
|
|
|
|
from server.callback_handler.conversation_callback_handler import ConversationCallbackHandler
|
2023-07-27 23:22:07 +08:00
|
|
|
|
|
|
|
|
|
|
|
2023-09-08 12:25:02 +08:00
|
|
|
|
async def chat(query: str = Body(..., description="用户输入", examples=["恼羞成怒"]),
|
2023-11-25 13:51:07 +08:00
|
|
|
|
conversation_id: str = Body("", description="对话框ID"),
|
2023-12-01 11:35:43 +08:00
|
|
|
|
history_len: int = Body(-1, description="从数据库中取历史消息的数量"),
|
2023-11-22 18:38:26 +08:00
|
|
|
|
history: Union[int, List[History]] = Body([],
|
|
|
|
|
|
description="历史对话,设为一个整数可以从数据库中读取历史消息",
|
|
|
|
|
|
examples=[[
|
|
|
|
|
|
{"role": "user",
|
|
|
|
|
|
"content": "我们来玩成语接龙,我先来,生龙活虎"},
|
|
|
|
|
|
{"role": "assistant", "content": "虎头虎脑"}]]
|
|
|
|
|
|
),
|
2023-11-03 11:31:45 +08:00
|
|
|
|
stream: bool = Body(False, description="流式输出"),
|
2023-11-09 22:15:52 +08:00
|
|
|
|
model_name: str = Body(LLM_MODELS[0], description="LLM 模型名称。"),
|
2023-11-03 11:31:45 +08:00
|
|
|
|
temperature: float = Body(TEMPERATURE, description="LLM 采样温度", ge=0.0, le=1.0),
|
|
|
|
|
|
max_tokens: Optional[int] = Body(None, description="限制LLM生成Token数量,默认None代表模型最大值"),
|
|
|
|
|
|
# top_p: float = Body(TOP_P, description="LLM 核采样。勿与temperature同时设置", gt=0.0, lt=1.0),
|
|
|
|
|
|
prompt_name: str = Body("default", description="使用的prompt模板名称(在configs/prompt_config.py中配置)"),
|
|
|
|
|
|
):
|
2023-11-22 18:38:26 +08:00
|
|
|
|
async def chat_iterator() -> AsyncIterable[str]:
|
2023-11-28 21:00:00 +08:00
|
|
|
|
nonlocal history, max_tokens
|
2023-07-27 23:22:07 +08:00
|
|
|
|
callback = AsyncIteratorCallbackHandler()
|
2023-11-22 18:38:26 +08:00
|
|
|
|
callbacks = [callback]
|
|
|
|
|
|
memory = None
|
|
|
|
|
|
|
2023-12-02 19:22:44 +08:00
|
|
|
|
# 负责保存llm response到message db
|
|
|
|
|
|
message_id = add_message_to_db(chat_type="llm_chat", query=query, conversation_id=conversation_id)
|
|
|
|
|
|
conversation_callback = ConversationCallbackHandler(conversation_id=conversation_id, message_id=message_id,
|
|
|
|
|
|
chat_type="llm_chat",
|
|
|
|
|
|
query=query)
|
|
|
|
|
|
callbacks.append(conversation_callback)
|
2023-12-01 11:35:43 +08:00
|
|
|
|
|
2023-11-26 16:47:58 +08:00
|
|
|
|
if isinstance(max_tokens, int) and max_tokens <= 0:
|
|
|
|
|
|
max_tokens = None
|
2023-11-22 18:38:26 +08:00
|
|
|
|
|
2023-09-15 17:52:22 +08:00
|
|
|
|
model = get_ChatOpenAI(
|
2023-09-01 23:58:09 +08:00
|
|
|
|
model_name=model_name,
|
2023-09-13 10:00:54 +08:00
|
|
|
|
temperature=temperature,
|
2023-10-12 16:18:56 +08:00
|
|
|
|
max_tokens=max_tokens,
|
2023-11-22 18:38:26 +08:00
|
|
|
|
callbacks=callbacks,
|
2023-07-27 23:22:07 +08:00
|
|
|
|
)
|
2023-09-17 13:27:11 +08:00
|
|
|
|
|
2023-12-01 11:35:43 +08:00
|
|
|
|
if history: # 优先使用前端传入的历史消息
|
2023-11-22 18:38:26 +08:00
|
|
|
|
history = [History.from_data(h) for h in history]
|
|
|
|
|
|
prompt_template = get_prompt_template("llm_chat", prompt_name)
|
|
|
|
|
|
input_msg = History(role="user", content=prompt_template).to_msg_template(False)
|
|
|
|
|
|
chat_prompt = ChatPromptTemplate.from_messages(
|
|
|
|
|
|
[i.to_msg_template() for i in history] + [input_msg])
|
2023-12-01 11:35:43 +08:00
|
|
|
|
elif conversation_id and history_len > 0: # 前端要求从数据库取历史消息
|
2023-11-22 18:38:26 +08:00
|
|
|
|
# 使用memory 时必须 prompt 必须含有memory.memory_key 对应的变量
|
|
|
|
|
|
prompt = get_prompt_template("llm_chat", "with_history")
|
|
|
|
|
|
chat_prompt = PromptTemplate.from_template(prompt)
|
|
|
|
|
|
# 根据conversation_id 获取message 列表进而拼凑 memory
|
2023-12-01 11:35:43 +08:00
|
|
|
|
memory = ConversationBufferDBMemory(conversation_id=conversation_id,
|
|
|
|
|
|
llm=model,
|
|
|
|
|
|
message_limit=history_len)
|
|
|
|
|
|
else:
|
|
|
|
|
|
prompt_template = get_prompt_template("llm_chat", prompt_name)
|
|
|
|
|
|
input_msg = History(role="user", content=prompt_template).to_msg_template(False)
|
|
|
|
|
|
chat_prompt = ChatPromptTemplate.from_messages([input_msg])
|
2023-11-22 18:38:26 +08:00
|
|
|
|
|
|
|
|
|
|
chain = LLMChain(prompt=chat_prompt, llm=model, memory=memory)
|
2023-07-27 23:22:07 +08:00
|
|
|
|
|
|
|
|
|
|
# Begin a task that runs in the background.
|
|
|
|
|
|
task = asyncio.create_task(wrap_done(
|
2023-08-08 23:54:51 +08:00
|
|
|
|
chain.acall({"input": query}),
|
2023-07-27 23:22:07 +08:00
|
|
|
|
callback.done),
|
|
|
|
|
|
)
|
|
|
|
|
|
|
2023-08-14 10:35:47 +08:00
|
|
|
|
if stream:
|
|
|
|
|
|
async for token in callback.aiter():
|
|
|
|
|
|
# Use server-sent-events to stream the response
|
2023-11-03 11:31:45 +08:00
|
|
|
|
yield json.dumps(
|
2023-11-22 18:38:26 +08:00
|
|
|
|
{"text": token, "message_id": message_id},
|
2023-11-03 11:31:45 +08:00
|
|
|
|
ensure_ascii=False)
|
2023-08-14 10:35:47 +08:00
|
|
|
|
else:
|
2023-11-22 18:38:26 +08:00
|
|
|
|
answer = ""
|
2023-08-14 10:35:47 +08:00
|
|
|
|
async for token in callback.aiter():
|
|
|
|
|
|
answer += token
|
2023-11-03 11:31:45 +08:00
|
|
|
|
yield json.dumps(
|
2023-11-22 18:38:26 +08:00
|
|
|
|
{"text": answer, "message_id": message_id},
|
2023-11-03 11:31:45 +08:00
|
|
|
|
ensure_ascii=False)
|
2023-08-14 10:35:47 +08:00
|
|
|
|
|
2023-07-27 23:22:07 +08:00
|
|
|
|
await task
|
2023-08-08 23:54:51 +08:00
|
|
|
|
|
2023-12-13 16:08:58 +08:00
|
|
|
|
return EventSourceResponse(chat_iterator())
|