Spaces:
Sleeping
Sleeping
Add interface and update pyproject.toml for new deeps
Browse files
app.py → interfaces/chainlit/app.py
RENAMED
File without changes
|
interfaces/whatsapp/webhook_endpoint.py
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from fastapi import FastAPI
|
2 |
+
from ai_companion.interfaces.whatsapp.whatsapp_response import whatsapp_router
|
3 |
+
|
4 |
+
app = FastAPI()
|
5 |
+
app.include_router(whatsapp_router)
|
interfaces/whatsapp/whatsapp_response.py
ADDED
@@ -0,0 +1,169 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import logging
|
2 |
+
import os
|
3 |
+
from io import BytesIO
|
4 |
+
from typing import Dict
|
5 |
+
|
6 |
+
import httpx
|
7 |
+
from fastapi import APIRouter, Request, Response
|
8 |
+
from langchain_core.messages import HumanMessage
|
9 |
+
from langgraph.checkpoint.sqlite.aio import AsyncSqliteSaver
|
10 |
+
|
11 |
+
from agent import create_agent_graph
|
12 |
+
from agent.utils.state import AgentState
|
13 |
+
|
14 |
+
logger = logging.getLogger(__name__)
|
15 |
+
|
16 |
+
# Global module instances
|
17 |
+
speech_to_text = SpeechToText()
|
18 |
+
text_to_speech = TextToSpeech()
|
19 |
+
image_to_text = ImageToText()
|
20 |
+
|
21 |
+
# Router for WhatsApp respo
|
22 |
+
whatsapp_router = APIRouter()
|
23 |
+
|
24 |
+
# WhatsApp API credentials
|
25 |
+
WHATSAPP_TOKEN = os.getenv("WHATSAPP_TOKEN")
|
26 |
+
WHATSAPP_PHONE_NUMBER_ID = os.getenv("WHATSAPP_PHONE_NUMBER_ID")
|
27 |
+
|
28 |
+
|
29 |
+
@whatsapp_router.api_route("/whatsapp_response", methods=["GET", "POST"])
|
30 |
+
async def whatsapp_handler(request: Request) -> Response:
|
31 |
+
"""Handles incoming messages and status updates from the WhatsApp Cloud API."""
|
32 |
+
|
33 |
+
if request.method == "GET":
|
34 |
+
params = request.query_params
|
35 |
+
if params.get("hub.verify_token") == os.getenv("WHATSAPP_VERIFY_TOKEN"):
|
36 |
+
return Response(content=params.get("hub.challenge"), status_code=200)
|
37 |
+
return Response(content="Verification token mismatch", status_code=403)
|
38 |
+
|
39 |
+
try:
|
40 |
+
data = await request.json()
|
41 |
+
change_value = data["entry"][0]["changes"][0]["value"]
|
42 |
+
if "messages" in change_value:
|
43 |
+
message = change_value["messages"][0]
|
44 |
+
from_number = message["from"]
|
45 |
+
session_id = from_number
|
46 |
+
|
47 |
+
# Get user message (text only for now)
|
48 |
+
if message["type"] != "text":
|
49 |
+
await send_response(from_number, "Sorry, I can only process text messages at the moment.")
|
50 |
+
return Response(content="Non-text message received", status_code=200)
|
51 |
+
|
52 |
+
content = message["text"]["body"]
|
53 |
+
|
54 |
+
# Process message through the graph agent
|
55 |
+
async with AsyncSqliteSaver.from_conn_string("data/short_term.db") as short_term_memory:
|
56 |
+
graph = await create_agent_graph(short_term_memory)
|
57 |
+
current_state = AgentState(
|
58 |
+
messages=[HumanMessage(content=content)],
|
59 |
+
context=[]
|
60 |
+
)
|
61 |
+
|
62 |
+
# Get the response from the graph
|
63 |
+
output_state = await graph.ainvoke(
|
64 |
+
current_state,
|
65 |
+
{"configurable": {"thread_id": session_id}},
|
66 |
+
)
|
67 |
+
|
68 |
+
response_message = output_state["messages"][-1].content
|
69 |
+
success = await send_response(from_number, response_message)
|
70 |
+
|
71 |
+
if not success:
|
72 |
+
return Response(content="Failed to send message", status_code=500)
|
73 |
+
|
74 |
+
return Response(content="Message processed", status_code=200)
|
75 |
+
|
76 |
+
elif "statuses" in change_value:
|
77 |
+
return Response(content="Status update received", status_code=200)
|
78 |
+
|
79 |
+
else:
|
80 |
+
return Response(content="Unknown event type", status_code=400)
|
81 |
+
|
82 |
+
except Exception as e:
|
83 |
+
logger.error(f"Error processing message: {e}", exc_info=True)
|
84 |
+
return Response(content="Internal server error", status_code=500)
|
85 |
+
|
86 |
+
|
87 |
+
async def download_media(media_id: str) -> bytes:
|
88 |
+
"""Download media from WhatsApp."""
|
89 |
+
media_metadata_url = f"https://graph.facebook.com/v21.0/{media_id}"
|
90 |
+
headers = {"Authorization": f"Bearer {WHATSAPP_TOKEN}"}
|
91 |
+
|
92 |
+
async with httpx.AsyncClient() as client:
|
93 |
+
metadata_response = await client.get(media_metadata_url, headers=headers)
|
94 |
+
metadata_response.raise_for_status()
|
95 |
+
metadata = metadata_response.json()
|
96 |
+
download_url = metadata.get("url")
|
97 |
+
|
98 |
+
media_response = await client.get(download_url, headers=headers)
|
99 |
+
media_response.raise_for_status()
|
100 |
+
return media_response.content
|
101 |
+
|
102 |
+
|
103 |
+
async def process_audio_message(message: Dict) -> str:
|
104 |
+
"""Download and transcribe audio message."""
|
105 |
+
audio_id = message["audio"]["id"]
|
106 |
+
media_metadata_url = f"https://graph.facebook.com/v21.0/{audio_id}"
|
107 |
+
headers = {"Authorization": f"Bearer {WHATSAPP_TOKEN}"}
|
108 |
+
|
109 |
+
async with httpx.AsyncClient() as client:
|
110 |
+
metadata_response = await client.get(media_metadata_url, headers=headers)
|
111 |
+
metadata_response.raise_for_status()
|
112 |
+
metadata = metadata_response.json()
|
113 |
+
download_url = metadata.get("url")
|
114 |
+
|
115 |
+
# Download the audio file
|
116 |
+
async with httpx.AsyncClient() as client:
|
117 |
+
audio_response = await client.get(download_url, headers=headers)
|
118 |
+
audio_response.raise_for_status()
|
119 |
+
|
120 |
+
# Prepare for transcription
|
121 |
+
audio_buffer = BytesIO(audio_response.content)
|
122 |
+
audio_buffer.seek(0)
|
123 |
+
audio_data = audio_buffer.read()
|
124 |
+
|
125 |
+
return await speech_to_text.transcribe(audio_data)
|
126 |
+
|
127 |
+
|
128 |
+
async def send_response(from_number: str, response_text: str) -> bool:
|
129 |
+
"""Send text response to user via WhatsApp API."""
|
130 |
+
headers = {
|
131 |
+
"Authorization": f"Bearer {WHATSAPP_TOKEN}",
|
132 |
+
"Content-Type": "application/json",
|
133 |
+
}
|
134 |
+
|
135 |
+
json_data = {
|
136 |
+
"messaging_product": "whatsapp",
|
137 |
+
"to": from_number,
|
138 |
+
"type": "text",
|
139 |
+
"text": {"body": response_text},
|
140 |
+
}
|
141 |
+
|
142 |
+
async with httpx.AsyncClient() as client:
|
143 |
+
response = await client.post(
|
144 |
+
f"https://graph.facebook.com/v21.0/{WHATSAPP_PHONE_NUMBER_ID}/messages",
|
145 |
+
headers=headers,
|
146 |
+
json=json_data,
|
147 |
+
)
|
148 |
+
|
149 |
+
return response.status_code == 200
|
150 |
+
|
151 |
+
|
152 |
+
async def upload_media(media_content: BytesIO, mime_type: str) -> str:
|
153 |
+
"""Upload media to WhatsApp servers."""
|
154 |
+
headers = {"Authorization": f"Bearer {WHATSAPP_TOKEN}"}
|
155 |
+
files = {"file": ("response.mp3", media_content, mime_type)}
|
156 |
+
data = {"messaging_product": "whatsapp", "type": mime_type}
|
157 |
+
|
158 |
+
async with httpx.AsyncClient() as client:
|
159 |
+
response = await client.post(
|
160 |
+
f"https://graph.facebook.com/v21.0/{WHATSAPP_PHONE_NUMBER_ID}/media",
|
161 |
+
headers=headers,
|
162 |
+
files=files,
|
163 |
+
data=data,
|
164 |
+
)
|
165 |
+
result = response.json()
|
166 |
+
|
167 |
+
if "id" not in result:
|
168 |
+
raise Exception("Failed to upload media")
|
169 |
+
return result["id"]
|
pyproject.toml
CHANGED
@@ -1,29 +1,31 @@
|
|
1 |
[project]
|
2 |
-
name = "
|
3 |
version = "0.1.0"
|
4 |
-
description = "
|
5 |
readme = "README.md"
|
6 |
-
requires-python = ">=3.
|
7 |
dependencies = [
|
8 |
-
"chainlit>=
|
9 |
-
"
|
10 |
-
"
|
11 |
-
"
|
12 |
-
"
|
13 |
-
"
|
14 |
-
"
|
15 |
-
"
|
16 |
-
"
|
17 |
-
"langchain-core>=0.1.23",
|
18 |
-
"langchain-community>=0.0.19",
|
19 |
-
"langchain-qdrant>=0.2.0",
|
20 |
-
"langgraph-checkpoint-duckdb>=2.0.1",
|
21 |
"langgraph-checkpoint-sqlite>=2.0.1",
|
22 |
-
"duckdb>=1.1.3",
|
23 |
"aiosqlite>=0.20.0",
|
24 |
-
"
|
25 |
-
"
|
26 |
-
"
|
27 |
-
"
|
28 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
29 |
]
|
|
|
1 |
[project]
|
2 |
+
name = "chief-joy-officer"
|
3 |
version = "0.1.0"
|
4 |
+
description = "AI-powered Chief Joy Officer for social activity recommendations"
|
5 |
readme = "README.md"
|
6 |
+
requires-python = ">=3.12"
|
7 |
dependencies = [
|
8 |
+
"chainlit>=1.3.2",
|
9 |
+
"fastapi[standard]>=0.115.6",
|
10 |
+
"httpx>=0.27.0",
|
11 |
+
"langchain>=0.3.13",
|
12 |
+
"langchain-community>=0.3.13",
|
13 |
+
"langchain-core>=0.1.27",
|
14 |
+
"langgraph>=0.2.60",
|
15 |
+
"langchain-openai>=0.2.14",
|
16 |
+
"pydantic>=2.10.0",
|
|
|
|
|
|
|
|
|
17 |
"langgraph-checkpoint-sqlite>=2.0.1",
|
|
|
18 |
"aiosqlite>=0.20.0",
|
19 |
+
"python-dotenv>=1.0.1",
|
20 |
+
"elevenlabs>=1.50.3",
|
21 |
+
"groq>=0.13.1",
|
22 |
+
"langchain-groq>=0.2.2",
|
23 |
+
"pydantic-settings>=2.7.0",
|
24 |
+
"pre-commit>=4.0.1",
|
25 |
+
"supabase>=2.11.0",
|
26 |
+
"langgraph-checkpoint-duckdb>=2.0.1",
|
27 |
+
"duckdb>=1.1.3",
|
28 |
+
"qdrant-client>=1.12.1",
|
29 |
+
"sentence-transformers>=3.3.1",
|
30 |
+
"together>=1.3.10"
|
31 |
]
|