mzobe commited on
Commit ·
fff3dc4
1
Parent(s): c7595ab
streaming
Browse filesFiles changed (3)
- DockerfileAdded+22
- main.pyAdded+104
- requirements.txtAdded+22
12345678910111213141516171819202122FROM python:3.9
WORKDIR /code
COPY ./requirements.txt /code/requirements.txt
RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt
RUN useradd -m -u 1000 user
USER user
ENV HOME=/home/user \ PATH=/home/user/.local/bin:$PATH
WORKDIR $HOME/app
COPY --chown=user . $HOME/app
COPY . .
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
from fastapi import FastAPI,Depends, HTTPException, status, Request # type: ignorefrom fastapi.responses import StreamingResponse # type: ignorefrom transformers import AutoTokenizer, AutoModelForCausalLM # type: ignorefrom fastapi.security import APIKeyHeader # type: ignorefrom pydantic import BaseModelfrom typing import Optional
from transformers import TextStreamer # type: ignoreimport asynciofrom threading import Threadfrom queue import Queue
# Defining a custom streamer which inherits the Text Streamerclass CustomStreamer(TextStreamer):
def __init__(self, queue, tokenizer, skip_prompt, **decode_kwargs) -> None: super().__init__(tokenizer, skip_prompt, **decode_kwargs) # Queue taken as input to the class self._queue = queue self.stop_signal=None self.timeout = 1 def on_finalized_text(self, text: str, stream_end: bool = False): # Instead of printing the text, we add the text into the queue self._queue.put(text) if stream_end: # Similarly we add the stop signal also in the queue to # break the stream self._queue.put(self.stop_signal)
#modelsmodel_name_en = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"tokenizer_en = AutoTokenizer.from_pretrained(model_name_en)model_en = AutoModelForCausalLM.from_pretrained(model_name_en)
api_key = APIKeyHeader(name="X-API-KEY", auto_error=False)
async def check_api_key(api_key: str = Depends(api_key)): # Validate the API key (replace with your validation logic) if api_key != "1234567890": raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Invalid API key")
return api_key
class Message(BaseModel): text: str filename: Optional[str] = None
app =FastAPI()
# Creating the queuestreamer_queue = Queue()
# Creating the streamerstreamer = CustomStreamer(streamer_queue, tokenizer_en, True)
# The generation processdef start_generation(query):
prompt = """
# You are assistant that behaves very professionally. # You will only provide the answer if you know the answer. If you do not know the answer, you will say I dont know.
# ###Human: {instruction}, # ###Assistant: """.format(instruction=query) inputs = tokenizer_en([prompt], return_tensors="pt") generation_kwargs = dict(inputs, streamer=streamer, max_new_tokens=64, temperature=0.1) thread = Thread(target=model_en.generate, kwargs=generation_kwargs) thread.start()
# Generation initiator and response serverasync def response_generator(query):
start_generation(query)
while True: value = streamer_queue.get() if value == None: break yield value streamer_queue.task_done() await asyncio.sleep(0.1)
@app.get('/query-stream/')async def stream(query: str): print(f'Query receieved: {query}') return StreamingResponse(response_generator(query), media_type='text/event-stream')
@app.get("/")async def running(): return {"Hello": f" A simple Chatbot "}
12345678910111213141516171819202122deep-translatorfastapiuvicorntransformersrequestssentencepiecetorchsacremosesprotobuflangchain-communitysupabasetiktokensentence-transformerslangchainlangchain_corelangchain-huggingfacebitsandbytesredis
DockerfileAdded+22
main.pyAdded+104
requirements.txtAdded+22