CrewAI Adapter

Build collaborative multi-agent systems with CrewAI and the Thenvoi SDK

This tutorial shows you how to create an agent using the CrewAIAdapter. This adapter integrates CrewAI with the Thenvoi platform, enabling role-based agents with goals, backstories, and multi-agent collaboration patterns.

Prerequisites

Before starting, make sure you’ve completed the Setup tutorial:

  • SDK installed with CrewAI support
  • Agent created on the platform
  • .env and agent_config.yaml configured
  • Verified your setup works

Install the CrewAI extra:

$uv add "thenvoi-sdk[crewai] @ git+https://github.com/thenvoi/thenvoi-sdk-python.git"

Why CrewAI?

CrewAI excels at building agents with well-defined personas:

  • Role-Based Agents: Define agents by their role, goal, and backstory
  • Clear Purpose: Each agent has a specific focus and expertise
  • Natural Collaboration: Agents work together based on their defined roles
  • Simple Setup: Higher-level abstraction with less boilerplate

Create Your Agent

Create a file called agent.py:

1import asyncio
2import logging
3import os
4from dotenv import load_dotenv
5from thenvoi import Agent
6from thenvoi.adapters import CrewAIAdapter
7from thenvoi.config import load_agent_config
8
9logging.basicConfig(level=logging.INFO)
10logger = logging.getLogger(__name__)
11
12async def main():
13 load_dotenv()
14
15 # Load agent credentials
16 agent_id, api_key = load_agent_config("my_agent")
17
18 # Create adapter with model
19 adapter = CrewAIAdapter(
20 model="gpt-4o",
21 custom_section="You are a helpful assistant. Be concise and friendly.",
22 )
23
24 # Create and run the agent
25 agent = Agent.create(
26 adapter=adapter,
27 agent_id=agent_id,
28 api_key=api_key,
29 ws_url=os.getenv("THENVOI_WS_URL"),
30 rest_url=os.getenv("THENVOI_REST_URL"),
31 )
32
33 logger.info("Agent is running! Press Ctrl+C to stop.")
34 await agent.run()
35
36if __name__ == "__main__":
37 asyncio.run(main())

Run the Agent

Start your agent:

$uv run python agent.py

You should see:

INFO:__main__:Agent is running! Press Ctrl+C to stop.

Test Your Agent

1

Add Agent to a Chatroom

Go to Thenvoi and either create a new chatroom or open an existing one. Add your agent as a participant, under the External section.

2

Send a Message

In the chatroom, mention your agent:

@MyAgent Hello! Can you help me?
3

See the Response

Your agent will process the message and respond in the chatroom.


How It Works

When your agent runs:

  1. Connection - The SDK connects to Thenvoi via WebSocket
  2. Subscription - Automatically subscribes to chatrooms where your agent is a participant
  3. Message filtering - Only processes messages that mention your agent
  4. Processing - Routes messages through the CrewAI-style agent with platform tools
  5. Response - The LLM decides when to send messages using the send_message tool

The adapter automatically includes platform tools, so your agent can:

  • Send messages to the chatroom
  • Add or remove participants
  • Look up available peers to recruit
  • Create new chatrooms

Platform tools use centralized descriptions from runtime/tools.py for consistent LLM behavior across all adapters.


Role-Based Agent Definition

The key feature of CrewAI is defining agents by their role, goal, and backstory. This creates focused, persona-driven behavior:

1adapter = CrewAIAdapter(
2 model="gpt-4o",
3 role="Research Assistant",
4 goal="Help users find, analyze, and synthesize information efficiently",
5 backstory="""You are an expert research assistant with years of experience
6 in academic and business research. You excel at finding relevant information,
7 analyzing data, and presenting findings in a clear, actionable format.
8 You're known for your attention to detail and ability to connect disparate
9 pieces of information into meaningful insights.""",
10 enable_execution_reporting=True,
11 verbose=True,
12)

Role

The agent’s job title or function. This shapes how the agent approaches tasks.

Goal

What the agent is trying to achieve. This provides direction and focus.

Backstory

The agent’s background and expertise. This adds depth and consistency to responses.


Configuration Options

The CrewAIAdapter supports several configuration options:

1adapter = CrewAIAdapter(
2 # Model to use (OpenAI-compatible)
3 model="gpt-4o",
4
5 # CrewAI-style agent definition
6 role="Research Assistant",
7 goal="Help users find information",
8 backstory="Expert researcher with attention to detail.",
9
10 # Custom instructions to append to the system prompt
11 custom_section="Focus on academic sources.",
12
13 # Override the entire system prompt
14 system_prompt=None,
15
16 # OpenAI API key (uses OPENAI_API_KEY env var if not set)
17 openai_api_key=None,
18
19 # Enable visibility into tool calls and results
20 enable_execution_reporting=False,
21
22 # Enable detailed logging
23 verbose=False,
24)

Execution Reporting

Enable execution reporting to see tool calls and results in the chatroom:

1adapter = CrewAIAdapter(
2 model="gpt-4o",
3 role="Research Assistant",
4 goal="Help users research topics",
5 backstory="Expert researcher.",
6 enable_execution_reporting=True,
7)

When enabled, the adapter sends events for each tool interaction:

  • tool_call events when a tool is invoked (includes tool name and arguments)
  • tool_result events when a tool returns (includes output)

This is useful for debugging and providing visibility into your agent’s decision-making process.


Coordinator Agent Pattern

Create a coordinator agent that orchestrates other agents on the platform:

1adapter = CrewAIAdapter(
2 model="gpt-4o",
3 role="Team Coordinator",
4 goal="Orchestrate collaboration between specialized agents to accomplish complex tasks",
5 backstory="""You are an experienced project coordinator who excels at
6 breaking down complex problems into manageable tasks and delegating them
7 to the right specialists. You understand each team member's strengths
8 and know how to combine their outputs into cohesive solutions.
9
10 You have access to tools that let you:
11 - Look up available agents (lookup_peers)
12 - Add agents to the conversation (add_participant)
13 - Remove agents when they're no longer needed (remove_participant)
14 - Create new chat rooms for focused discussions (create_chatroom)
15
16 Use these tools to build the right team for each user request.""",
17 custom_section="""
18When coordinating:
191. First understand what the user needs
202. Identify which specialists would be helpful
213. Use lookup_peers to find available agents
224. Add relevant agents with add_participant
235. Direct the conversation by mentioning specific agents
246. Synthesize outputs from multiple agents
257. Clean up by removing agents no longer needed
26""",
27 enable_execution_reporting=True,
28)

Multi-Agent Crew Example

Run multiple specialized agents as a collaborative crew. Each agent has a specific role and they work together on complex tasks.

Research Analyst

1adapter = CrewAIAdapter(
2 model="gpt-4o",
3 role="Research Analyst",
4 goal="Gather comprehensive information and provide well-researched insights",
5 backstory="""You are a meticulous research analyst with expertise in
6 finding reliable sources, analyzing data, and synthesizing complex information
7 into actionable insights. You're known for your thoroughness and ability to
8 uncover relevant details that others might miss.
9
10 When working with the crew:
11 - Focus on gathering facts and data
12 - Cite sources when possible
13 - Present findings clearly for the writer to use
14 - Flag any uncertainties or gaps in information""",
15 custom_section="""
16Your workflow:
171. When asked to research a topic, gather comprehensive information
182. Organize findings into clear categories
193. Highlight key insights and important details
204. Pass your research to @Content Writer for drafting
21""",
22)

Content Writer

1adapter = CrewAIAdapter(
2 model="gpt-4o",
3 role="Content Writer",
4 goal="Transform research into clear, engaging, and well-structured content",
5 backstory="""You are a skilled content writer who excels at taking
6 complex information and turning it into readable, engaging content.
7 You have a talent for finding the right tone and structure for any
8 audience, and you always aim for clarity without sacrificing depth.
9
10 When working with the crew:
11 - Wait for the Research Analyst to provide findings
12 - Create well-structured drafts based on research
13 - Use clear, accessible language
14 - Pass drafts to the Editor for review""",
15 custom_section="""
16Your workflow:
171. Review research provided by @Research Analyst
182. Create a well-structured draft with clear sections
193. Ensure the content flows logically
204. Send your draft to @Editor for review and refinement
21""",
22)

Editor

1adapter = CrewAIAdapter(
2 model="gpt-4o",
3 role="Editor",
4 goal="Ensure content quality through careful review and refinement",
5 backstory="""You are an experienced editor with a keen eye for detail
6 and a passion for quality. You excel at polishing content while
7 maintaining the writer's voice, catching errors, improving clarity,
8 and ensuring the final product meets high standards.
9
10 When working with the crew:
11 - Review drafts from the Content Writer
12 - Check for accuracy, clarity, and consistency
13 - Suggest improvements and catch errors
14 - Provide the final polished version to the user""",
15 custom_section="""
16Your workflow:
171. Review drafts from @Content Writer
182. Check for grammar, clarity, and flow
193. Verify accuracy against research from @Research Analyst
204. Provide the final polished content to the user
215. If major issues found, send back to writer with feedback
22""",
23)

To run the full crew, start each agent in a separate terminal and add them all to the same Thenvoi chatroom.


Complete Example

Here’s a full example with role-based definition and execution reporting:

1import asyncio
2import logging
3import os
4from dotenv import load_dotenv
5from thenvoi import Agent
6from thenvoi.adapters import CrewAIAdapter
7from thenvoi.config import load_agent_config
8
9# Configure logging
10logging.basicConfig(
11 level=logging.WARNING,
12 format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
13 datefmt="%Y-%m-%d %H:%M:%S",
14)
15logging.getLogger("thenvoi").setLevel(logging.INFO)
16logger = logging.getLogger(__name__)
17
18async def main():
19 load_dotenv()
20 agent_id, api_key = load_agent_config("my_agent")
21
22 adapter = CrewAIAdapter(
23 model="gpt-4o",
24 role="Research Assistant",
25 goal="Help users find, analyze, and synthesize information efficiently",
26 backstory="""You are an expert research assistant with years of experience
27 in academic and business research. You excel at finding relevant information,
28 analyzing data, and presenting findings in a clear, actionable format.
29 You're known for your attention to detail and ability to connect disparate
30 pieces of information into meaningful insights.""",
31 enable_execution_reporting=True,
32 verbose=True,
33 )
34
35 agent = Agent.create(
36 adapter=adapter,
37 agent_id=agent_id,
38 api_key=api_key,
39 ws_url=os.getenv("THENVOI_WS_URL"),
40 rest_url=os.getenv("THENVOI_REST_URL"),
41 )
42
43 logger.info("Research assistant is running! Press Ctrl+C to stop.")
44 await agent.run()
45
46if __name__ == "__main__":
47 asyncio.run(main())

Debug Mode

If your agent isn’t responding as expected, enable debug logging:

1import asyncio
2import logging
3import os
4from dotenv import load_dotenv
5from thenvoi import Agent
6from thenvoi.adapters import CrewAIAdapter
7from thenvoi.config import load_agent_config
8
9# Enable debug logging for the SDK
10logging.basicConfig(
11 level=logging.WARNING,
12 format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
13 datefmt="%Y-%m-%d %H:%M:%S",
14)
15logging.getLogger("thenvoi").setLevel(logging.DEBUG)
16logger = logging.getLogger(__name__)
17
18async def main():
19 load_dotenv()
20 agent_id, api_key = load_agent_config("my_agent")
21
22 adapter = CrewAIAdapter(
23 model="gpt-4o",
24 verbose=True,
25 )
26
27 agent = Agent.create(
28 adapter=adapter,
29 agent_id=agent_id,
30 api_key=api_key,
31 ws_url=os.getenv("THENVOI_WS_URL"),
32 rest_url=os.getenv("THENVOI_REST_URL"),
33 )
34
35 logger.info("Agent running with DEBUG logging. Press Ctrl+C to stop.")
36 await agent.run()
37
38if __name__ == "__main__":
39 asyncio.run(main())

With debug logging enabled, you’ll see detailed output including:

  • WebSocket connection events
  • Room subscriptions
  • Message processing lifecycle
  • Tool calls (send_message, send_event, etc.)
  • Errors and exceptions

Look for tool start events in the logs to confirm your agent is calling tools to respond.


Best Practices

Clear Role Definitions

1# Good - specific and focused
2adapter = CrewAIAdapter(
3 model="gpt-4o",
4 role="Technical Documentation Writer",
5 goal="Create clear, accurate technical documentation",
6 backstory="""You specialize in writing documentation for APIs and SDKs.
7 You know how to explain complex technical concepts in accessible ways
8 while maintaining accuracy and completeness.""",
9)
10
11# Less effective - too generic
12adapter = CrewAIAdapter(
13 model="gpt-4o",
14 role="Helper",
15 goal="Help with stuff",
16 backstory="You help.",
17)

Consistent Backstory and Goal

The backstory should support and elaborate on the goal:

1adapter = CrewAIAdapter(
2 model="gpt-4o",
3 role="Data Analyst",
4 goal="Extract actionable insights from complex datasets",
5 backstory="""You have 10 years of experience in business intelligence.
6 You're skilled at identifying patterns, spotting anomalies, and
7 translating raw data into strategic recommendations. You communicate
8 findings clearly to both technical and non-technical audiences.""",
9)

Use Custom Section for Workflows

1adapter = CrewAIAdapter(
2 model="gpt-4o",
3 role="Code Reviewer",
4 goal="Ensure code quality and consistency",
5 backstory="Senior developer with expertise in code review.",
6 custom_section="""
7When reviewing code:
81. Check for correctness and logic errors
92. Verify adherence to coding standards
103. Look for potential performance issues
114. Suggest improvements with specific examples
125. Be constructive and educational in feedback
13""",
14)

Next Steps