File size: 11,438 Bytes
2a473f0
154ea17
2a473f0
154ea17
17e63a8
154ea17
2a473f0
154ea17
 
3d39a20
154ea17
 
6d86fc0
 
 
c1b0151
154ea17
 
 
 
 
 
 
2a473f0
17e63a8
2a473f0
154ea17
17e63a8
 
154ea17
d4c432e
 
154ea17
 
 
 
 
 
 
 
c573ee8
 
154ea17
 
 
 
 
 
 
 
 
 
d4c432e
 
 
 
 
 
 
c573ee8
 
 
154ea17
c573ee8
154ea17
17e63a8
c573ee8
 
 
154ea17
17e63a8
154ea17
17e63a8
c573ee8
 
 
 
 
 
 
 
 
 
154ea17
 
 
 
 
 
 
 
 
c573ee8
154ea17
 
 
 
 
c573ee8
154ea17
 
c573ee8
17e63a8
154ea17
17e63a8
154ea17
 
 
 
 
 
 
 
 
17e63a8
 
 
 
2a473f0
 
3d39a20
154ea17
1ce4699
17e63a8
5de7a1a
6d86fc0
 
 
 
 
 
 
1441d80
6d86fc0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc5c78b
6d86fc0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a473f0
154ea17
 
2a473f0
 
154ea17
 
 
 
 
 
 
17e63a8
2a473f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
154ea17
 
 
 
 
 
2a473f0
154ea17
 
 
 
 
 
 
17e63a8
2a473f0
154ea17
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a473f0
 
 
154ea17
 
2a473f0
 
 
 
154ea17
 
 
 
 
 
 
 
 
 
 
 
2a473f0
 
154ea17
 
 
 
 
 
2a473f0
154ea17
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17e63a8
154ea17
 
 
 
 
 
 
 
2a473f0
154ea17
 
 
 
 
 
2a473f0
154ea17
 
 
 
 
 
 
 
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
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
238
239
240
241
242
243
244
245
246
247
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
300
301
302
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
import json
import logging
import time
from concurrent.futures import ThreadPoolExecutor
from contextvars import ContextVar
from typing import Any, Dict, Generator, List

from anthropic import Anthropic
from fastapi import FastAPI, HTTPException, Request, Response
from fastapi.responses import JSONResponse, StreamingResponse, HTMLResponse
from fastapi.security import HTTPBearer
from starlette.concurrency import run_in_threadpool
from pathlib import Path
import markdown
from pygments.formatters import HtmlFormatter


from schemas import OpenAIChatCompletionForm, FilterForm

# logger
logger = logging.getLogger()

# FastAPI app initialization
app = FastAPI()
security = HTTPBearer()

# Context variable for token storage
token_context = ContextVar('token', default=None)

# Endpoints that don't require authentication
PUBLIC_ENDPOINTS = {"/"}

# Available Anthropic models
AVAILABLE_MODELS = [
    "claude-3-haiku-20240307",
    "claude-3-opus-20240229",
    "claude-3-sonnet-20240229",
    "claude-3-5-sonnet-20241022"
]

@app.middleware("http")
async def auth_middleware(request: Request, call_next):
    """

    Middleware for handling authentication and response logging.

    

    Args:

        request: The incoming HTTP request

        call_next: The next middleware in the chain

        

    Returns:

        Response: The processed HTTP response

    """
    if request.url.path in PUBLIC_ENDPOINTS:
        start_time = time.perf_counter()
        response = await call_next(request)
        process_time = time.perf_counter() - start_time
        response.headers["X-Process-Time"] = str(process_time)
        return response
    
    try:
        auth_header = request.headers.get('Authorization')
        if not auth_header:
            raise HTTPException(
                status_code=401,
                detail="No authorization header"
            )
        
        scheme, token = auth_header.split()
        if scheme.lower() != 'bearer':
            raise HTTPException(
                status_code=401,
                detail="Invalid authentication scheme"
            )
        
        token_context.set(token)
        
        start_time = time.perf_counter()
        response = await call_next(request)
        process_time = time.perf_counter() - start_time
        response.headers["X-Process-Time"] = str(process_time)
        
        return response
            
    except HTTPException as http_ex:
        logger.error(
            f"HTTP Exception - Status: {http_ex.status_code} - "
            f"Detail: {http_ex.detail} - Path: {request.url.path}"
        )
        return JSONResponse(
            status_code=http_ex.status_code,
            content={"detail": http_ex.detail}
        )
    except Exception as e:
        logger.error(
            f"Unexpected error in middleware - Error: {str(e)} - "
            f"Path: {request.url.path}",
            exc_info=True
        )
        return JSONResponse(
            status_code=500,
            content={"detail": "Internal server error"}
        )


def get_anthropic_client():
    """

    Get an authenticated Anthropic client using the current token.

    

    Returns:

        Anthropic: An authenticated Anthropic client instance

        

    Raises:

        HTTPException: If no authorization token is found

    """
    token = token_context.get()
    if not token:
        raise HTTPException(status_code=401, detail="No authorization token found")
    return Anthropic(api_key=token)



@app.get("/v1")
@app.get("/")
async def read_root():
    """Root endpoint for API health check."""
    try:
        # Lecture du README.md
        readme_path = Path("README.md")
        if not readme_path.exists():
            return HTMLResponse(content="<h1>README.md non trouvé</h1>")
        
        md_text = readme_path.read_text(encoding='utf-8')
        md_text = '\n'.join(md_text.split('\n')[10:])
        
        # Conversion Markdown vers HTML
        html = markdown.markdown(
            md_text,
            extensions=[
                'markdown.extensions.fenced_code',
                'markdown.extensions.tables',
                'markdown.extensions.codehilite',
                'markdown.extensions.sane_lists'
            ]
        )
        
        # Lecture du CSS
        css_file = Path("main.css")
        custom_css = css_file.read_text(encoding='utf-8') if css_file.exists() else ""
        
        # CSS pour la coloration syntaxique
        code_css = HtmlFormatter(style='default').get_style_defs('.codehilite')
        
        # Construction de la page HTML
        html_content = f"""

        <!DOCTYPE html>

        <html>

        <head>

            <meta charset="utf-8">

            <meta name="viewport" content="width=device-width, initial-scale=1">

            <style>

                {custom_css}

                {code_css}

            </style>

        </head>

        <body>

            <div class="markdown-body">

                {html}

            </div>

        </body>

        </html>

        """
        
        return HTMLResponse(content=html_content)
        
    except Exception as e:
        return HTMLResponse(
            content=f"<h1>Erreur: {str(e)}</h1>",
            status_code=500
        )


@app.get("/v1/models")
@app.get("/models")
async def get_models():
    """

    Get available Anthropic models.

    

    Returns:

        JSONResponse: List of available models and their details

    """
    get_anthropic_client()  # Verify token validity
    
    models = [
        {
            "id": model_id,
            "object": "model",
            "name": f"🤖 {model_id}",
            "created": int(time.time()),
            "owned_by": "anthropic",
            "pipeline": {"type": "custom", "valves": False}
        }
        for model_id in AVAILABLE_MODELS
    ]
    
    return JSONResponse(
        content={
            "data": models,
            "object": "list",
            "pipelines": True,
        }
    )


def stream_message(

    model: str,

    messages: List[Dict[str, Any]]

) -> Generator[str, None, None]:
    """

    Stream messages using the specified model.

    

    Args:

        model: The model identifier to use

        messages: List of messages to process

        

    Returns:

        Generator: Stream of SSE formatted responses

    """
    client = get_anthropic_client()
    response = client.messages.create(
        model=model,
        max_tokens=1024,
        messages=messages,
        stream=True
    )

    def event_stream() -> Generator[str, None, None]:
        message_id = None
        
        for chunk in response:
            if not message_id:
                message_id = f"chatcmpl-{int(time.time())}"
                
            if chunk.type == 'content_block_delta':
                data = {
                    "id": message_id,
                    "object": "chat.completion.chunk",
                    "created": int(time.time()),
                    "model": model,
                    "choices": [
                        {
                            "index": 0,
                            "delta": {
                                "content": (
                                    chunk.delta.text
                                    if hasattr(chunk.delta, 'text')
                                    else ""
                                )
                            },
                            "logprobs": None,
                            "finish_reason": None,
                        }
                    ],
                }
                yield f"data: {json.dumps(data)}\n\n"

            elif chunk.type == 'content_block_stop':
                data = {
                    "id": message_id,
                    "object": "chat.completion.chunk",
                    "created": int(time.time()),
                    "model": model,
                    "choices": [
                        {
                            "index": 0,
                            "delta": {},
                            "logprobs": None,
                            "finish_reason": "stop",
                        }
                    ],
                }
                yield f"data: {json.dumps(data)}\n\n"

        yield "data: [DONE]\n\n"

    return event_stream()


def send_message(model: str, messages: List[Dict[str, Any]]) -> Dict[str, Any]:
    """

    Send a message via the Anthropic provider without streaming.



    Args:

        model: The model identifier to use

        messages: List of messages to process



    Returns:

        dict: The formatted response from the model

    """
    client = get_anthropic_client()
    response = client.messages.create(
        model=model,
        max_tokens=1024,
        messages=messages
    )

    content = response.content[0].text if response.content else ""

    return {
        "id": response.id,
        "object": "chat.completion",
        "created": int(time.time()),
        "model": model,
        "choices": [
            {
                "index": 0,
                "message": {
                    "role": "assistant",
                    "content": content,
                },
                "logprobs": None,
                "finish_reason": "stop",
            }
        ],
    }


@app.post("/v1/chat/completions")
@app.post("/chat/completions")
async def generate_chat_completion(form_data: OpenAIChatCompletionForm):
    """

    Generate chat completions from the model.

    

    Args:

        form_data: The chat completion request parameters

        

    Returns:

        Union[StreamingResponse, dict]: Either a streaming response or a complete message

    """
    messages = [
        {"role": message.role, "content": message.content}
        for message in form_data.messages
    ]
    model = form_data.model

    def job():
        """Handle both streaming and non-streaming modes."""
        if form_data.stream:
            return StreamingResponse(
                stream_message(model=model, messages=messages),
                media_type="text/event-stream"
            )
        return send_message(model=model, messages=messages)

    with ThreadPoolExecutor() as executor:
        return await run_in_threadpool(job)


@app.post("/v1/{pipeline_id}/filter/inlet")
@app.post("/{pipeline_id}/filter/inlet")
async def filter_inlet(pipeline_id: str, form_data: FilterForm):
    """

    Handle inlet filtering for the pipeline.

    

    Args:

        pipeline_id: The ID of the pipeline

        form_data: The filter parameters

        

    Returns:

        dict: The processed request body

    """
    return form_data.body


@app.post("/v1/{pipeline_id}/filter/outlet")
@app.post("/{pipeline_id}/filter/outlet")
async def filter_outlet(pipeline_id: str, form_data: FilterForm):
    """

    Handle outlet filtering for the pipeline.

    

    Args:

        pipeline_id: The ID of the pipeline

        form_data: The filter parameters

        

    Returns:

        dict: The processed request body

    """
    return form_data.body