Skip to content

Commit

Permalink
fix lead serialization
Browse files Browse the repository at this point in the history
  • Loading branch information
alejamp committed Dec 20, 2024
1 parent 00cb706 commit a48a497
Show file tree
Hide file tree
Showing 5 changed files with 295 additions and 11 deletions.
4 changes: 2 additions & 2 deletions celai_chatwoot/connector/model/woot_lead.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ def __init__(self,
conversation_id:str,
message_type: str = None,
**kwargs):
super().__init__(connector_name="chatwoot", **kwargs)
super().__init__(**kwargs)
self.account_id = str(account_id)
self.inbox_id = str(inbox_id)
self.conversation_id = str(conversation_id)
Expand All @@ -37,7 +37,7 @@ def from_dict(cls, lead_dict):
)

def __str__(self):
return f"TelegramLead: {self.chat_id}"
return f"WootLead: {self.account_id}:{self.inbox_id}:{self.conversation_id}"


@classmethod
Expand Down
16 changes: 12 additions & 4 deletions celai_chatwoot/connector/woo_connector.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,11 @@
from .bot_utils import ChatwootAgentsBots


def hash_token(token: str) -> str:
"""Hash the token using SHA256. Returns last 8 characters of the hash."""
import hashlib
return hashlib.sha256(token.encode()).hexdigest()[-8:]




Expand Down Expand Up @@ -56,10 +61,15 @@ def __init__(self,
self.ssl = ssl


def name(self) -> str:
hashed_token = hash_token(self.access_key)
return f"chatwoot:{hashed_token}:{self.account_id}:{self.inbox_id}"


def __create_routes(self, router: APIRouter):

@router.post(f"/webhook/{self.security_token}")
async def telegram_webhook(payload: Dict[Any, Any], background_tasks: BackgroundTasks):
async def woot_webhook(payload: Dict[Any, Any], background_tasks: BackgroundTasks):

background_tasks.add_task(self.__process_message, payload)
return {"status": "ok"}
Expand Down Expand Up @@ -123,7 +133,7 @@ async def send_message(self, message: OutgoingMessage):
assert isinstance(message, OutgoingMessage),\
"message must be an instance of OutgoingMessage"
assert isinstance(message.lead, WootLead),\
"lead must be an instance of TelegramLead"
"lead must be an instance of WootLead"
lead = message.lead

if message.type == OutgoingMessageType.TEXT:
Expand Down Expand Up @@ -234,8 +244,6 @@ async def send_audio_message(self,



def name(self) -> str:
return "telegram"

def get_router(self) -> APIRouter:
return self.router
Expand Down
118 changes: 118 additions & 0 deletions examples/callback_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
# LOAD ENV VARIABLES
import os
import time
import json
from loguru import logger as log
# Load .env variables
from dotenv import load_dotenv





load_dotenv()


# REMOVE THIS BLOCK IF YOU ARE USING THIS SCRIPT AS A TEMPLATE
# -------------------------------------------------------------
import sys
from pathlib import Path
# Add parent directory to path
path = Path(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(str(path.parents[0]))
# -------------------------------------------------------------

# Import Cel.ai modules
from cel.connectors.telegram import TelegramConnector
from cel.gateway.message_gateway import MessageGateway, StreamMode
from cel.assistants.macaw.macaw_assistant import MacawAssistant
from cel.prompt.prompt_template import PromptTemplate
from cel.assistants.request_context import RequestContext
from cel.gateway.http_callbacks import HttpCallbackProvider
from cel.gateway.model.conversation_lead import ConversationLead
from cel.gateway.model.message_gateway_context import MessageGatewayContext
from celai_chatwoot.connector.woo_connector import WootConnector


from datetime import datetime
date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

# Setup prompt
prompt = """You are an AI Assistant called Jane.
Today: {date}
"""

callbacks = HttpCallbackProvider()



prompt_template = PromptTemplate(prompt, initial_state={
# Today full date and time
"date": date,
})

ast = MacawAssistant(prompt=prompt_template, state={})



@ast.event('message')
async def handle_message(session, ctx: RequestContext):

if ctx.message.text == "link":
log.debug(f"Link request for:{ctx.lead.conversation_from.name}")

async def handle_callback(lead: ConversationLead, data: dict):
log.critical(f"Callback received from {lead} with data: {data}")
await ctx.send_text_message("Thank you for completing the task with data: " + json.dumps(data))
return {"saved": True}

# Create a callback
url = callbacks.create_callback(ctx.lead,
handle_callback,
ttl=20,
single_use=False)


await ctx.send_link_message("Welcome, this is a link to complete the task", "Click here", url)
return ctx.cancel_ai_response()

# Setup the Callback Provider
def on_startup(context: MessageGatewayContext):
callbacks.setup(context)


# Create the Message Gateway - This component is the core of the assistant
# It handles the communication between the assistant and the connectors
gateway = MessageGateway(
assistant=ast,
host="127.0.0.1", port=5004,
on_startup=on_startup
)

# # For this example, we will use the Telegram connector
# conn = TelegramConnector(
# token=os.environ.get("TELEGRAM_TOKEN"),
# stream_mode=StreamMode.FULL
# )
# # Register the connector with the gateway
# gateway.register_connector(conn)


# For this example, we will use the Telegram connector
conn = WootConnector(
bot_name="Testing Ale Bot",
access_key=os.environ.get("CHATWOOT_ACCESS_KEY"),
account_id=os.environ.get("CHATWOOT_ACCOUNT_ID"),
inbox_id=os.environ.get("CHATWOOT_INBOX_ID"),
chatwoot_url=os.environ.get("CHATWOOT_URL"),
bot_description="This is a test bot",
stream_mode=StreamMode.FULL
)


# Register the connector with the gateway
gateway.register_connector(conn)

# Then start the gateway and begin processing messages
gateway.run(enable_ngrok=True)

Loading

0 comments on commit a48a497

Please sign in to comment.