ethiotech4848 commited on
Commit
c593623
·
verified ·
1 Parent(s): 4a7b225

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -0
app.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import openai
4
+ from fastapi import FastAPI, Request
5
+
6
+ app = FastAPI()
7
+
8
+ # Load knowledge base
9
+ with open("kb.json") as f:
10
+ kb = json.load(f)
11
+
12
+ system_prompt = "You are a helpful assistant. Only answer questions based on the following knowledge base:\n\n"
13
+ for question, answer in kb.items():
14
+ system_prompt += f"Q: {question}\nA: {answer}\n\n"
15
+ system_prompt += (
16
+ "If the question is not in the knowledge base, respond with: "
17
+ "'I'm not sure about that. Let me connect you with a human agent.'"
18
+ )
19
+
20
+ openai.api_key = os.getenv("OPENAI_API_KEY")
21
+ openai.api_base = os.getenv("OPENAI_API_BASE", "https://fast.typegpt.net/v1")
22
+
23
+ @app.post("/ask")
24
+ async def ask(request: Request):
25
+ data = await request.json()
26
+ user_question = data.get("content") or data.get("message") or ""
27
+
28
+ if not user_question:
29
+ return {"reply": "Please ask a question."}
30
+
31
+ messages = [
32
+ {"role": "system", "content": system_prompt},
33
+ {"role": "user", "content": user_question},
34
+ ]
35
+
36
+ try:
37
+ response = openai.ChatCompletion.create(
38
+ model="gpt-4o-mini",
39
+ messages=messages,
40
+ temperature=0.0,
41
+ max_tokens=200,
42
+ )
43
+ answer = response.choices[0].message.content.strip()
44
+ except Exception as e:
45
+ print(f"Error calling OpenAI: {e}")
46
+ answer = "Sorry, I'm having trouble answering right now."
47
+
48
+ return {"reply": answer}