summaryrefslogtreecommitdiff
path: root/server/tests/util/openai_mock.py
blob: 763c564758e718ef116af3284302a0273a79f0eb (plain)
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
import asyncio
import os
import random
import subprocess
from typing import Dict, List, Optional

from fastapi import FastAPI
from fastapi.responses import StreamingResponse
from pydantic import BaseModel

openai = FastAPI()


class CompletionBody(BaseModel):
    prompt: str
    max_tokens: Optional[int] = 60
    stream: Optional[bool] = False

    class Config:
        extra = "allow"


@openai.post("/completions")
@openai.post("/v1/completions")
async def mock_completion(item: CompletionBody):
    prompt = item.prompt

    text = "This is a fake completion."

    if item.stream:

        async def stream_text():
            for i in range(len(text)):
                word = random.choice(prompt.split())
                yield {
                    "choices": [
                        {
                            "delta": {"role": "assistant", "content": word},
                            "finish_reason": None,
                            "index": 0,
                        }
                    ],
                    "created": 1677825464,
                    "id": "chatcmpl-6ptKyqKOGXZT6iQnqiXAH8adNLUzD",
                    "model": "gpt-3.5-turbo-0301",
                    "object": "chat.completion.chunk",
                }
                await asyncio.sleep(0.1)

        return StreamingResponse(stream_text(), media_type="text/plain")

    return {
        "id": "cmpl-uqkvlQyYK7bGYrRHQ0eXlWi7",
        "object": "text_completion",
        "created": 1589478378,
        "model": "gpt-3.5-turbo",
        "choices": [
            {
                "text": text,
                "index": 0,
                "logprobs": None,
                "finish_reason": "length",
            }
        ],
        "usage": {"prompt_tokens": 5, "completion_tokens": 7, "total_tokens": 12},
    }


class ChatBody(BaseModel):
    messages: List[Dict[str, str]]
    max_tokens: Optional[int] = None
    stream: Optional[bool] = False

    class Config:
        extra = "allow"


@openai.post("/v1/chat/completions")
async def mock_chat_completion(item: ChatBody):
    text = "This is a fake completion."

    if item.stream:

        async def stream_text():
            for i in range(len(text)):
                word = text[i]
                yield {
                    "choices": [
                        {
                            "delta": {"role": "assistant", "content": word},
                            "finish_reason": None,
                            "index": 0,
                        }
                    ],
                    "created": 1677825464,
                    "id": "chatcmpl-6ptKyqKOGXZT6iQnqiXAH8adNLUzD",
                    "model": "gpt-3.5-turbo-0301",
                    "object": "chat.completion.chunk",
                }
                await asyncio.sleep(0.1)

        return StreamingResponse(stream_text(), media_type="text/plain")

    return {
        "id": "chatcmpl-123",
        "object": "chat.completion",
        "created": 1677652288,
        "model": "gpt-3.5-turbo-0613",
        "choices": [
            {
                "index": 0,
                "message": {
                    "role": "assistant",
                    "content": text,
                },
                "finish_reason": "stop",
            }
        ],
        "usage": {"prompt_tokens": 9, "completion_tokens": 12, "total_tokens": 21},
    }


def start_openai(port: int = 8000):
    server = subprocess.Popen(
        [
            "uvicorn",
            "openai_mock:openai",
            "--host",
            "127.0.0.1",
            "--port",
            str(port),
        ],
        cwd=os.path.dirname(__file__),
    )
    return server


if __name__ == "__main__":
    start_openai()