Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -99,18 +99,50 @@ async def ask(request: Request):
|
|
99 |
)
|
100 |
answer = response.choices[0].message.content.strip()
|
101 |
print("β
GPT Answer:", answer)
|
102 |
-
except Exception as e:
|
103 |
-
print("β OpenAI Error:", e)
|
104 |
-
answer = "Sorry, I'm having trouble answering right now."
|
105 |
-
|
106 |
-
if answer == "I'm not sure about that. Let me connect you with a human agent.":
|
107 |
-
stop_reply_conversations.add(conversation_id)
|
108 |
-
print(f"π« Fallback answer, disabling AI for conversation {conversation_id}")
|
109 |
|
110 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
111 |
|
112 |
return {"status": "ok"}
|
113 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
114 |
|
115 |
async def send_chatwoot_message(conversation_id: str, content: str):
|
116 |
message_payload = {
|
|
|
99 |
)
|
100 |
answer = response.choices[0].message.content.strip()
|
101 |
print("β
GPT Answer:", answer)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
102 |
|
103 |
+
# β
Extract and send token usage to Slack
|
104 |
+
usage = response.usage
|
105 |
+
if usage:
|
106 |
+
prompt_tokens = usage.prompt_tokens
|
107 |
+
completion_tokens = usage.completion_tokens
|
108 |
+
total_tokens = usage.total_tokens
|
109 |
+
|
110 |
+
slack_msg = (
|
111 |
+
f"π Token usage for conversation `{conversation_id}`:\n"
|
112 |
+
f"> Prompt: {prompt_tokens} tokens\n"
|
113 |
+
f"> Completion: {completion_tokens} tokens\n"
|
114 |
+
f"> Total: {total_tokens} tokens"
|
115 |
+
)
|
116 |
+
await send_to_slack(slack_msg)
|
117 |
+
else:
|
118 |
+
print("β οΈ No token usage info returned from API")
|
119 |
+
|
120 |
+
except Exception as e:
|
121 |
+
print("β OpenAI Error:", e)
|
122 |
+
answer = "Sorry, I'm having trouble answering right now."
|
123 |
+
|
124 |
+
if answer == "I'm not sure about that. Let me connect you with a human agent.":
|
125 |
+
stop_reply_conversations.add(conversation_id)
|
126 |
+
print(f"π« Fallback answer, disabling AI for conversation {conversation_id}")
|
127 |
+
|
128 |
+
await send_chatwoot_message(conversation_id, answer)
|
129 |
|
130 |
return {"status": "ok"}
|
131 |
|
132 |
+
async def send_to_slack(message: str):
|
133 |
+
webhook_url = os.getenv("SLACK_WEBHOOK_URL")
|
134 |
+
if not webhook_url:
|
135 |
+
print("β SLACK_WEBHOOK_URL not set")
|
136 |
+
return
|
137 |
+
|
138 |
+
payload = {"text": message}
|
139 |
+
|
140 |
+
try:
|
141 |
+
async with httpx.AsyncClient() as http:
|
142 |
+
resp = await http.post(webhook_url, json=payload)
|
143 |
+
print("π¨ Slack response:", resp.status_code, resp.text)
|
144 |
+
except Exception as e:
|
145 |
+
print("β Slack Send Error:", e)
|
146 |
|
147 |
async def send_chatwoot_message(conversation_id: str, content: str):
|
148 |
message_payload = {
|