Langchain-Chatchat/server/chat/chat.py

71 lines
3.0 KiB
Python
Raw Normal View History

2023-07-27 23:22:07 +08:00
from fastapi import Body
from fastapi.responses import StreamingResponse
from configs.model_config import llm_model_dict, LLM_MODEL, TEMPERATURE
2023-08-06 18:32:10 +08:00
from server.chat.utils import wrap_done
2023-07-27 23:22:07 +08:00
from langchain.chat_models import ChatOpenAI
from langchain import LLMChain
from langchain.callbacks import AsyncIteratorCallbackHandler
from typing import AsyncIterable
import asyncio
2023-08-08 23:54:51 +08:00
from langchain.prompts.chat import ChatPromptTemplate
2023-08-10 21:26:05 +08:00
from typing import List
2023-08-08 23:54:51 +08:00
from server.chat.utils import History
2023-07-27 23:22:07 +08:00
async def chat(query: str = Body(..., description="用户输入", examples=["恼羞成怒"]),
history: List[History] = Body([],
2023-08-10 21:26:05 +08:00
description="历史对话",
examples=[[
{"role": "user", "content": "我们来玩成语接龙,我先来,生龙活虎"},
{"role": "assistant", "content": "虎头虎脑"}]]
),
stream: bool = Body(False, description="流式输出"),
model_name: str = Body(LLM_MODEL, description="LLM 模型名称。"),
temperature: float = Body(TEMPERATURE, description="LLM 采样温度", gt=0.0, le=1.0),
# top_p: float = Body(TOP_P, description="LLM 核采样。勿与temperature同时设置", gt=0.0, lt=1.0),
2023-08-08 23:54:51 +08:00
):
history = [History.from_data(h) for h in history]
2023-08-10 21:26:05 +08:00
2023-08-08 23:54:51 +08:00
async def chat_iterator(query: str,
history: List[History] = [],
model_name: str = LLM_MODEL,
2023-08-08 23:54:51 +08:00
) -> AsyncIterable[str]:
2023-07-27 23:22:07 +08:00
callback = AsyncIteratorCallbackHandler()
model = ChatOpenAI(
streaming=True,
verbose=True,
callbacks=[callback],
openai_api_key=llm_model_dict[model_name]["api_key"],
openai_api_base=llm_model_dict[model_name]["api_base_url"],
model_name=model_name,
temperature=temperature,
openai_proxy=llm_model_dict[model_name].get("openai_proxy")
2023-07-27 23:22:07 +08:00
)
input_msg = History(role="user", content="{{ input }}").to_msg_template(False)
2023-08-08 23:54:51 +08:00
chat_prompt = ChatPromptTemplate.from_messages(
[i.to_msg_template() for i in history] + [input_msg])
2023-08-08 23:54:51 +08:00
chain = LLMChain(prompt=chat_prompt, llm=model)
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
yield token
else:
answer = ""
async for token in callback.aiter():
answer += token
yield answer
2023-07-27 23:22:07 +08:00
await task
2023-08-08 23:54:51 +08:00
return StreamingResponse(chat_iterator(query, history, model_name),
2023-08-08 23:54:51 +08:00
media_type="text/event-stream")