-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
81 lines (65 loc) · 2.35 KB
/
Copy pathmain.py
File metadata and controls
81 lines (65 loc) · 2.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import asyncio
import json
import time
from time_of_day_handler import TimeOfDayHandler
from echo_model_handler import EchoModelHandler
from shakespeare_sonnet_handler import ShakespeareSonnetHandler
from default_handler import DefaultHandler
from shakespeare_sonnet_handler import ShakespeareSonnetHandler
from nonsense_poem_handler import NonsensePoemHandler
import uuid
from typing import Optional, List
from pydantic import BaseModel, Field
from starlette.responses import StreamingResponse
from fastapi import FastAPI, HTTPException, Request
app = FastAPI(title="OpenAI-compatible API")
COMPLETION_HANDLERS = {
'mock-gpt-model': EchoModelHandler,
'time-of-day': TimeOfDayHandler,
'sonnets': ShakespeareSonnetHandler,
'nonsense': NonsensePoemHandler,
}
# data models
class Message(BaseModel):
role: str
content: str
class ChatCompletionRequest(BaseModel):
model: Optional[str]
messages: List[Message]
max_tokens: Optional[int] = 512
temperature: Optional[float] = 0.1
stream: Optional[bool] = False
def complete(self):
handler = COMPLETION_HANDLERS.get(self.model, DefaultHandler)
return handler(self).complete()
async def _resp_async_generator(text_resp: str, request: ChatCompletionRequest):
# let's pretend every word is a token and return it over time
tokens = text_resp.split(" ")
for i, token in enumerate(tokens):
chunk = {
"id": str(uuid.uuid4()),
"object": "chat.completion.chunk",
"created": time.time(),
"model": request.model,
"choices": [{"delta": {"content": token + " "}}],
}
yield f"data: {json.dumps(chunk)}\n\n"
await asyncio.sleep(0.01)
yield "data: [DONE]\n\n"
@app.post("/v1/chat/completions")
async def chat_completions(request: ChatCompletionRequest):
resp_content = request.complete()
if request.stream:
return StreamingResponse(
_resp_async_generator(resp_content, request), media_type="application/x-ndjson"
)
return {
"id": str(uuid.uuid4()),
"object": "chat.completion",
"created": time.time(),
"model": request.model,
"choices": [{"message": Message(role="assistant", content=resp_content)}],
}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)