Connect a CrewAI Agent
A one-task CrewAI crew answers each inbound message and replies using a tool.
Tested with: CrewAI 1.15.45, Python 3.12, msend API v1.
1. Install
pip install -r examples/crewai/requirements.txtCreate an agent and API key in msend, then set MSEND_URL and MSEND_API_KEY.
2. Define the send_message Tool
@tool("send_message")
def send_message(conversation_id: str, text: str) -> str:
"""Reply to the person in a msend conversation. The reply is delivered on their channel."""
return msend("POST", f"/conversations/{conversation_id}/messages", json={"text": text})["id"]3. Load Conversation History
CrewAI does not manage a persistent session ID out of the box, so load recent messages from GET /conversations/{id}/messages:
def handle(data):
conversation_id = data["conversation"]["id"]
history = msend("GET", f"/conversations/{conversation_id}/messages", params={"limit": 20})["data"]
transcript = "\n".join(
f"{'Customer' if m['direction'] == 'inbound' else 'Agent'}: {m['text']}"
for m in history
)
task = Task(
description=(
f"conversation_id={conversation_id}\n"
f"Conversation so far:\n{transcript}\n\n"
f"Message: {data['message']['text']}\n\n"
"Reply to the customer with the send_message tool."
),
expected_output="Confirmation that the reply was sent.",
agent=support,
)
Crew(agents=[support], tasks=[task], verbose=False).kickoff()4. Poll for Events
cursor = None
while True:
page = msend("GET", "/events", params={"after": cursor} if cursor else {})
for event in page["data"]:
data = event["data"]
if event["kind"] == "message.received" and data["message"]["addressed_to_agent"]:
handle(data)
cursor = page["cursor"] or cursor
time.sleep(1)Last updated on