from fastapi import Body
from sse_starlette.sse import EventSourceResponse
from configs import LLM_MODELS, TEMPERATURE
from server.utils import wrap_done, get_OpenAI
from langchain.chains import LLMChain
from langchain.callbacks import AsyncIteratorCallbackHandler
from typing import AsyncIterable, Optional
import asyncio
from langchain.prompts import PromptTemplate

from server.utils import get_prompt_template


async def completion(query: str = Body(..., description="用户输入", examples=["恼羞成怒"]),
                     stream: bool = Body(False, description="流式输出"),
                     echo: bool = Body(False, description="除了输出之外，还回显输入"),
                     model_name: str = Body(LLM_MODELS[0], description="LLM 模型名称。"),
                     temperature: float = Body(TEMPERATURE, description="LLM 采样温度", ge=0.0, le=1.0),
                     max_tokens: Optional[int] = Body(1024, 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中配置)"),
                     ):

    #todo 因ApiModelWorker 默认是按chat处理的，会对params["prompt"] 解析为messages，因此ApiModelWorker 使用时需要有相应处理
    async def completion_iterator(query: str,
                                  model_name: str = LLM_MODELS[0],
                                  prompt_name: str = prompt_name,
                                  echo: bool = echo,
                                  ) -> AsyncIterable[str]:
        nonlocal max_tokens
        callback = AsyncIteratorCallbackHandler()
        if isinstance(max_tokens, int) and max_tokens <= 0:
            max_tokens = None

        model = get_OpenAI(
            model_name=model_name,
            temperature=temperature,
            max_tokens=max_tokens,
            callbacks=[callback],
            echo=echo
        )

        prompt_template = get_prompt_template("completion", prompt_name)
        prompt = PromptTemplate.from_template(prompt_template)
        chain = LLMChain(prompt=prompt, llm=model)

        # Begin a task that runs in the background.
        task = asyncio.create_task(wrap_done(
            chain.acall({"input": query}),
            callback.done),
        )

        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

        await task

    return EventSourceResponse(completion_iterator(query=query,
                                                 model_name=model_name,
                                                 prompt_name=prompt_name),
                             )

langchain.chains.LLMChain langchain.prompts.PromptTemplate.from_template langchain.callbacks.AsyncIteratorCallbackHandler
[((450, 498), 'fastapi.Body', 'Body', (['...'], {'description': '"""用户输入"""', 'examples': "['恼羞成怒']"}), "(..., description='用户输入', examples=['恼羞成怒'])\n", (454, 498), False, 'from fastapi import Body\n'), ((536, 567), 'fastapi.Body', 'Body', (['(False)'], {'description': '"""流式输出"""'}), "(False, description='流式输出')\n", (540, 567), False, 'from fastapi import Body\n'), ((603, 642), 'fastapi.Body', 'Body', (['(False)'], {'description': '"""除了输出之外，还回显输入"""'}), "(False, description='除了输出之外，还回显输入')\n", (607, 642), False, 'from fastapi import Body\n'), ((683, 727), 'fastapi.Body', 'Body', (['LLM_MODELS[0]'], {'description': '"""LLM 模型名称。"""'}), "(LLM_MODELS[0], description='LLM 模型名称。')\n", (687, 727), False, 'from fastapi import Body\n'), ((771, 828), 'fastapi.Body', 'Body', (['TEMPERATURE'], {'description': '"""LLM 采样温度"""', 'ge': '(0.0)', 'le': '(1.0)'}), "(TEMPERATURE, description='LLM 采样温度', ge=0.0, le=1.0)\n", (775, 828), False, 'from fastapi import Body\n'), ((879, 933), 'fastapi.Body', 'Body', (['(1024)'], {'description': '"""限制LLM生成Token数量，默认None代表模型最大值"""'}), "(1024, description='限制LLM生成Token数量，默认None代表模型最大值')\n", (883, 933), False, 'from fastapi import Body\n'), ((1083, 1157), 'fastapi.Body', 'Body', (['"""default"""'], {'description': '"""使用的prompt模板名称(在configs/prompt_config.py中配置)"""'}), "('default', description='使用的prompt模板名称(在configs/prompt_config.py中配置)')\n", (1087, 1157), False, 'from fastapi import Body\n'), ((1664, 1694), 'langchain.callbacks.AsyncIteratorCallbackHandler', 'AsyncIteratorCallbackHandler', ([], {}), '()\n', (1692, 1694), False, 'from langchain.callbacks import AsyncIteratorCallbackHandler\n'), ((1802, 1921), 'server.utils.get_OpenAI', 'get_OpenAI', ([], {'model_name': 'model_name', 'temperature': 'temperature', 'max_tokens': 'max_tokens', 'callbacks': '[callback]', 'echo': 'echo'}), '(model_name=model_name, temperature=temperature, max_tokens=\n    max_tokens, callbacks=[callback], echo=echo)\n', (1812, 1921), False, 'from server.utils import wrap_done, get_OpenAI\n'), ((2014, 2060), 'server.utils.get_prompt_template', 'get_prompt_template', (['"""completion"""', 'prompt_name'], {}), "('completion', prompt_name)\n", (2033, 2060), False, 'from server.utils import get_prompt_template\n'), ((2078, 2123), 'langchain.prompts.PromptTemplate.from_template', 'PromptTemplate.from_template', (['prompt_template'], {}), '(prompt_template)\n', (2106, 2123), False, 'from langchain.prompts import PromptTemplate\n'), ((2140, 2174), 'langchain.chains.LLMChain', 'LLMChain', ([], {'prompt': 'prompt', 'llm': 'model'}), '(prompt=prompt, llm=model)\n', (2148, 2174), False, 'from langchain.chains import LLMChain\n')]