main.py 4.06 KB
Newer Older
1
from fastapi import FastAPI, Request, Response, HTTPException, Depends, status
2
3
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import StreamingResponse
Timothy J. Baek's avatar
Timothy J. Baek committed
4
from fastapi.concurrency import run_in_threadpool
Timothy J. Baek's avatar
Timothy J. Baek committed
5
6
7

import requests
import json
8
import uuid
9
from pydantic import BaseModel
Timothy J. Baek's avatar
Timothy J. Baek committed
10

11
12
from apps.web.models.users import Users
from constants import ERROR_MESSAGES
13
from utils.utils import decode_token, get_current_user, get_admin_user
14
from config import OLLAMA_API_BASE_URL, WEBUI_AUTH
Timothy J. Baek's avatar
Timothy J. Baek committed
15

16
17
18
19
20
21
22
23
app = FastAPI()
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
Timothy J. Baek's avatar
Timothy J. Baek committed
24

25
app.state.OLLAMA_API_BASE_URL = OLLAMA_API_BASE_URL
Timothy J. Baek's avatar
Timothy J. Baek committed
26

27
# TARGET_SERVER_URL = OLLAMA_API_BASE_URL
Timothy J. Baek's avatar
Timothy J. Baek committed
28
29


30
31
32
REQUEST_POOL = []


33
@app.get("/url")
34
35
async def get_ollama_api_url(user=Depends(get_admin_user)):
    return {"OLLAMA_API_BASE_URL": app.state.OLLAMA_API_BASE_URL}
36

Timothy J. Baek's avatar
Timothy J. Baek committed
37

38
39
40
41
42
class UrlUpdateForm(BaseModel):
    url: str


@app.post("/url/update")
Timothy J. Baek's avatar
Timothy J. Baek committed
43
async def update_ollama_api_url(
44
    form_data: UrlUpdateForm, user=Depends(get_admin_user)
Timothy J. Baek's avatar
Timothy J. Baek committed
45
):
46
47
    app.state.OLLAMA_API_BASE_URL = form_data.url
    return {"OLLAMA_API_BASE_URL": app.state.OLLAMA_API_BASE_URL}
Timothy J. Baek's avatar
Timothy J. Baek committed
48
49


50
51
52
53
54
55
56
57
58
59
@app.get("/cancel/{request_id}")
async def cancel_ollama_request(request_id: str, user=Depends(get_current_user)):
    if user:
        if request_id in REQUEST_POOL:
            REQUEST_POOL.remove(request_id)
        return True
    else:
        raise HTTPException(status_code=401, detail=ERROR_MESSAGES.ACCESS_PROHIBITED)


60
61
62
63
64
65
66
67
68
69
@app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE"])
async def proxy(path: str, request: Request, user=Depends(get_current_user)):
    target_url = f"{app.state.OLLAMA_API_BASE_URL}/{path}"

    body = await request.body()
    headers = dict(request.headers)

    if user.role in ["user", "admin"]:
        if path in ["pull", "delete", "push", "copy", "create"]:
            if user.role != "admin":
Timothy J. Baek's avatar
Timothy J. Baek committed
70
                raise HTTPException(
71
                    status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.ACCESS_PROHIBITED
Timothy J. Baek's avatar
Timothy J. Baek committed
72
                )
73
    else:
74
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.ACCESS_PROHIBITED)
75

76
77
78
79
    headers.pop("host", None)
    headers.pop("authorization", None)
    headers.pop("origin", None)
    headers.pop("referer", None)
Timothy J. Baek's avatar
Timothy J. Baek committed
80

Timothy J. Baek's avatar
Timothy J. Baek committed
81
82
83
84
    r = None

    def get_request():
        nonlocal r
85
86

        request_id = str(uuid.uuid4())
Timothy J. Baek's avatar
Timothy J. Baek committed
87
        try:
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
            REQUEST_POOL.append(request_id)

            def stream_content():
                try:
                    if path in ["chat"]:
                        yield json.dumps({"id": request_id, "done": False}) + "\n"

                    for chunk in r.iter_content(chunk_size=8192):
                        if request_id in REQUEST_POOL:
                            yield chunk
                        else:
                            print("User: canceled request")
                            break
                finally:
                    if hasattr(r, "close"):
                        r.close()
                        REQUEST_POOL.remove(request_id)

Timothy J. Baek's avatar
Timothy J. Baek committed
106
107
108
109
110
111
112
113
114
115
            r = requests.request(
                method=request.method,
                url=target_url,
                data=body,
                headers=headers,
                stream=True,
            )

            r.raise_for_status()

116
117
            # r.close()

Timothy J. Baek's avatar
Timothy J. Baek committed
118
            return StreamingResponse(
119
                stream_content(),
Timothy J. Baek's avatar
Timothy J. Baek committed
120
121
122
123
124
                status_code=r.status_code,
                headers=dict(r.headers),
            )
        except Exception as e:
            raise e
125

Timothy J. Baek's avatar
Timothy J. Baek committed
126
127
    try:
        return await run_in_threadpool(get_request)
128
    except Exception as e:
129
        error_detail = "Ollama WebUI: Server Connection Error"
Timothy J. Baek's avatar
Timothy J. Baek committed
130
        if r is not None:
131
            try:
Timothy J. Baek's avatar
Timothy J. Baek committed
132
                res = r.json()
133
134
135
136
137
                if "error" in res:
                    error_detail = f"Ollama: {res['error']}"
            except:
                error_detail = f"Ollama: {e}"

Timothy J. Baek's avatar
Timothy J. Baek committed
138
        raise HTTPException(
Timothy J. Baek's avatar
Timothy J. Baek committed
139
            status_code=r.status_code if r else 500,
Timothy J. Baek's avatar
Timothy J. Baek committed
140
141
            detail=error_detail,
        )