ethiotech4848 commited on
Commit
974c992
Β·
verified Β·
1 Parent(s): 34311f1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +46 -58
app.py CHANGED
@@ -2,96 +2,84 @@ import os
2
  import json
3
  import httpx
4
  from fastapi import FastAPI, Request
5
-
6
  from openai import OpenAI
7
 
8
  app = FastAPI()
9
 
10
- # Load knowledge base
11
  with open("kb.json") as f:
12
  kb = json.load(f)
13
 
14
- # Prepare system prompt
15
  system_prompt = "You are a helpful assistant. Only answer questions based on the following knowledge base:\n\n"
16
- for question, answer in kb.items():
17
- system_prompt += f"Q: {question}\nA: {answer}\n\n"
18
- system_prompt += (
19
- "If the question is not in the knowledge base, respond with: "
20
- "'I'm not sure about that. I've transferred you to a human agent.'"
21
- )
22
 
23
- # OpenAI client
24
  client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
25
- client.base_url = os.getenv("OPENAI_API_BASE", "https://fast.typegpt.net/v1")
26
-
27
- # Track conversations transferred
28
- transferred_conversations = set()
29
 
30
- # Chatwoot configs
31
- CHATWOOT_BASE_URL = os.getenv("CHATWOOT_BASE_URL") # e.g., https://app.chatwoot.com
32
- CHATWOOT_API_TOKEN = os.getenv("CHATWOOT_API_TOKEN") # from profile
33
- CHATWOOT_AGENT_ID = os.getenv("CHATWOOT_AGENT_ID") # numeric ID of your agent
34
 
35
  @app.post("/ask")
36
  async def ask(request: Request):
37
  payload = await request.json()
 
38
 
39
- user_msg = payload.get("content") or payload.get("message") or ""
40
- conv_id = payload.get("conversation", {}).get("id")
41
- inbox_id = payload.get("conversation", {}).get("inbox_id")
42
 
43
- if not user_msg or not conv_id:
44
- return {"status": "ignored"}
 
45
 
46
- if str(conv_id) in transferred_conversations:
47
- return {"status": "already transferred"}
48
-
49
- # Compose OpenAI prompt
50
  messages = [
51
  {"role": "system", "content": system_prompt},
52
- {"role": "user", "content": user_msg},
53
  ]
54
 
55
  try:
56
  response = client.chat.completions.create(
57
  model="gpt-4o-mini",
58
  messages=messages,
59
- temperature=0.0,
60
  max_tokens=200,
61
  )
62
  answer = response.choices[0].message.content.strip()
 
63
  except Exception as e:
64
- print(f"OpenAI error: {e}")
65
  answer = "Sorry, I'm having trouble answering right now."
66
 
67
- # If fallback response, stop future replies
68
- if "transferred you to a human agent" in answer:
69
- transferred_conversations.add(str(conv_id))
70
-
71
- # Send reply using your agent
72
- await send_chatwoot_reply(
73
- conversation_id=conv_id,
74
- message=answer,
75
- agent_id=CHATWOOT_AGENT_ID,
76
- inbox_id=inbox_id
77
- )
78
-
79
- return {"status": "replied"}
80
-
81
-
82
- async def send_chatwoot_reply(conversation_id, message, agent_id, inbox_id):
83
- url = f"{CHATWOOT_BASE_URL}/api/v1/conversations/{conversation_id}/messages"
84
- headers = {
85
- "Content-Type": "application/json",
86
- "api_access_token": CHATWOOT_API_TOKEN
87
- }
88
- payload = {
89
- "content": message,
90
  "message_type": "outgoing",
91
  "private": False,
92
- "sender_type": "AgentBot",
93
- "sender_id": agent_id,
94
- "inbox_id": inbox_id
95
  }
96
- async with httpx.AsyncClient() as client:
97
- await client.post(url, json=payload, headers=headers)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  import json
3
  import httpx
4
  from fastapi import FastAPI, Request
 
5
  from openai import OpenAI
6
 
7
  app = FastAPI()
8
 
9
+ # Load KB
10
  with open("kb.json") as f:
11
  kb = json.load(f)
12
 
13
+ # Build system prompt
14
  system_prompt = "You are a helpful assistant. Only answer questions based on the following knowledge base:\n\n"
15
+ for q, a in kb.items():
16
+ system_prompt += f"Q: {q}\nA: {a}\n\n"
17
+ system_prompt += "If the question is not in the knowledge base, respond with: 'I'm not sure about that. Let me connect you with a human agent.'"
 
 
 
18
 
19
+ # OpenAI setup
20
  client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
21
+ client.base_url = os.getenv("OPENAI_API_BASE", "https://api.openai.com/v1")
 
 
 
22
 
23
+ # Chatwoot config
24
+ CHATWOOT_BASE_URL = os.getenv("CHATWOOT_BASE_URL") # e.g., https://app.chatwoot.com
25
+ CHATWOOT_API_KEY = os.getenv("CHATWOOT_API_KEY") # API Access Token of bot
26
+ BOT_AGENT_ID = os.getenv("BOT_AGENT_ID") # Agent ID (integer)
27
 
28
  @app.post("/ask")
29
  async def ask(request: Request):
30
  payload = await request.json()
31
+ print("πŸ“₯ Incoming payload:", json.dumps(payload, indent=2))
32
 
33
+ user_question = payload.get("message") or payload.get("content") or ""
34
+ conversation_id = payload.get("conversation", {}).get("id")
 
35
 
36
+ if not user_question or not conversation_id:
37
+ print("❌ Missing message or conversation ID")
38
+ return {"status": "invalid payload"}
39
 
 
 
 
 
40
  messages = [
41
  {"role": "system", "content": system_prompt},
42
+ {"role": "user", "content": user_question},
43
  ]
44
 
45
  try:
46
  response = client.chat.completions.create(
47
  model="gpt-4o-mini",
48
  messages=messages,
49
+ temperature=0,
50
  max_tokens=200,
51
  )
52
  answer = response.choices[0].message.content.strip()
53
+ print("βœ… OpenAI Answer:", answer)
54
  except Exception as e:
55
+ print("❌ OpenAI Error:", e)
56
  answer = "Sorry, I'm having trouble answering right now."
57
 
58
+ # Send answer back to Chatwoot conversation
59
+ message_payload = {
60
+ "content": answer,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  "message_type": "outgoing",
62
  "private": False,
63
+ "agent_id": int(BOT_AGENT_ID)
 
 
64
  }
65
+
66
+ try:
67
+ async with httpx.AsyncClient() as http:
68
+ chatwoot_url = f"{CHATWOOT_BASE_URL}/api/v1/conversations/{conversation_id}/messages"
69
+ print("πŸ“€ Sending to Chatwoot:", chatwoot_url)
70
+ print("πŸ“¦ Payload to Chatwoot:", json.dumps(message_payload, indent=2))
71
+
72
+ resp = await http.post(
73
+ chatwoot_url,
74
+ headers={
75
+ "Content-Type": "application/json",
76
+ "api_access_token": CHATWOOT_API_KEY,
77
+ },
78
+ json=message_payload,
79
+ )
80
+ print("πŸ“¬ Chatwoot Response:", resp.status_code, resp.text)
81
+
82
+ except Exception as e:
83
+ print("❌ Chatwoot Send Error:", e)
84
+
85
+ return {"status": "ok"}