> ## Documentation Index
> Fetch the complete documentation index at: https://docs.memvid.com/llms.txt
> Use this file to discover all available pages before exploring further.

# CrewAI

> Build AI crews with Memvid-powered knowledge retrieval

Integrate Memvid with CrewAI to build collaborative AI crews with shared knowledge access. The `crewai` adapter provides function schemas compatible with OpenAI's function calling API.

<Tabs>
  <Tab title="Node.js">
    ## Installation

    ```bash theme={null}
    npm install @memvid/sdk openai
    ```

    ## Quick Start

    ```typescript theme={null}
    import { use } from '@memvid/sdk';

    // Open with CrewAI adapter
    const mem = await use('crewai', 'knowledge.mv2');

    // Access function schemas (OpenAI-compatible)
    const functions = mem.functions;
    ```

    <Note>
      Node.js uses OpenAI function calling directly. CrewAI is Python-only,
      but the function schemas work with any OpenAI-compatible client for
      building similar multi-agent workflows.
    </Note>
  </Tab>

  <Tab title="Python">
    ## Installation

    ```bash theme={null}
    pip install memvid-sdk crewai crewai-tools
    ```

    ## Quick Start

    ```python theme={null}
    from memvid_sdk import create, use
    import os

    # Create new file or open existing
    if os.path.exists('knowledge.mv2'):
        mem = use('crewai', 'knowledge.mv2')
    else:
        mem = create('knowledge.mv2', kind='crewai')

    # Access CrewAI tools
    tools = mem.tools  # Returns CrewAI Tool objects
    ```
  </Tab>
</Tabs>

## Available Functions

The CrewAI adapter provides three functions:

| Function      | Description                                           |
| ------------- | ----------------------------------------------------- |
| `memvid_put`  | Store documents in memory with title, label, and text |
| `memvid_find` | Search for relevant documents by query                |
| `memvid_ask`  | Ask questions with RAG-style answer synthesis         |

## Python: Basic Usage with CrewAI

```python theme={null}
from crewai import Agent, Task, Crew
from memvid_sdk import create, use
import os

# Create new file or open existing
if os.path.exists('knowledge.mv2'):
    mem = use('crewai', 'knowledge.mv2', read_only=True)
else:
    mem = create('knowledge.mv2', kind='crewai')

# Get the search tool (find tool is at index 1)
find_tool = mem.tools[1]

# Create agent with Memvid tool
researcher = Agent(
    role="Research Analyst",
    goal="Find relevant information from the knowledge base",
    backstory="Expert at finding and analyzing information",
    tools=[find_tool],
    verbose=True
)

# Define task
research_task = Task(
    description="Research the main features and create a summary",
    agent=researcher,
    expected_output="A summary of the main features"
)

# Create crew
crew = Crew(
    agents=[researcher],
    tasks=[research_task]
)

# Execute
result = crew.kickoff()
print(result)
```

## Node.js: Multi-Agent Workflow

```typescript theme={null}
import { use } from '@memvid/sdk';
import OpenAI from 'openai';

// Get Memvid functions
const mem = await use('crewai', 'knowledge.mv2');
const functions = mem.functions;

const client = new OpenAI();

// Define agent personas
const agents = {
  researcher: {
    role: 'Research Analyst',
    goal: 'Find relevant information from the knowledge base',
    systemPrompt: 'You are a research analyst. Use the memvid_find tool to search the knowledge base.',
  },
  writer: {
    role: 'Technical Writer',
    goal: 'Write clear documentation based on research',
    systemPrompt: 'You are a technical writer. Summarize the research findings clearly.',
  },
};

// Execute function by name
async function executeFunction(name: string, args: any): Promise<string> {
  if (name === 'memvid_find') {
    const result = await mem.find(args.query, { k: args.top_k || 5 });
    return JSON.stringify(result.hits?.map((h: any) => ({
      title: h.title,
      snippet: h.snippet || h.text?.slice(0, 200),
    })));
  } else if (name === 'memvid_ask') {
    const result = await mem.ask(args.question, { mode: args.mode || 'auto' });
    return result.answer || 'No answer generated';
  }
  return 'Unknown function';
}

// Run agent with tools
async function runAgent(agent: typeof agents.researcher, task: string): Promise<string> {
  const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [
    { role: 'system', content: agent.systemPrompt },
    { role: 'user', content: task },
  ];

  while (true) {
    const response = await client.chat.completions.create({
      model: 'gpt-4o',
      messages,
      tools: functions.map((f: any) => ({ type: 'function' as const, function: f })),
      tool_choice: 'auto',
    });

    const message = response.choices[0].message;
    messages.push(message);

    if (message.tool_calls) {
      for (const toolCall of message.tool_calls) {
        const result = await executeFunction(
          toolCall.function.name,
          JSON.parse(toolCall.function.arguments)
        );
        messages.push({ role: 'tool', tool_call_id: toolCall.id, content: result });
      }
    } else {
      return message.content || '';
    }
  }
}

// Execute crew workflow
async function runCrew() {
  // Step 1: Research
  console.log('🔍 Researcher working...');
  const research = await runAgent(
    agents.researcher,
    'Research authentication mechanisms in the knowledge base'
  );
  console.log('Research findings:', research);

  // Step 2: Writing (uses research context)
  console.log('✍️ Writer working...');
  const documentation = await runAgent(
    agents.writer,
    `Based on this research, write a clear guide:\n\n${research}`
  );
  console.log('Final documentation:', documentation);
}

await runCrew();
await mem.seal();
```

## Python: Multi-Agent Crew

```python theme={null}
from crewai import Agent, Task, Crew, Process
from memvid_sdk import create, use
import os

# Create new file or open existing
if os.path.exists('knowledge.mv2'):
    mem = use('crewai', 'knowledge.mv2', read_only=True)
else:
    mem = create('knowledge.mv2', kind='crewai')

# Get the find tool (index 1)
find_tool = mem.tools[1]

# Create multiple agents
researcher = Agent(
    role="Researcher",
    goal="Find comprehensive information from the knowledge base",
    backstory="Skilled at finding relevant information quickly",
    tools=[find_tool],
    verbose=True
)

writer = Agent(
    role="Technical Writer",
    goal="Write clear documentation based on research",
    backstory="Expert at translating technical content into readable docs",
    verbose=True
)

reviewer = Agent(
    role="Editor",
    goal="Review and improve the documentation for clarity",
    backstory="Meticulous editor with attention to detail",
    verbose=True
)

# Define tasks
research_task = Task(
    description="Research authentication mechanisms in the knowledge base",
    agent=researcher,
    expected_output="Detailed findings about authentication"
)

writing_task = Task(
    description="Write a guide based on the research findings",
    agent=writer,
    expected_output="A clear authentication guide",
    context=[research_task]  # Depends on research
)

review_task = Task(
    description="Review and polish the guide for publication",
    agent=reviewer,
    expected_output="Final polished guide",
    context=[writing_task]  # Depends on writing
)

# Create crew with sequential process
crew = Crew(
    agents=[researcher, writer, reviewer],
    tasks=[research_task, writing_task, review_task],
    process=Process.sequential,
    verbose=True
)

result = crew.kickoff()
print(result)
```

## Custom Tools (Python)

```python theme={null}
from crewai.tools import tool
from memvid_sdk import use

mem = use('crewai', 'knowledge.mv2', read_only=True)

@tool("Search Knowledge Base")
def search_knowledge(query: str) -> str:
    """Search the knowledge base for relevant information."""
    results = mem.find(query, k=5)
    return "\n".join([f"- {r.title}: {r.snippet}" for r in results])

@tool("Get Recent Entries")
def get_recent(limit: int = 10) -> str:
    """Get the most recent entries from the knowledge base."""
    entries = mem.timeline(limit=limit)
    return "\n".join([f"- [{e.timestamp}] {e.title}" for e in entries])

@tool("Ask Question")
def ask_question(question: str) -> str:
    """Ask a question and get an AI-synthesized answer."""
    answer = mem.ask(question)
    return str(answer.get("answer", ""))
```

## Best Practices

1. **Use read-only mode** for retrieval crews
2. **Share tools** across agents that need knowledge access
3. **Use task context** to pass information between tasks
4. **Close the memory** when done

```python theme={null}
mem = use('crewai', 'knowledge.mv2', read_only=True)
try:
    # Create and run crew
    crew = Crew(agents=[...], tasks=[...])
    result = crew.kickoff()
finally:
    mem.seal()
```

## Next Steps

<CardGroup cols={2}>
  <Card title="AutoGen" icon="robot" href="/frameworks/autogen">
    AutoGen integration
  </Card>

  <Card title="OpenAI SDK" icon="brain" href="/frameworks/openai">
    Direct OpenAI function calling
  </Card>
</CardGroup>
