|
| 1 | +import json |
| 2 | +import logging |
| 3 | +import os |
| 4 | + |
| 5 | +import requests |
| 6 | +from fastapi import FastAPI, Form, Request |
| 7 | +from fastapi.responses import HTMLResponse |
| 8 | +from fastapi.staticfiles import StaticFiles |
| 9 | +from fastapi.responses import JSONResponse |
| 10 | + |
| 11 | +app = FastAPI() |
| 12 | +app.mount("/static", StaticFiles(directory="static"), name="static") |
| 13 | + |
| 14 | +# Configure basic logging |
| 15 | +logging.basicConfig(level=logging.INFO) |
| 16 | + |
| 17 | +default_openai_base_url = "https://api.openai.com/v1/" |
| 18 | + |
| 19 | +# Set the environment variables for the chat model |
| 20 | +LLM_URL = os.getenv("LLM_URL", default_openai_base_url) + "chat/completions" |
| 21 | +# Fallback to OpenAI Model if not set in environment |
| 22 | +MODEL_ID = os.getenv("LLM_MODEL", "gpt-4-turbo") |
| 23 | + |
| 24 | +# Get the API key for the LLM |
| 25 | +# For development, you can use your local API key. In production, the LLM gateway service will override the need for it. |
| 26 | +def get_api_key(): |
| 27 | + return os.getenv("OPENAI_API_KEY", "") |
| 28 | + |
| 29 | +# Home page form |
| 30 | +@app.get("/", response_class=HTMLResponse) |
| 31 | +async def home(): |
| 32 | + return """ |
| 33 | + <html> |
| 34 | + <head> |
| 35 | + <title>Ask the AI Model</title> |
| 36 | + <script type="text/javascript" src="./static/app.js"></script> |
| 37 | + </head> |
| 38 | + <body> |
| 39 | + <h1>Ask the AI Model</h1> |
| 40 | + <form method="post" id="askForm" onsubmit="event.preventDefault(); submitForm(event);"> |
| 41 | + <textarea id="prompt" name="prompt" autofocus="autofocus" rows="5" cols="60" placeholder="Enter your question here..." |
| 42 | + onkeydown="if(event.key==='Enter'&&!event.shiftKey){event.preventDefault();this.form.dispatchEvent(new Event('submit', {cancelable:true}));}"></textarea> |
| 43 | + <br><br> |
| 44 | + <input type="submit" value="Ask"> |
| 45 | + </form> |
| 46 | + <hr> |
| 47 | + <h2>Model's Reply:</h2> |
| 48 | + <p id="reply"></p> |
| 49 | + </body> |
| 50 | + </html> |
| 51 | + """ |
| 52 | + |
| 53 | +# Handle form submission |
| 54 | +@app.post("/ask", response_class=JSONResponse) |
| 55 | +async def ask(prompt: str = Form(...)): |
| 56 | + payload = { |
| 57 | + "model": MODEL_ID, |
| 58 | + "messages": [ |
| 59 | + {"role": "user", "content": prompt} |
| 60 | + ], |
| 61 | + "stream": False |
| 62 | + } |
| 63 | + |
| 64 | + reply = get_llm_response(payload) |
| 65 | + |
| 66 | + return {"prompt": prompt, "reply": reply} |
| 67 | + |
| 68 | +def get_llm_response(payload): |
| 69 | + api_key = get_api_key() |
| 70 | + request_headers = { |
| 71 | + "Content-Type": "application/json", |
| 72 | + "Authorization": f"Bearer {api_key}" |
| 73 | + } |
| 74 | + |
| 75 | + # Log request details |
| 76 | + logging.info(f"Sending POST to {LLM_URL}") |
| 77 | + logging.info(f"Request Headers: {request_headers}") |
| 78 | + logging.info(f"Request Payload: {payload}") |
| 79 | + |
| 80 | + response = None |
| 81 | + try: |
| 82 | + response = requests.post(f"{LLM_URL}", headers=request_headers, data=json.dumps(payload)) |
| 83 | + except requests.exceptions.HTTPError as errh: |
| 84 | + return f"HTTP error:", errh |
| 85 | + except requests.exceptions.ConnectionError as errc: |
| 86 | + return f"Connection error:", errc |
| 87 | + except requests.exceptions.Timeout as errt: |
| 88 | + return f"Timeout error:", errt |
| 89 | + except requests.exceptions.RequestException as err: |
| 90 | + return f"Unexpected error:", err |
| 91 | + |
| 92 | + if response is None: |
| 93 | + return f"Error: No response from server." |
| 94 | + if response.status_code == 400: |
| 95 | + return f"Connect Error: {response.status_code} - {response.text}" |
| 96 | + if response.status_code == 500: |
| 97 | + return f"Error from server: {response.status_code} - {response.text}" |
| 98 | + |
| 99 | + try: |
| 100 | + data = response.json() |
| 101 | + return data["choices"][0]["message"]["content"] |
| 102 | + except (KeyError, IndexError): |
| 103 | + return "Model returned an unexpected response." |
0 commit comments