|
| 1 | +import json |
| 2 | +import logging |
| 3 | +import os |
| 4 | + |
| 5 | +import requests |
| 6 | +from fastapi import FastAPI, Form |
| 7 | +from fastapi.responses import HTMLResponse |
| 8 | +from fastapi.staticfiles import StaticFiles |
| 9 | +from fastapi.responses import JSONResponse |
| 10 | +from fastapi.responses import FileResponse |
| 11 | + |
| 12 | +app = FastAPI() |
| 13 | +app.mount("/static", StaticFiles(directory="static"), name="static") |
| 14 | + |
| 15 | +# Configure basic logging |
| 16 | +logging.basicConfig(level=logging.INFO) |
| 17 | + |
| 18 | +default_openai_base_url = "https://api.openai.com/v1/" |
| 19 | + |
| 20 | +# Set the environment variables for the chat model |
| 21 | +LLM_URL = os.getenv("LLM_URL", default_openai_base_url) + "chat/completions" |
| 22 | +# Fallback to OpenAI Model if not set in environment |
| 23 | +MODEL_ID = os.getenv("LLM_MODEL", "gpt-4-turbo") |
| 24 | + |
| 25 | +# Get the API key for the LLM |
| 26 | +# For development, you have the option to use your local API key. In production, the LLM gateway service will override the need for it. |
| 27 | +def get_api_key(): |
| 28 | + return os.getenv("OPENAI_API_KEY", "") |
| 29 | + |
| 30 | +# Home page form |
| 31 | +@app.get("/", response_class=HTMLResponse) |
| 32 | +async def home(): |
| 33 | + return FileResponse("static/index.html", media_type="text/html") |
| 34 | + |
| 35 | +# Handle form submission |
| 36 | +@app.post("/ask", response_class=JSONResponse) |
| 37 | +async def ask(prompt: str = Form(...)): |
| 38 | + payload = { |
| 39 | + "model": MODEL_ID, |
| 40 | + "messages": [ |
| 41 | + {"role": "user", "content": prompt} |
| 42 | + ], |
| 43 | + "stream": False |
| 44 | + } |
| 45 | + |
| 46 | + reply = get_llm_response(payload) |
| 47 | + |
| 48 | + return {"prompt": prompt, "reply": reply} |
| 49 | + |
| 50 | +def get_llm_response(payload): |
| 51 | + api_key = get_api_key() |
| 52 | + request_headers = { |
| 53 | + "Content-Type": "application/json", |
| 54 | + "Authorization": f"Bearer {api_key}" |
| 55 | + } |
| 56 | + |
| 57 | + # Log request details |
| 58 | + logging.info(f"Sending POST to {LLM_URL}") |
| 59 | + logging.info(f"Request Headers: {request_headers}") |
| 60 | + logging.info(f"Request Payload: {payload}") |
| 61 | + |
| 62 | + response = None |
| 63 | + try: |
| 64 | + response = requests.post(f"{LLM_URL}", headers=request_headers, data=json.dumps(payload)) |
| 65 | + except requests.exceptions.HTTPError as errh: |
| 66 | + return f"HTTP error:", errh |
| 67 | + except requests.exceptions.ConnectionError as errc: |
| 68 | + return f"Connection error:", errc |
| 69 | + except requests.exceptions.Timeout as errt: |
| 70 | + return f"Timeout error:", errt |
| 71 | + except requests.exceptions.RequestException as err: |
| 72 | + return f"Unexpected error:", err |
| 73 | + |
| 74 | + if response is None: |
| 75 | + return f"Error: No response from server." |
| 76 | + if response.status_code == 400: |
| 77 | + return f"Connect Error: {response.status_code} - {response.text}" |
| 78 | + if response.status_code == 500: |
| 79 | + return f"Error from server: {response.status_code} - {response.text}" |
| 80 | + |
| 81 | + try: |
| 82 | + data = response.json() |
| 83 | + return data["choices"][0]["message"]["content"] |
| 84 | + except (KeyError, IndexError): |
| 85 | + return "Model returned an unexpected response." |
0 commit comments