main.py 11.1 KB
Newer Older
1
2
from fastapi import FastAPI, Depends
from fastapi.routing import APIRoute
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
3
from fastapi.responses import StreamingResponse
4
from fastapi.middleware.cors import CORSMiddleware
5
from starlette.middleware.sessions import SessionMiddleware
6
from sqlalchemy.orm import Session
7
from apps.webui.routers import (
Timothy J. Baek's avatar
Timothy J. Baek committed
8
9
10
11
    auths,
    users,
    chats,
    documents,
Timothy J. Baek's avatar
Timothy J. Baek committed
12
    tools,
Timothy J. Baek's avatar
Timothy J. Baek committed
13
    models,
Timothy J. Baek's avatar
Timothy J. Baek committed
14
15
    prompts,
    configs,
Timothy J. Baek's avatar
Timothy J. Baek committed
16
    memories,
Timothy J. Baek's avatar
Timothy J. Baek committed
17
    utils,
Timothy J. Baek's avatar
Timothy J. Baek committed
18
    files,
Timothy J. Baek's avatar
Timothy J. Baek committed
19
    functions,
Timothy J. Baek's avatar
Timothy J. Baek committed
20
)
Timothy J. Baek's avatar
Timothy J. Baek committed
21
22
from apps.webui.models.functions import Functions
from apps.webui.utils import load_function_module_by_id
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
23
from utils.misc import stream_message_template
Timothy J. Baek's avatar
Timothy J. Baek committed
24

Timothy J. Baek's avatar
Timothy J. Baek committed
25
from config import (
26
    WEBUI_BUILD_HASH,
27
28
    SHOW_ADMIN_DETAILS,
    ADMIN_EMAIL,
Timothy J. Baek's avatar
Timothy J. Baek committed
29
30
31
32
33
34
    WEBUI_AUTH,
    DEFAULT_MODELS,
    DEFAULT_PROMPT_SUGGESTIONS,
    DEFAULT_USER_ROLE,
    ENABLE_SIGNUP,
    USER_PERMISSIONS,
Timothy J. Baek's avatar
Timothy J. Baek committed
35
    WEBHOOK_URL,
36
    WEBUI_AUTH_TRUSTED_EMAIL_HEADER,
37
    WEBUI_AUTH_TRUSTED_NAME_HEADER,
38
    JWT_EXPIRES_IN,
Timothy J. Baek's avatar
Timothy J. Baek committed
39
    WEBUI_BANNERS,
40
    ENABLE_COMMUNITY_SHARING,
Timothy J. Baek's avatar
Timothy J. Baek committed
41
    AppConfig,
Timothy J. Baek's avatar
Timothy J. Baek committed
42
)
43

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
44
45
46
47
48
49
50
51
import inspect
import uuid
import time
import json

from typing import Iterator, Generator
from pydantic import BaseModel

52
53
54
55
app = FastAPI()

origins = ["*"]

56
app.state.config = AppConfig()
Timothy J. Baek's avatar
Timothy J. Baek committed
57

58
59
app.state.config.ENABLE_SIGNUP = ENABLE_SIGNUP
app.state.config.JWT_EXPIRES_IN = JWT_EXPIRES_IN
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
60
app.state.AUTH_TRUSTED_EMAIL_HEADER = WEBUI_AUTH_TRUSTED_EMAIL_HEADER
61
app.state.AUTH_TRUSTED_NAME_HEADER = WEBUI_AUTH_TRUSTED_NAME_HEADER
62

63
64
65
66
67

app.state.config.SHOW_ADMIN_DETAILS = SHOW_ADMIN_DETAILS
app.state.config.ADMIN_EMAIL = ADMIN_EMAIL


68
69
70
71
72
app.state.config.DEFAULT_MODELS = DEFAULT_MODELS
app.state.config.DEFAULT_PROMPT_SUGGESTIONS = DEFAULT_PROMPT_SUGGESTIONS
app.state.config.DEFAULT_USER_ROLE = DEFAULT_USER_ROLE
app.state.config.USER_PERMISSIONS = USER_PERMISSIONS
app.state.config.WEBHOOK_URL = WEBHOOK_URL
Timothy J. Baek's avatar
Timothy J. Baek committed
73
app.state.config.BANNERS = WEBUI_BANNERS
Timothy J. Baek's avatar
Timothy J. Baek committed
74

75
app.state.config.ENABLE_COMMUNITY_SHARING = ENABLE_COMMUNITY_SHARING
Timothy J. Baek's avatar
Timothy J. Baek committed
76
77

app.state.MODELS = {}
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
78
app.state.TOOLS = {}
Timothy J. Baek's avatar
Timothy J. Baek committed
79
app.state.FUNCTIONS = {}
Timothy J. Baek's avatar
Timothy J. Baek committed
80

81
82
83
84
85
86
87
88
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

Timothy J. Baek's avatar
Timothy J. Baek committed
89
90

app.include_router(configs.router, prefix="/configs", tags=["configs"])
91
app.include_router(auths.router, prefix="/auths", tags=["auths"])
92
93
app.include_router(users.router, prefix="/users", tags=["users"])
app.include_router(chats.router, prefix="/chats", tags=["chats"])
Timothy J. Baek's avatar
Timothy J. Baek committed
94

Timothy J. Baek's avatar
Timothy J. Baek committed
95
app.include_router(documents.router, prefix="/documents", tags=["documents"])
Timothy J. Baek's avatar
Timothy J. Baek committed
96
app.include_router(models.router, prefix="/models", tags=["models"])
97
app.include_router(prompts.router, prefix="/prompts", tags=["prompts"])
Timothy J. Baek's avatar
Timothy J. Baek committed
98

Timothy J. Baek's avatar
Timothy J. Baek committed
99
app.include_router(memories.router, prefix="/memories", tags=["memories"])
Timothy J. Baek's avatar
Timothy J. Baek committed
100
101
102
app.include_router(files.router, prefix="/files", tags=["files"])
app.include_router(tools.router, prefix="/tools", tags=["tools"])
app.include_router(functions.router, prefix="/functions", tags=["functions"])
Timothy J. Baek's avatar
Timothy J. Baek committed
103

Timothy J. Baek's avatar
Timothy J. Baek committed
104
app.include_router(utils.router, prefix="/utils", tags=["utils"])
105
106
107
108


@app.get("/")
async def get_status():
Timothy J. Baek's avatar
Timothy J. Baek committed
109
110
111
    return {
        "status": True,
        "auth": WEBUI_AUTH,
112
113
        "default_models": app.state.config.DEFAULT_MODELS,
        "default_prompt_suggestions": app.state.config.DEFAULT_PROMPT_SUGGESTIONS,
Timothy J. Baek's avatar
Timothy J. Baek committed
114
    }
Timothy J. Baek's avatar
Timothy J. Baek committed
115
116


117
118
async def get_pipe_models():
    pipes = Functions.get_functions_by_type("pipe", active_only=True)
Timothy J. Baek's avatar
Timothy J. Baek committed
119
120
121
122
123
    pipe_models = []

    for pipe in pipes:
        # Check if function is already loaded
        if pipe.id not in app.state.FUNCTIONS:
124
125
126
            function_module, function_type, frontmatter = load_function_module_by_id(
                pipe.id
            )
Timothy J. Baek's avatar
Timothy J. Baek committed
127
128
129
130
            app.state.FUNCTIONS[pipe.id] = function_module
        else:
            function_module = app.state.FUNCTIONS[pipe.id]

Timothy J. Baek's avatar
fix  
Timothy J. Baek committed
131
132
133
134
135
136
137
        if hasattr(function_module, "valves") and hasattr(function_module, "Valves"):
            print(f"Getting valves for {pipe.id}")
            valves = Functions.get_function_valves_by_id(pipe.id)
            function_module.valves = function_module.Valves(
                **(valves if valves else {})
            )

Timothy J. Baek's avatar
Timothy J. Baek committed
138
139
140
141
142
143
        # Check if function is a manifold
        if hasattr(function_module, "type"):
            if function_module.type == "manifold":
                manifold_pipes = []

                # Check if pipes is a function or a list
Timothy J. Baek's avatar
Timothy J. Baek committed
144
145
                if callable(function_module.pipes):
                    manifold_pipes = function_module.pipes()
Timothy J. Baek's avatar
Timothy J. Baek committed
146
                else:
Timothy J. Baek's avatar
Timothy J. Baek committed
147
                    manifold_pipes = function_module.pipes
Timothy J. Baek's avatar
Timothy J. Baek committed
148
149
150
151
152

                for p in manifold_pipes:
                    manifold_pipe_id = f'{pipe.id}.{p["id"]}'
                    manifold_pipe_name = p["name"]

Timothy J. Baek's avatar
Timothy J. Baek committed
153
                    if hasattr(function_module, "name"):
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
154
155
156
                        manifold_pipe_name = (
                            f"{function_module.name}{manifold_pipe_name}"
                        )
Timothy J. Baek's avatar
Timothy J. Baek committed
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180

                    pipe_models.append(
                        {
                            "id": manifold_pipe_id,
                            "name": manifold_pipe_name,
                            "object": "model",
                            "created": pipe.created_at,
                            "owned_by": "openai",
                            "pipe": {"type": pipe.type},
                        }
                    )
        else:
            pipe_models.append(
                {
                    "id": pipe.id,
                    "name": pipe.name,
                    "object": "model",
                    "created": pipe.created_at,
                    "owned_by": "openai",
                    "pipe": {"type": "pipe"},
                }
            )

    return pipe_models
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237


async def generate_function_chat_completion(form_data, user):
    async def job():
        pipe_id = form_data["model"]
        if "." in pipe_id:
            pipe_id, sub_pipe_id = pipe_id.split(".", 1)
        print(pipe_id)

        # Check if function is already loaded
        if pipe_id not in app.state.FUNCTIONS:
            function_module, function_type, frontmatter = load_function_module_by_id(
                pipe_id
            )
            app.state.FUNCTIONS[pipe_id] = function_module
        else:
            function_module = app.state.FUNCTIONS[pipe_id]

        if hasattr(function_module, "valves") and hasattr(function_module, "Valves"):

            valves = Functions.get_function_valves_by_id(pipe_id)
            function_module.valves = function_module.Valves(
                **(valves if valves else {})
            )

        pipe = function_module.pipe

        # Get the signature of the function
        sig = inspect.signature(pipe)
        params = {"body": form_data}

        if "__user__" in sig.parameters:
            __user__ = {
                "id": user.id,
                "email": user.email,
                "name": user.name,
                "role": user.role,
            }

            try:
                if hasattr(function_module, "UserValves"):
                    __user__["valves"] = function_module.UserValves(
                        **Functions.get_user_valves_by_id_and_user_id(pipe_id, user.id)
                    )
            except Exception as e:
                print(e)

            params = {**params, "__user__": __user__}

        if form_data["stream"]:

            async def stream_content():
                try:
                    if inspect.iscoroutinefunction(pipe):
                        res = await pipe(**params)
                    else:
                        res = pipe(**params)
Timothy J. Baek's avatar
Timothy J. Baek committed
238
239
240
241
242
243
244
245
246
247

                    # Directly return if the response is a StreamingResponse
                    if isinstance(res, StreamingResponse):
                        async for data in res.body_iterator:
                            yield data
                        return
                    if isinstance(res, dict):
                        yield f"data: {json.dumps(res)}\n\n"
                        return

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
                except Exception as e:
                    print(f"Error: {e}")
                    yield f"data: {json.dumps({'error': {'detail':str(e)}})}\n\n"
                    return

                if isinstance(res, str):
                    message = stream_message_template(form_data["model"], res)
                    yield f"data: {json.dumps(message)}\n\n"

                if isinstance(res, Iterator):
                    for line in res:
                        if isinstance(line, BaseModel):
                            line = line.model_dump_json()
                            line = f"data: {line}"
                        try:
                            line = line.decode("utf-8")
                        except:
                            pass

                        if line.startswith("data:"):
                            yield f"{line}\n\n"
                        else:
                            line = stream_message_template(form_data["model"], line)
                            yield f"data: {json.dumps(line)}\n\n"

                if isinstance(res, str) or isinstance(res, Generator):
                    finish_message = {
                        "id": f"{form_data['model']}-{str(uuid.uuid4())}",
                        "object": "chat.completion.chunk",
                        "created": int(time.time()),
                        "model": form_data["model"],
                        "choices": [
                            {
                                "index": 0,
                                "delta": {},
                                "logprobs": None,
                                "finish_reason": "stop",
                            }
                        ],
                    }

                    yield f"data: {json.dumps(finish_message)}\n\n"
                    yield f"data: [DONE]"

            return StreamingResponse(stream_content(), media_type="text/event-stream")
        else:

            try:
                if inspect.iscoroutinefunction(pipe):
                    res = await pipe(**params)
                else:
                    res = pipe(**params)
Timothy J. Baek's avatar
Timothy J. Baek committed
300
301
302

                if isinstance(res, StreamingResponse):
                    return res
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
            except Exception as e:
                print(f"Error: {e}")
                return {"error": {"detail": str(e)}}

            if isinstance(res, dict):
                return res
            elif isinstance(res, BaseModel):
                return res.model_dump()
            else:
                message = ""
                if isinstance(res, str):
                    message = res
                if isinstance(res, Generator):
                    for stream in res:
                        message = f"{message}{stream}"

                return {
                    "id": f"{form_data['model']}-{str(uuid.uuid4())}",
                    "object": "chat.completion",
                    "created": int(time.time()),
                    "model": form_data["model"],
                    "choices": [
                        {
                            "index": 0,
                            "message": {
                                "role": "assistant",
                                "content": message,
                            },
                            "logprobs": None,
                            "finish_reason": "stop",
                        }
                    ],
                }

    return await job()