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