1
- import os
2
1
import json
3
2
import logging
4
- from fastapi import FastAPI , Form , Request
5
- from fastapi . responses import HTMLResponse
3
+ import os
4
+
6
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
7
11
8
12
app = FastAPI ()
13
+ app .mount ("/static" , StaticFiles (directory = "static" ), name = "static" )
9
14
10
15
# Configure basic logging
11
16
logging .basicConfig (level = logging .INFO )
12
17
18
+ default_openai_base_url = "https://api.openai.com/v1/"
19
+
13
20
# Set the environment variables for the chat model
14
- ENDPOINT_URL = os .getenv ("ENDPOINT_URL " , "https://api.openai.com/v1/ chat/completions")
21
+ LLM_URL = os .getenv ("LLM_URL " , default_openai_base_url ) + " chat/completions"
15
22
# Fallback to OpenAI Model if not set in environment
16
- MODEL_ID = os .getenv ("MODEL " , "gpt-4-turbo" )
23
+ MODEL_ID = os .getenv ("LLM_MODEL " , "gpt-4-turbo" )
17
24
18
25
# Get the API key for the LLM
19
26
# For development, you can use your local API key. In production, the LLM gateway service will override the need for it.
20
27
def get_api_key ():
21
- return os .getenv ("OPENAI_API_KEY" , "API key not set " )
28
+ return os .getenv ("OPENAI_API_KEY" , "" )
22
29
23
30
# Home page form
24
31
@app .get ("/" , response_class = HTMLResponse )
25
32
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
- """
33
+ return FileResponse ("static/index.html" , media_type = "text/html" )
42
34
43
35
# Handle form submission
44
- @app .post ("/ask" , response_class = HTMLResponse )
36
+ @app .post ("/ask" , response_class = JSONResponse )
45
37
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
38
payload = {
54
39
"model" : MODEL_ID ,
55
40
"messages" : [
@@ -58,59 +43,43 @@ async def ask(prompt: str = Form(...)):
58
43
"stream" : False
59
44
}
60
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
+
61
57
# Log request details
62
- logging .info (f"Sending POST to { ENDPOINT_URL } " )
63
- logging .info (f"Request Headers: { headers } " )
58
+ logging .info (f"Sending POST to { LLM_URL } " )
59
+ logging .info (f"Request Headers: { request_headers } " )
64
60
logging .info (f"Request Payload: { payload } " )
65
61
66
62
response = None
67
- reply = None
68
63
try :
69
- response = requests .post (f"{ ENDPOINT_URL } " , headers = headers , data = json .dumps (payload ))
64
+ response = requests .post (f"{ LLM_URL } " , headers = request_headers , data = json .dumps (payload ))
70
65
except requests .exceptions .HTTPError as errh :
71
- reply = f"HTTP error:" , errh
66
+ return f"HTTP error:" , errh
72
67
except requests .exceptions .ConnectionError as errc :
73
- reply = f"Connection error:" , errc
68
+ return f"Connection error:" , errc
74
69
except requests .exceptions .Timeout as errt :
75
- reply = f"Timeout error:" , errt
70
+ return f"Timeout error:" , errt
76
71
except requests .exceptions .RequestException as err :
77
- reply = f"Unexpected error:" , err
72
+ return f"Unexpected error:" , err
78
73
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 } " )
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 } "
97
80
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
- """
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