CrewAI integration

Add long-term agent memory and knowledge graphs to CrewAI agents

The zep-crewai package gives CrewAI agents persistent memory backed by Zep’s temporal knowledge graph. You persist conversation turns and business data with Zep storage adapters, and give your agents Zep tools so they can retrieve relevant context when they need it. This lets agents carry context across executions, share a common knowledge base, and ground their decisions in what was learned before.

Core benefits

  • Persistent memory — Conversations and knowledge persist across sessions and crew runs.
  • On-demand retrieval — Agents search Zep through tools and pull in context exactly when a task calls for it.
  • Dual storage — User-specific memory for individuals and shared knowledge graphs for organizational data.
  • Tool integration — Search and add-data tools let agents read from and write to Zep during execution.

How it works

Memory in this integration is explicit and tool-driven. There are two distinct steps, and you control both.

Persisting context. Create a ZepUserStorage or ZepGraphStorage adapter and call storage.save(value, metadata={"type": ...}). The adapter routes each item by its type:

Metadata typeRoutes toUse for
messageThread APIConversation turns (role-based)
jsonKnowledge graphStructured data
textKnowledge graphFacts, preferences, free text

Retrieving context. Attach create_search_tool (and optionally create_add_data_tool) to an Agent(tools=[...]). The agent searches Zep when it decides the task needs it. You can also call ZepUserStorage.get_context() directly to fetch the prompt-ready context block that Zep auto-assembles for a thread.

Failure isolation. save() on every storage adapter logs a Zep failure and returns normally instead of raising, so a Zep outage never crashes a crew run. When you want misconfiguration to fail loudly, provision with ensure_user and ensure_thread before the crew runs — see provisioning users and threads.

There is no automatic retrieval or storage, and no external_memory= Crew wiring. CrewAI 1.x removed the ExternalMemory(storage=...) wrapper and the storage interface it depended on, so context is never injected behind the scenes. You decide what to save with save(...), and the agent decides what to search through its tools. The package is also sync-only: its adapters are built on the synchronous Zep client.

Installation

$pip install zep-crewai

Requires Python 3.11+, zep-crewai>=1.2.0, crewai>=1.0.0, zep-cloud>=3.23.0, and pydantic>=2.0.0, plus a Zep Cloud API key. Get your API key from app.getzep.com.

Set your API key in the environment:

$export ZEP_API_KEY="your-zep-api-key"

Three changes affect existing code:

  • The compound all search scope is removed — use auto to let Zep pick a scope.
  • save() logs Zep failures instead of raising them.
  • search() wraps its context string in a <ZEP_CONTEXT> template; pass context_template="{context}" for the raw block.

See the package changelog for the full list of changes.

Provisioning users and threads

ensure_user and ensure_thread are idempotent create-then-catch-conflict helpers. Both return True when the resource is newly created and False when it already exists; genuine failures (auth, network, 5xx) raise. Call them before a crew runs so misconfiguration surfaces loudly rather than being swallowed by save().

The optional on_created hook fires exactly once, only when the user is genuinely new — use it for one-time per-user setup such as ontology configuration.

Python
1from zep_crewai import ensure_user, ensure_thread
2
3def setup_new_user(client, user_id):
4 client.graph.set_ontology(...) # one-time per-user configuration
5
6ensure_user(zep_client, user_id="alice_123", first_name="Alice", on_created=setup_new_user)
7ensure_thread(zep_client, thread_id="project_456", user_id="alice_123")

ZepUserStorage and ZepStorage also provision lazily on the first save() or search() call; pass first_name, last_name, email, or on_created to their constructors to feed that path. The lazy path never raises — a provisioning failure is logged and the call becomes a no-op — so prefer the explicit helpers when you want failures to surface. ZepGraphStorage is scoped to a standalone graph rather than a Zep user, so it has no lazy provisioning; passing it on_created raises TypeError.

Storage types

User storage

Use ZepUserStorage for an individual user’s conversation history and personal context. A thread_id is required and ties message storage to a conversation thread. CrewAI has no automatic persistence loop; sharing one thread across multiple agents is safe when your code or tools write each turn once.

Python
1import os
2from zep_cloud.client import Zep
3from zep_crewai import ZepUserStorage, create_search_tool, ensure_user, ensure_thread
4from crewai import Agent
5
6zep_client = Zep(api_key=os.getenv("ZEP_API_KEY"))
7
8# Provision the user and thread (idempotent; genuine failures raise)
9ensure_user(zep_client, user_id="alice_123", first_name="Alice")
10ensure_thread(zep_client, thread_id="project_456", user_id="alice_123")
11
12# Create user storage
13user_storage = ZepUserStorage(
14 client=zep_client,
15 user_id="alice_123",
16 thread_id="project_456",
17)
18
19# Persist a conversation turn (routes to the thread)
20user_storage.save(
21 "How can I help you today?",
22 metadata={"type": "message", "role": "assistant", "name": "Helper"},
23)
24
25# Persist a preference as graph data
26user_storage.save(
27 "Alice prefers morning meetings",
28 metadata={"type": "text"},
29)
30
31# Give an agent a Zep search tool so it can retrieve this context on demand
32assistant = Agent(
33 role="Personal Assistant",
34 goal="Help Alice using what you know about her",
35 backstory="You know Alice's preferences and conversation history.",
36 tools=[create_search_tool(zep_client, user_id="alice_123")],
37)

To fetch the auto-assembled context block for the thread directly, call get_context():

Python
1# Returns a prompt-ready context block string (or None if empty)
2context = user_storage.get_context()
3print(context)

Graph storage

Use ZepGraphStorage for shared organizational knowledge that multiple agents can read and write.

Python
1from zep_cloud import SearchFilters
2from zep_crewai import ZepGraphStorage, create_search_tool
3from crewai import Agent
4
5# Create the graph
6zep_client.graph.create(
7 graph_id="company_knowledge",
8 name="Company Knowledge Graph",
9 description="Shared organizational knowledge and insights.",
10)
11
12# Create graph storage for shared knowledge
13graph_storage = ZepGraphStorage(
14 client=zep_client,
15 graph_id="company_knowledge",
16 search_filters=SearchFilters(node_labels=["Technology", "Project"]),
17)
18
19# Persist knowledge
20graph_storage.save(
21 "Project Alpha uses Python and React",
22 metadata={"type": "text"},
23)
24
25# Let agents search it through a tool
26knowledge_agent = Agent(
27 role="Knowledge Assistant",
28 goal="Answer questions from the shared knowledge graph",
29 backstory="You maintain and search the team's shared knowledge.",
30 tools=[create_search_tool(zep_client, graph_id="company_knowledge")],
31)

You can also search a graph directly. search returns a list whose entries include a composed context string wrapped in the storage’s context template — a <ZEP_CONTEXT>...</ZEP_CONTEXT> block by default:

Python
1results = graph_storage.search("project status", limit=5)
2for item in results:
3 print(item.get("context", "")) # <ZEP_CONTEXT> ... </ZEP_CONTEXT>

Pass context_template="{context}" to the storage constructor to get the bare context string instead.

Customizing retrieved context

Both storage classes wrap the context string returned from search() in a template. context_template must contain a literal {context} placeholder and is rendered with plain string replacement (never str.format), so context containing {, }, or % is always safe. The default is the DEFAULT_CONTEXT_TEMPLATE export — the <ZEP_CONTEXT>...</ZEP_CONTEXT> block shared across Zep integrations.

ZepUserStorage also accepts a context_builder: a synchronous callable that replaces the default graph composition in search() with your own retrieval logic. The builder receives a frozen ContextInput (zep, user_id, thread_id, user_message) and returns the context string, or None for no results. A builder exception is logged and degrades to empty results.

Python
1from zep_crewai import ZepUserStorage, ContextInput
2
3def my_builder(ctx: ContextInput) -> str | None:
4 results = ctx.zep.graph.search(user_id=ctx.user_id, query=ctx.user_message, scope="edges")
5 if not results.edges:
6 return None
7 return "\n".join(edge.fact for edge in results.edges)
8
9storage = ZepUserStorage(
10 client=zep_client,
11 user_id="alice_123",
12 thread_id="project_456",
13 context_builder=my_builder,
14)

Tool integration

Tools are the supported extension point for exposing Zep to CrewAI agents. Bind a tool to a single user or a single graph at creation time, then add it to an agent’s tools list.

Python
1from zep_cloud import SearchFilters
2from zep_crewai import create_search_tool, create_add_data_tool
3from crewai import Agent
4
5# Tools bound to user storage
6user_search_tool = create_search_tool(zep_client, user_id="alice_123")
7user_add_tool = create_add_data_tool(zep_client, user_id="alice_123")
8
9# Tools bound to graph storage
10graph_search_tool = create_search_tool(zep_client, graph_id="knowledge_base")
11graph_add_tool = create_add_data_tool(zep_client, graph_id="knowledge_base")
12
13curator = Agent(
14 role="Knowledge Curator",
15 goal="Search existing knowledge and record new findings",
16 backstory="You maintain the organization's knowledge base.",
17 tools=[graph_search_tool, graph_add_tool],
18 llm="gpt-5-mini",
19)

create_search_tool and create_add_data_tool return ZepSearchTool and ZepAddDataTool instances; both classes are also exported if you prefer to construct them directly. A Zep failure inside either tool returns an error string to the agent — the tool never raises into the crew.

Search tool parameters

The search tool’s args_schema exposes every graph.search parameter to the model by default:

ParameterValuesDefault
queryNatural language search query (required; truncated to 400 characters)
scopeedges, nodes, episodes, observations, thread_summaries, autoedges
rerankerrrf, mmr, node_distance, episode_mentions, cross_encoderrrf
limitMaximum results10
mmr_lambdaDiversity/relevance balance for the mmr rerankeromitted when unset
center_node_uuidCenter node for node_distance rerankingomitted when unset

Use pinned_params to fix a parameter to a constant and remove it from the model-facing schema, or hidden_params to remove it from the schema without pinning it (Zep’s server-side default applies). The legacy scope, reranker, and limit keyword arguments each pin and hide their parameter, equivalent to putting them in pinned_params. search_filters and bfs_origin_node_uuids are constructor-only and never exposed to the model.

Python
1# Pin scope and limit (hidden from the model, always sent); hide reranker entirely
2search_tool = create_search_tool(
3 zep_client,
4 user_id="alice_123",
5 pinned_params={"scope": "edges", "limit": 5},
6 hidden_params={"reranker"},
7)
8
9# Constructor-only parameters are never exposed to the model
10search_tool = create_search_tool(
11 zep_client,
12 graph_id="knowledge_base",
13 search_filters=SearchFilters(node_labels=["Project"]),
14 bfs_origin_node_uuids=["node-uuid-1"],
15)

The tool returns results to the agent as plain - fact lines, one per result.

Add-data tool parameters

  • data — Content to store; payloads over Zep’s graph.add ceiling are truncated to 9,900 characters instead of failing.
  • data_type — Explicit type: text (default), json, or message.

Structured data with ontologies

Define entity models so Zep organizes graph data into typed entities. The SDK requires a docstring on each entity class to describe it.

Python
1from pydantic import Field
2from zep_cloud import SearchFilters
3from zep_cloud.external_clients.ontology import EntityModel, EntityText
4from zep_crewai import ZepGraphStorage
5
6class ProjectEntity(EntityModel):
7 """A project tracked in the knowledge graph."""
8
9 status: EntityText = Field(description="project status")
10 priority: EntityText = Field(description="priority level")
11 team_size: EntityText = Field(description="team size")
12
13# Apply the ontology to one or more graphs
14zep_client.graph.set_ontology(
15 graph_ids=["projects"],
16 entities={"Project": ProjectEntity},
17 edges={},
18)
19
20# Use the graph with filtered search and context limits
21graph_storage = ZepGraphStorage(
22 client=zep_client,
23 graph_id="projects",
24 search_filters=SearchFilters(node_labels=["Project"]),
25 facts_limit=20,
26 entity_limit=5,
27)

Configuration options

ZepUserStorage parameters

ParameterDescription
clientZep client instance (required)
user_idUser identifier (required)
thread_idThread identifier (required); ties message storage to a conversation thread
search_filtersFilter search results by node labels or attributes
facts_limitMaximum facts (edges) for context (default: 20)
entity_limitMaximum entities (nodes) for context (default: 5)
first_name / last_name / emailOptional identity fields applied during lazy provisioning
on_createdHook fired once when the Zep user is newly created on the lazy path
context_builderSync callable replacing the default search() composition
context_templateTemplate wrapping search() context (default: DEFAULT_CONTEXT_TEMPLATE)
modeDeprecated and ignored

ZepGraphStorage parameters

ParameterDescription
clientZep client instance (required)
graph_idGraph identifier (required)
search_filtersFilter by node labels, for example SearchFilters(node_labels=["Technology"])
facts_limitMaximum facts (edges) for context (default: 20)
entity_limitMaximum entities (nodes) for context (default: 5)
context_templateTemplate wrapping search() context (default: DEFAULT_CONTEXT_TEMPLATE)

ZepGraphStorage has no on_created parameter — it is graph-scoped, with no Zep user to provision. Passing on_created raises TypeError.

ZepStorage parameters

ZepStorage is a standalone user-and-thread adapter that preserves the historical save(value, metadata) / search(query, limit, score_threshold) / reset() contract for existing callers. It takes client, user_id, and thread_id (all required) plus the same lazy-provisioning fields as ZepUserStorage (first_name, last_name, email, on_created). New code should prefer ZepUserStorage.

Size limits

  • Zep rejects direct thread-message payloads over 4,096 characters; the CrewAI storage paths truncate message content to 4,000 characters before thread.add_messages, logging lengths only and never content.
  • Zep rejects direct graph.add payloads over 10,000 characters; CrewAI storage paths and ZepAddDataTool truncate graph payloads to 9,900 characters before calling graph.add.
  • Search queries are truncated to 400 characters (Zep’s query limit).

Complete example

This example mirrors the simple_example.py from the integration repository. It persists conversation turns and business data to a user’s memory, then runs an agent that searches that memory through a Zep tool before answering.

Python
1import os
2import sys
3import time
4import uuid
5
6from crewai import Agent, Crew, Process, Task
7from zep_cloud.client import Zep
8
9from zep_crewai import ZepUserStorage, create_search_tool, ensure_thread, ensure_user
10
11
12def main():
13 api_key = os.environ.get("ZEP_API_KEY")
14 if not api_key:
15 print("Error: set your ZEP_API_KEY environment variable")
16 print("Get your API key from: https://app.getzep.com")
17 sys.exit(1)
18
19 zep_client = Zep(api_key=api_key)
20
21 # Set up a unique user and thread
22 user_id = "demo_user_" + str(uuid.uuid4())
23 thread_id = "demo_thread_" + str(uuid.uuid4())
24
25 ensure_user(
26 zep_client,
27 user_id=user_id,
28 first_name="John",
29 last_name="Doe",
30 email="[email protected]",
31 )
32 ensure_thread(zep_client, thread_id=thread_id, user_id=user_id)
33
34 # Initialize the Zep storage adapter
35 user_storage = ZepUserStorage(client=zep_client, user_id=user_id, thread_id=thread_id)
36
37 # Persist context with metadata-based routing
38 # JSON data routes to the graph
39 user_storage.save(
40 '{"trip_type": "business", "destination": "New York", "duration": "3 days", '
41 '"budget": 2000, "accommodation_preference": "mid-range hotels"}',
42 metadata={"type": "json"},
43 )
44
45 # Messages route to the thread
46 user_storage.save(
47 "Hi, I need help planning a business trip to New York. I'll be there for 3 "
48 "days and prefer mid-range hotels.",
49 metadata={"type": "message", "role": "user", "name": "John Doe"},
50 )
51 user_storage.save(
52 "I'd be happy to help you plan your New York business trip!",
53 metadata={"type": "message", "role": "assistant", "name": "Travel Planning Assistant"},
54 )
55
56 # Text data routes to the graph
57 user_storage.save(
58 "John Doe prefers mid-range hotels with business amenities, enjoys local "
59 "cuisine, and values convenient locations near business districts.",
60 metadata={"type": "text"},
61 )
62 user_storage.save(
63 "John Doe's budget constraint: around $2000 total for the trip including "
64 "flights and accommodation. Looking for good value rather than luxury.",
65 metadata={"type": "text"},
66 )
67
68 # Allow time for indexing before the agent searches
69 time.sleep(20)
70
71 # Give the agent a Zep search tool bound to this user
72 search_tool = create_search_tool(zep_client, user_id=user_id)
73
74 travel_agent = Agent(
75 role="Travel Planning Assistant",
76 goal="Help plan business trips efficiently and within budget",
77 backstory="""You are an experienced travel planner who specializes in business
78 trips. You always consider the user's preferences, budget, and trip context.
79 Use the Zep memory search tool to recall what you know about the user before
80 answering.""",
81 tools=[search_tool],
82 verbose=True,
83 llm="gpt-4.1-mini",
84 )
85
86 planning_task = Task(
87 description="""First, search Zep memory for the user's saved preferences and
88 trip context. Then provide 3 specific hotel recommendations in New York that
89 would be good for a business traveler. Include hotel names and locations, price
90 range per night, why each fits the user's preferences, and any business
91 amenities.""",
92 expected_output="A list of 3 hotel recommendations with detailed explanations",
93 agent=travel_agent,
94 )
95
96 crew = Crew(
97 agents=[travel_agent],
98 tasks=[planning_task],
99 process=Process.sequential,
100 verbose=True,
101 )
102
103 result = crew.kickoff()
104 print(result)
105
106 # Optionally persist the result for future runs
107 user_storage.save(str(result), metadata={"type": "message", "role": "assistant"})
108
109
110if __name__ == "__main__":
111 main()

Best practices

Storage selection

  • Use ZepUserStorage for personal preferences, conversation history, and user-specific context.
  • Use ZepGraphStorage for shared knowledge, organizational data, and collaborative information.

Memory management

  • Set up ontologies for structured graph data, and give every entity class a docstring.
  • Use search filters to target specific node types and improve relevance.
  • Combine storage types for comprehensive memory coverage.

Tool usage

  • Bind tools to a specific user or graph at creation time.
  • Pin or hide search parameters the model should not control with pinned_params and hidden_params.
  • Save data with the right type (message, json, or text) so it routes correctly.
  • Allow time for indexing — Zep extracts knowledge asynchronously, so facts from a turn are not instantly searchable.

Next steps