zenaight commited on
Commit
fdeebb1
·
1 Parent(s): d1fcb7b
Files changed (2) hide show
  1. main.py +92 -3
  2. requirements.txt +2 -1
main.py CHANGED
@@ -2,12 +2,33 @@ import os
2
  from fastapi import FastAPI, Request, HTTPException, Query
3
  from fastapi.responses import PlainTextResponse, JSONResponse
4
  import httpx
 
 
 
5
 
6
  app = FastAPI()
7
 
8
  VERIFY_TOKEN = os.getenv("VERIFY_TOKEN", "")
9
  PHONE_NUMBER_ID = os.getenv("PHONE_NUMBER_ID", "")
10
  WHATSAPP_API_TOKEN = os.getenv("WHATSAPP_API_TOKEN", "")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
  @app.get("/webhook")
13
  def verify_webhook(
@@ -35,8 +56,14 @@ async def receive_message(req: Request):
35
  msg = messages[0]
36
 
37
  if msg.get("type") == "text":
38
- reply_text = "Hello 👋 from PropAgent Git!"
39
- await send_whatsapp_message(wa_id, reply_text)
 
 
 
 
 
 
40
  return JSONResponse({"status": "replied"})
41
 
42
  except Exception as e:
@@ -45,6 +72,58 @@ async def receive_message(req: Request):
45
 
46
  return JSONResponse({"status": "ignored"})
47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
  async def send_whatsapp_message(wa_id: str, message: str):
49
  url = f"https://graph.facebook.com/v18.0/{PHONE_NUMBER_ID}/messages"
50
  headers = {
@@ -65,4 +144,14 @@ async def send_whatsapp_message(wa_id: str, message: str):
65
 
66
  @app.get("/ping")
67
  def ping():
68
- return {"pong": True}
 
 
 
 
 
 
 
 
 
 
 
2
  from fastapi import FastAPI, Request, HTTPException, Query
3
  from fastapi.responses import PlainTextResponse, JSONResponse
4
  import httpx
5
+ from openai import OpenAI
6
+ from pydantic import BaseModel
7
+ from typing import Optional
8
 
9
  app = FastAPI()
10
 
11
  VERIFY_TOKEN = os.getenv("VERIFY_TOKEN", "")
12
  PHONE_NUMBER_ID = os.getenv("PHONE_NUMBER_ID", "")
13
  WHATSAPP_API_TOKEN = os.getenv("WHATSAPP_API_TOKEN", "")
14
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "")
15
+
16
+ # Initialize OpenAI client
17
+ openai_client = None
18
+ if OPENAI_API_KEY:
19
+ openai_client = OpenAI(api_key=OPENAI_API_KEY)
20
+
21
+ # Pydantic model for chat requests
22
+ class ChatRequest(BaseModel):
23
+ message: str
24
+ model: Optional[str] = "gpt-3.5-turbo" # Using the cheapest OpenAI model
25
+ max_tokens: Optional[int] = 150
26
+
27
+ # Pydantic model for chat responses
28
+ class ChatResponse(BaseModel):
29
+ response: str
30
+ model: str
31
+ tokens_used: Optional[int] = None
32
 
33
  @app.get("/webhook")
34
  def verify_webhook(
 
56
  msg = messages[0]
57
 
58
  if msg.get("type") == "text":
59
+ # Get the user's message
60
+ user_message = msg.get("text", {}).get("body", "")
61
+
62
+ # Generate AI response using OpenAI
63
+ ai_response = await generate_ai_response(user_message)
64
+
65
+ # Send the AI response back to WhatsApp
66
+ await send_whatsapp_message(wa_id, ai_response)
67
  return JSONResponse({"status": "replied"})
68
 
69
  except Exception as e:
 
72
 
73
  return JSONResponse({"status": "ignored"})
74
 
75
+ async def generate_ai_response(user_message: str) -> str:
76
+ """Generate AI response using OpenAI API"""
77
+ if not openai_client:
78
+ return "Sorry, AI chat is not available. Please check your OpenAI API key configuration."
79
+
80
+ try:
81
+ response = openai_client.chat.completions.create(
82
+ model="gpt-3.5-turbo",
83
+ messages=[
84
+ {"role": "system", "content": "You are a helpful assistant. Keep your responses concise and friendly."},
85
+ {"role": "user", "content": user_message}
86
+ ],
87
+ max_tokens=150,
88
+ temperature=0.7
89
+ )
90
+
91
+ ai_response = response.choices[0].message.content
92
+ return ai_response if ai_response else "I'm sorry, I couldn't generate a response."
93
+
94
+ except Exception as e:
95
+ print(f"Error generating AI response: {e}")
96
+ return "Sorry, I'm having trouble processing your request right now."
97
+
98
+ @app.post("/chat", response_model=ChatResponse)
99
+ async def chat_with_ai(request: ChatRequest):
100
+ """Basic chat endpoint for direct API calls"""
101
+ if not openai_client:
102
+ raise HTTPException(status_code=500, detail="OpenAI API key not configured")
103
+
104
+ try:
105
+ response = openai_client.chat.completions.create(
106
+ model=request.model,
107
+ messages=[
108
+ {"role": "system", "content": "You are a helpful assistant. Keep your responses concise and friendly."},
109
+ {"role": "user", "content": request.message}
110
+ ],
111
+ max_tokens=request.max_tokens,
112
+ temperature=0.7
113
+ )
114
+
115
+ ai_response = response.choices[0].message.content
116
+ usage = response.usage
117
+
118
+ return ChatResponse(
119
+ response=ai_response,
120
+ model=request.model,
121
+ tokens_used=usage.total_tokens if usage else None
122
+ )
123
+
124
+ except Exception as e:
125
+ raise HTTPException(status_code=500, detail=f"Error generating response: {str(e)}")
126
+
127
  async def send_whatsapp_message(wa_id: str, message: str):
128
  url = f"https://graph.facebook.com/v18.0/{PHONE_NUMBER_ID}/messages"
129
  headers = {
 
144
 
145
  @app.get("/ping")
146
  def ping():
147
+ return {"pong": True}
148
+
149
+ @app.get("/health")
150
+ def health_check():
151
+ """Health check endpoint to verify API connectivity"""
152
+ status = {
153
+ "api": "healthy",
154
+ "whatsapp": "configured" if WHATSAPP_API_TOKEN else "not configured",
155
+ "openai": "configured" if OPENAI_API_KEY else "not configured"
156
+ }
157
+ return status
requirements.txt CHANGED
@@ -1,4 +1,5 @@
1
  fastapi
2
  uvicorn
3
  python-dotenv
4
- httpx
 
 
1
  fastapi
2
  uvicorn
3
  python-dotenv
4
+ httpx
5
+ openai