Langchain-Chatchat/server/chat/chat.py

56 lines
2.2 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
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
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": "虎头虎脑"}]]
),
2023-08-08 23:54:51 +08:00
):
history = [History(**h) if isinstance(h, dict) else 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] = [],
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[LLM_MODEL]["api_key"],
openai_api_base=llm_model_dict[LLM_MODEL]["api_base_url"],
model_name=LLM_MODEL
)
2023-08-08 23:54:51 +08:00
chat_prompt = ChatPromptTemplate.from_messages(
[i.to_msg_tuple() for i in history] + [("human", "{input}")])
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),
)
async for token in callback.aiter():
# Use server-sent-events to stream the response
yield token
await task
2023-08-08 23:54:51 +08:00
return StreamingResponse(chat_iterator(query, history),
media_type="text/event-stream")