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