Spaces:
Runtime error
Runtime error
File size: 7,087 Bytes
4107531 a178fd6 4107531 60bb91e a178fd6 4c9b469 a178fd6 60bb91e 82b42e7 6500788 d42b6d6 6500788 8cd1822 7bfabdf 60bb91e 38acba7 60bb91e a178fd6 60bb91e ad66be0 60bb91e 1828807 6500788 1828807 6500788 4c9b469 1828807 c32808f 4c9b469 7bfabdf d42b6d6 0fdaf32 d42b6d6 b2e11d6 d42b6d6 0fdaf32 4c9b469 d42b6d6 8cd1822 16c8074 4c9b469 7bfabdf 16c8074 21a8c71 7bfabdf 4c9b469 a178fd6 60bb91e 3ae76f6 4107531 bb9b91b 4107531 bb9b91b 4107531 bb9b91b 4107531 bb9b91b 4c9b469 a178fd6 60bb91e 4107531 60bb91e 4107531 |
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 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 |
import argparse
import markdown2
import sys
import uvicorn
from pathlib import Path
from fastapi import FastAPI
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel, Field
from sse_starlette.sse import EventSourceResponse
from conversations import (
ConversationConnector,
ConversationCreator,
MessageComposer,
)
from utils.logger import logger
class ChatAPIApp:
def __init__(self):
self.app = FastAPI(
docs_url="/",
title="Bing Chat API",
swagger_ui_parameters={"defaultModelsExpandDepth": -1},
version="1.0",
)
self.setup_routes()
self.app.mount("/docs", StaticFiles(directory="docs", html=True), name="docs")
def get_available_models(self):
self.available_models = {
"object": "list",
"data": [
{
"id": "precise",
"description": "Bing (Precise): Concise and straightforward.",
"object": "model",
"created": 1700000000,
"owned_by": "bing",
},
{
"id": "balanced",
"description": "Bing (Balanced): Informative and friendly.",
"object": "model",
"created": 1700000000,
"owned_by": "bing",
},
{
"id": "creative",
"description": "Bing (Creative): Original and imaginative.",
"object": "model",
"created": 1700000000,
"owned_by": "bing",
},
{
"id": "precise-offline",
"description": "Bing (Precise): (No Internet) Concise and straightforward.",
"object": "model",
"created": 1700000000,
"owned_by": "bing",
},
{
"id": "balanced-offline",
"description": "Bing (Balanced): (No Internet) Informative and friendly.",
"object": "model",
"created": 1700000000,
"owned_by": "bing",
},
{
"id": "creative-offline",
"description": "Bing (Creative): (No Internet) Original and imaginative.",
"object": "model",
"created": 1700000000,
"owned_by": "bing",
},
],
}
return self.available_models
class CreateConversationSessionPostItem(BaseModel):
model: str = Field(
default="precise",
description="(str) `precise`, `balanced`, `creative`, `precise-offline`, `balanced-offline`, `creative-offline`",
)
def create_conversation_session(self, item: CreateConversationSessionPostItem):
creator = ConversationCreator()
creator.create()
return {
"model": item.model,
"sec_access_token": creator.sec_access_token,
"client_id": creator.client_id,
"conversation_id": creator.conversation_id,
}
class ChatCompletionsPostItem(BaseModel):
model: str = Field(
default="precise",
description="(str) `precise`, `balanced`, `creative`, `precise-offline`, `balanced-offline`, `creative-offline`",
)
messages: list = Field(
default=[{"role": "user", "content": "Hello, who are you?"}],
description="(list) Messages",
)
def chat_completions(self, item: ChatCompletionsPostItem):
creator = ConversationCreator()
creator.create()
connector = ConversationConnector(
conversation_style=item.model,
sec_access_token=creator.sec_access_token,
client_id=creator.client_id,
conversation_id=creator.conversation_id,
cookies=creator.request_cookies,
invocation_id=0,
)
message_composer = MessageComposer()
prompt = message_composer.merge(item.messages)
logger.mesg(item.messages[-1]["content"])
system_prompt = message_composer.system_prompt
return EventSourceResponse(
connector.stream_chat(
prompt=prompt, system_prompt=system_prompt, yield_output=True
),
ping=2000,
media_type="text/event-stream",
)
def get_readme(self):
readme_path = Path(__file__).parents[1] / "README.md"
with open(readme_path, "r", encoding="utf-8") as rf:
readme_str = rf.read()
readme_html = markdown2.markdown(
readme_str, extras=["table", "fenced-code-blocks", "highlightjs-lang"]
)
return readme_html
def setup_routes(self):
for prefix in ["", "/v1", "/api", "/api/v1"]:
include_in_schema = True if prefix == "" else False
self.app.get(
prefix + "/models",
summary="Get available models",
include_in_schema=include_in_schema,
)(self.get_available_models)
self.app.post(
prefix + "/create",
summary="Create a conversation session",
include_in_schema=include_in_schema,
)(self.create_conversation_session)
self.app.post(
prefix + "/chat/completions",
summary="Chat completions in conversation session",
include_in_schema=include_in_schema,
)(self.chat_completions)
self.app.get(
"/readme",
summary="README of Bing Chat API",
response_class=HTMLResponse,
include_in_schema=False,
)(self.get_readme)
class ArgParser(argparse.ArgumentParser):
def __init__(self, *args, **kwargs):
super(ArgParser, self).__init__(*args, **kwargs)
self.add_argument(
"-s",
"--server",
type=str,
default="0.0.0.0",
help="Server IP for Bing Chat API",
)
self.add_argument(
"-p",
"--port",
type=int,
default=22222,
help="Server Port for Bing Chat API",
)
self.add_argument(
"-d",
"--dev",
default=False,
action="store_true",
help="Run in dev mode",
)
self.args = self.parse_args(sys.argv[1:])
app = ChatAPIApp().app
if __name__ == "__main__":
args = ArgParser().args
if args.dev:
uvicorn.run("__main__:app", host=args.server, port=args.port, reload=True)
else:
uvicorn.run("__main__:app", host=args.server, port=args.port, reload=False)
# python -m apis.chat_api # [Docker] on product mode
# python -m apis.chat_api -d # [Dev] on develop mode
|