Skip to main content
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.

Installation

npm install @memvid/sdk openai

Quick Start

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;
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.

Available Functions

The CrewAI adapter provides three functions:
FunctionDescription
memvid_putStore documents in memory with title, label, and text
memvid_findSearch for relevant documents by query
memvid_askAsk questions with RAG-style answer synthesis

Python: Basic Usage with CrewAI

from crewai import Agent, Task, Crew
from memvid_sdk import use

# Initialize with crewai adapter
mem = use('crewai', 'knowledge.mv2', read_only=True)

# Get the search tool
search_tool = mem.get_search_tool()

# 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=[search_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

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

from crewai import Agent, Task, Crew, Process
from memvid_sdk import use

# Initialize
mem = use('crewai', 'knowledge.mv2', read_only=True)
search_tool = mem.get_search_tool()

# Create multiple agents
researcher = Agent(
    role="Researcher",
    goal="Find comprehensive information from the knowledge base",
    backstory="Skilled at finding relevant information quickly",
    tools=[search_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)

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
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