|
| 1 | +# Copyright (C) 2024 Intel Corporation |
| 2 | +# SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +import os |
| 5 | + |
| 6 | +from fastapi.responses import StreamingResponse |
| 7 | +from langchain.chains.summarize import load_summarize_chain |
| 8 | +from langchain.docstore.document import Document |
| 9 | +from langchain.prompts import PromptTemplate |
| 10 | +from langchain.text_splitter import CharacterTextSplitter |
| 11 | +from langchain_community.llms import VLLMOpenAI |
| 12 | + |
| 13 | +from comps import CustomLogger, GeneratedDoc, LLMParamsDoc, ServiceType, opea_microservices, register_microservice |
| 14 | +from comps.cores.mega.utils import get_access_token |
| 15 | + |
| 16 | +logger = CustomLogger("llm_faqgen") |
| 17 | +logflag = os.getenv("LOGFLAG", False) |
| 18 | + |
| 19 | +# Environment variables |
| 20 | +TOKEN_URL = os.getenv("TOKEN_URL") |
| 21 | +CLIENTID = os.getenv("CLIENTID") |
| 22 | +CLIENT_SECRET = os.getenv("CLIENT_SECRET") |
| 23 | + |
| 24 | + |
| 25 | +def post_process_text(text: str): |
| 26 | + if text == " ": |
| 27 | + return "data: @#$\n\n" |
| 28 | + if text == "\n": |
| 29 | + return "data: <br/>\n\n" |
| 30 | + if text.isspace(): |
| 31 | + return None |
| 32 | + new_text = text.replace(" ", "@#$") |
| 33 | + return f"data: {new_text}\n\n" |
| 34 | + |
| 35 | + |
| 36 | +@register_microservice( |
| 37 | + name="opea_service@llm_faqgen", |
| 38 | + service_type=ServiceType.LLM, |
| 39 | + endpoint="/v1/faqgen", |
| 40 | + host="0.0.0.0", |
| 41 | + port=9000, |
| 42 | +) |
| 43 | +async def llm_generate(input: LLMParamsDoc): |
| 44 | + if logflag: |
| 45 | + logger.info(input) |
| 46 | + access_token = ( |
| 47 | + get_access_token(TOKEN_URL, CLIENTID, CLIENT_SECRET) if TOKEN_URL and CLIENTID and CLIENT_SECRET else None |
| 48 | + ) |
| 49 | + headers = {} |
| 50 | + if access_token: |
| 51 | + headers = {"Authorization": f"Bearer {access_token}"} |
| 52 | + |
| 53 | + model = input.model if input.model else os.getenv("LLM_MODEL_ID") |
| 54 | + llm = VLLMOpenAI( |
| 55 | + openai_api_key="EMPTY", |
| 56 | + openai_api_base=llm_endpoint + "/v1", |
| 57 | + model_name=model, |
| 58 | + default_headers=headers, |
| 59 | + max_tokens=input.max_tokens, |
| 60 | + top_p=input.top_p, |
| 61 | + streaming=input.streaming, |
| 62 | + temperature=input.temperature, |
| 63 | + ) |
| 64 | + |
| 65 | + templ = """Create a concise FAQs (frequently asked questions and answers) for following text: |
| 66 | + TEXT: {text} |
| 67 | + Do not use any prefix or suffix to the FAQ. |
| 68 | + """ |
| 69 | + PROMPT = PromptTemplate.from_template(templ) |
| 70 | + llm_chain = load_summarize_chain(llm=llm, prompt=PROMPT) |
| 71 | + texts = text_splitter.split_text(input.query) |
| 72 | + |
| 73 | + # Create multiple documents |
| 74 | + docs = [Document(page_content=t) for t in texts] |
| 75 | + |
| 76 | + if input.streaming: |
| 77 | + |
| 78 | + async def stream_generator(): |
| 79 | + from langserve.serialization import WellKnownLCSerializer |
| 80 | + |
| 81 | + _serializer = WellKnownLCSerializer() |
| 82 | + async for chunk in llm_chain.astream_log(docs): |
| 83 | + data = _serializer.dumps({"ops": chunk.ops}).decode("utf-8") |
| 84 | + if logflag: |
| 85 | + logger.info(data) |
| 86 | + yield f"data: {data}\n\n" |
| 87 | + yield "data: [DONE]\n\n" |
| 88 | + |
| 89 | + return StreamingResponse(stream_generator(), media_type="text/event-stream") |
| 90 | + else: |
| 91 | + response = await llm_chain.ainvoke(docs) |
| 92 | + response = response["output_text"] |
| 93 | + if logflag: |
| 94 | + logger.info(response) |
| 95 | + return GeneratedDoc(text=response, prompt=input.query) |
| 96 | + |
| 97 | + |
| 98 | +if __name__ == "__main__": |
| 99 | + llm_endpoint = os.getenv("vLLM_ENDPOINT", "http://localhost:8080") |
| 100 | + # Split text |
| 101 | + text_splitter = CharacterTextSplitter() |
| 102 | + opea_microservices["opea_service@llm_faqgen"].start() |
0 commit comments