|
| 1 | +import math |
| 2 | +import time |
| 3 | +import os |
| 4 | +import requests |
| 5 | +from typing import List, Optional |
| 6 | + |
| 7 | +import uvicorn |
| 8 | +from fastapi import FastAPI, HTTPException |
| 9 | +from pydantic import BaseModel |
| 10 | + |
| 11 | +app = FastAPI() |
| 12 | + |
| 13 | +# Configuration |
| 14 | +MODEL = os.getenv("MODEL", "Qwen/Qwen2-0.5B-Instruct") |
| 15 | +SERVED_MODEL_NAME = os.getenv("SERVED_MODEL_NAME", MODEL) |
| 16 | +LLM_KATAN_URL = os.getenv("LLM_KATAN_URL", "http://localhost:8001") |
| 17 | + |
| 18 | +# Check if HuggingFace token is set |
| 19 | +hf_token = os.getenv("HUGGINGFACE_HUB_TOKEN") |
| 20 | +if not hf_token: |
| 21 | + print("Warning: HUGGINGFACE_HUB_TOKEN not set. Some models may require authentication.") |
| 22 | + |
| 23 | + |
| 24 | +class ChatMessage(BaseModel): |
| 25 | + role: str |
| 26 | + content: str |
| 27 | + |
| 28 | + |
| 29 | +class ChatRequest(BaseModel): |
| 30 | + model: str |
| 31 | + messages: List[ChatMessage] |
| 32 | + temperature: Optional[float] = 0.2 |
| 33 | + max_tokens: Optional[int] = None |
| 34 | + |
| 35 | + |
| 36 | +@app.get("/health") |
| 37 | +async def health(): |
| 38 | + return {"status": "ok"} |
| 39 | + |
| 40 | + |
| 41 | +@app.get("/v1/models") |
| 42 | +async def models(): |
| 43 | + return {"data": [{"id": SERVED_MODEL_NAME, "object": "model"}]} |
| 44 | + |
| 45 | + |
| 46 | +@app.post("/v1/chat/completions") |
| 47 | +async def chat_completions(req: ChatRequest): |
| 48 | + try: |
| 49 | + # Forward request to llm-katan backend |
| 50 | + llm_katan_request = { |
| 51 | + "model": MODEL, |
| 52 | + "messages": [{"role": msg.role, "content": msg.content} for msg in req.messages], |
| 53 | + "temperature": req.temperature, |
| 54 | + } |
| 55 | + |
| 56 | + if req.max_tokens: |
| 57 | + llm_katan_request["max_tokens"] = req.max_tokens |
| 58 | + |
| 59 | + # Make request to llm-katan |
| 60 | + response = requests.post( |
| 61 | + f"{LLM_KATAN_URL}/v1/chat/completions", |
| 62 | + json=llm_katan_request, |
| 63 | + timeout=30 |
| 64 | + ) |
| 65 | + |
| 66 | + if response.status_code != 200: |
| 67 | + raise HTTPException( |
| 68 | + status_code=response.status_code, |
| 69 | + detail=f"LLM Katan error: {response.text}" |
| 70 | + ) |
| 71 | + |
| 72 | + result = response.json() |
| 73 | + |
| 74 | + # Update the model name in response to match our served model name |
| 75 | + result["model"] = req.model |
| 76 | + |
| 77 | + return result |
| 78 | + |
| 79 | + except requests.exceptions.RequestException as e: |
| 80 | + # Fallback to simple echo behavior if llm-katan is not available |
| 81 | + print(f"Warning: LLM Katan not available ({e}), using fallback response") |
| 82 | + |
| 83 | + # Simple echo-like behavior as fallback |
| 84 | + last_user = next( |
| 85 | + (m.content for m in reversed(req.messages) if m.role == "user"), "" |
| 86 | + ) |
| 87 | + content = f"[katan-{req.model}] You said: {last_user}" |
| 88 | + |
| 89 | + # Rough token estimation: ~1 token per 4 characters (ceil) |
| 90 | + def estimate_tokens(text: str) -> int: |
| 91 | + if not text: |
| 92 | + return 0 |
| 93 | + return max(1, math.ceil(len(text) / 4)) |
| 94 | + |
| 95 | + prompt_text = "\n".join( |
| 96 | + m.content for m in req.messages if isinstance(m.content, str) |
| 97 | + ) |
| 98 | + prompt_tokens = estimate_tokens(prompt_text) |
| 99 | + completion_tokens = estimate_tokens(content) |
| 100 | + total_tokens = prompt_tokens + completion_tokens |
| 101 | + |
| 102 | + created_ts = int(time.time()) |
| 103 | + |
| 104 | + usage = { |
| 105 | + "prompt_tokens": prompt_tokens, |
| 106 | + "completion_tokens": completion_tokens, |
| 107 | + "total_tokens": total_tokens, |
| 108 | + "prompt_tokens_details": {"cached_tokens": 0}, |
| 109 | + "completion_tokens_details": {"reasoning_tokens": 0}, |
| 110 | + } |
| 111 | + |
| 112 | + return { |
| 113 | + "id": "cmpl-katan-123", |
| 114 | + "object": "chat.completion", |
| 115 | + "created": created_ts, |
| 116 | + "model": req.model, |
| 117 | + "system_fingerprint": "llm-katan-server", |
| 118 | + "choices": [ |
| 119 | + { |
| 120 | + "index": 0, |
| 121 | + "message": {"role": "assistant", "content": content}, |
| 122 | + "finish_reason": "stop", |
| 123 | + "logprobs": None, |
| 124 | + } |
| 125 | + ], |
| 126 | + "usage": usage, |
| 127 | + "token_usage": usage, |
| 128 | + } |
| 129 | + |
| 130 | + |
| 131 | +if __name__ == "__main__": |
| 132 | + uvicorn.run(app, host="0.0.0.0", port=8000) |
0 commit comments