main.py 2.99 KB
Newer Older
Timothy J. Baek's avatar
Timothy J. Baek committed
1
2
3
from litellm.proxy.proxy_server import ProxyConfig, initialize
from litellm.proxy.proxy_server import app

4
from fastapi import FastAPI, Request, Depends, status, Response
Timothy J. Baek's avatar
Timothy J. Baek committed
5
from fastapi.responses import JSONResponse
6
7
8
9
10

from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
from starlette.responses import StreamingResponse
import json

Timothy J. Baek's avatar
Timothy J. Baek committed
11
12
13
from utils.utils import get_http_authorization_cred, get_current_user
from config import ENV

14
15
16
17
18
19
20

from config import (
    MODEL_FILTER_ENABLED,
    MODEL_FILTER_LIST,
)


Timothy J. Baek's avatar
Timothy J. Baek committed
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
proxy_config = ProxyConfig()


async def config():
    router, model_list, general_settings = await proxy_config.load_config(
        router=None, config_file_path="./data/litellm/config.yaml"
    )

    await initialize(config="./data/litellm/config.yaml", telemetry=False)


async def startup():
    await config()


@app.on_event("startup")
async def on_startup():
    await startup()


41
42
43
44
app.state.MODEL_FILTER_ENABLED = MODEL_FILTER_ENABLED
app.state.MODEL_FILTER_LIST = MODEL_FILTER_LIST


Timothy J. Baek's avatar
Timothy J. Baek committed
45
46
47
@app.middleware("http")
async def auth_middleware(request: Request, call_next):
    auth_header = request.headers.get("Authorization", "")
48
    request.state.user = None
Timothy J. Baek's avatar
Timothy J. Baek committed
49
50
51
52
53

    if ENV != "dev":
        try:
            user = get_current_user(get_http_authorization_cred(auth_header))
            print(user)
54
            request.state.user = user
Timothy J. Baek's avatar
Timothy J. Baek committed
55
56
57
58
59
        except Exception as e:
            return JSONResponse(status_code=400, content={"detail": str(e)})

    response = await call_next(request)
    return response
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


class ModifyModelsResponseMiddleware(BaseHTTPMiddleware):
    async def dispatch(
        self, request: Request, call_next: RequestResponseEndpoint
    ) -> Response:

        response = await call_next(request)
        user = request.state.user

        # Check if the request is for the `/models` route
        if "/models" in request.url.path:
            # Ensure the response is a StreamingResponse
            if isinstance(response, StreamingResponse):
                # Read the content of the streaming response
                body = b""
                async for chunk in response.body_iterator:
                    body += chunk

                # Modify the content as needed
                data = json.loads(body.decode("utf-8"))

                print(data)

                if app.state.MODEL_FILTER_ENABLED:
                    if user and user.role == "user":
                        data["data"] = list(
                            filter(
                                lambda model: model["id"]
                                in app.state.MODEL_FILTER_LIST,
                                data["data"],
                            )
                        )

                # Example modification: Add a new key-value pair
                data["modified"] = True

                # Return a new JSON response with the modified content
                return JSONResponse(content=data)

        return response


# Add the middleware to the app
app.add_middleware(ModifyModelsResponseMiddleware)