Google ADK integration
Google’s Agent Development Kit (ADK) agents equipped with Zep’s context layer can maintain context across conversations and access personalized knowledge graphs. The zep-adk package provides real-time message persistence and automatic context injection for ADK agents, and ships for Python, TypeScript, and Go.
Core benefits
- Zero restructuring: Add Zep to an existing ADK agent without changing your agent architecture
- Shared-agent architecture: One
Agentdefinition serves all users. Per-user identity is resolved at runtime from ADK session state - Real-time persistence: Both user and assistant messages are persisted to Zep on every turn, not batched at session end
- Automatic context injection: Zep’s context block — facts, relationships, and prior knowledge — is injected into the LLM prompt before each response
- Explicit provisioning: Idempotent helpers create Zep users and threads once, out of band, before the first turn
- ADK-native memory service: Zep backs ADK’s built-in
load_memory/preload_memorytools through aBaseMemoryServiceimplementation
How it works
The integration hooks into ADK’s agent lifecycle to persist the user’s message and inject relevant context before each model call, then persist the assistant’s reply afterward. Each language exposes the same capabilities through its idiomatic ADK extension points:
In Python and TypeScript, ZepContextTool is a BaseTool that hooks ADK’s process_llm_request() lifecycle method — the same hook ADK’s own PreloadMemoryTool uses — and is never called by the model directly. In TypeScript, use either createZepBeforeModelCallback or ZepContextTool, not both: running both persists each user message twice. Go intentionally has no tool-based injection — callbacks are the idiomatic Go ADK hook.
On each turn the context hook resolves the user’s Zep identity, persists the user’s message, retrieves the relevant context block, and injects it into the model’s system instruction. Tool-loop continuations are skipped, so a turn is recorded in Zep exactly once. The turn path assumes the Zep user and thread already exist — provision them with the ensure_user/ensure_thread helpers before the first turn (see Provisioning users and threads). If persistence targets a user or thread that doesn’t exist, a warning naming the helpers is logged and the turn continues without Zep memory.
What gets persisted
Only the user’s message and the model’s final response are persisted to Zep on each turn. Intermediate model outputs — such as “thinking” text emitted alongside a tool call (e.g. “Let me look that up for you.”) — are not persisted. Tool calls and tool results are also excluded. This keeps the Zep thread clean: one user message and one assistant message per turn, reflecting the actual conversation rather than internal agent mechanics.
If the user message contains multiple text parts (e.g. text alongside an image), all text parts are joined. Non-text parts (images, files) are ignored — only text is sent to Zep. The Zep API rejects thread messages over 4,096 characters; the ADK integration truncates longer messages before persisting rather than dropping the turn.
Installation
Requires a Zep Cloud API key — get yours from app.getzep.com — plus the ADK runtime for your language: Python 3.11+ with google-adk>=1.19.0,<3 and zep-cloud>=3.23.0, Node.js 20+ with @google/adk (a ^1.2.0 peer dependency), or Go 1.25+ with google.golang.org/adk v1.4.0. The Go package is imported as zepadk "github.com/getzep/zep/integrations/adk/go".
Set up your Zep API key and Google API key:
Upgrading from earlier versions
Versions zep-adk 0.3.0 (Python), @getzep/zep-adk 0.2.0 (TypeScript), and zepadk 0.2.0 (Go) replaced lazy in-band resource creation with explicit provisioning. If you’re upgrading:
- Python: The
on_user_createdconstructor argument onZepContextToolis removed — pass the hook asensure_user(..., on_created=...). - Python:
ContextBuildertakes a singleContextInputargument instead of four positional arguments. - TypeScript:
ZepResourceManageris removed — usecreateZepCallbacks, or share aTurnDedupinstance via thededupoption. - Go:
EnsureUser/EnsureThreadreturn(created bool, err error)instead oferror. - All languages: The
zep_emailsession-state key is removed — passemailtoensure_user/ensureUser/EnsureUser.
For the full list of changes, see the package CHANGELOGs in the zep-adk repository.
Adding Zep to an agent
Whether you’re building a new agent or adding Zep to an existing one, the setup is the same: provision the Zep user and thread out of band, then wire up the context hook and the after-model callback. The Python example below shows the full runner flow; the TypeScript and Go tabs show the equivalent wiring.
That’s it. Every user message is persisted to Zep, relevant context is injected into the LLM prompt, and assistant responses are captured — all automatically.
The ignore_roles parameter shown above excludes specific message roles from graph ingestion while still storing them in the thread history. This is useful when assistant messages don’t add meaningful knowledge to the graph — they’re preserved for conversation context but don’t create nodes or edges. Both ZepContextTool and create_after_model_callback accept ignore_roles (TypeScript: ignoreRoles). See Ignore assistant messages in the Zep docs for more detail.
Provisioning users and threads
ensure_user and ensure_thread (TypeScript: ensureUser/ensureThread, Go: EnsureUser/EnsureThread) are explicit, idempotent provisioning helpers. Call them once — during onboarding, account creation, or before the first turn of a new conversation — before the agent runs. Each calls the Zep SDK’s create method directly and reports whether the resource was newly created: Python and TypeScript return True/true for a new resource and False/false for one that already existed; Go returns (created bool, err error). An “already exists” conflict is treated as success. Genuine failures (auth, network, 5xx) raise, so misconfiguration is caught immediately rather than silently swallowed.
Two error philosophies apply, by design:
- Provisioning fails loudly.
ensure_user/ensure_threadraise on genuine failures, so a misconfigured API key or network problem surfaces before the agent ever runs. - The turn path degrades gracefully. The callbacks and tools never raise a Zep error into the agent — failures are logged and the turn continues without Zep memory. If a persist call targets a user or thread that was never provisioned, the logged warning names
ensure_user/ensure_thread.
Pass the user’s email to ensure_user — the name and email on the Zep user profile are set at provisioning time, not through session state.
Identity and session state
The integration maps ADK session metadata to Zep automatically: user_id becomes the Zep user ID, and session_id becomes the Zep thread ID. Zep’s knowledge graph is per-user, not per-thread — it accumulates knowledge across all of a user’s conversations, so when they start a new session they get context from everything Zep has learned about them.
The following session state keys are recognized (all optional):
Identity resolves by precedence: explicit construction options (userId/threadId) take precedence over the zep_user_id/zep_thread_id session-state keys, which in turn take precedence over the ADK user_id/session_id.
Advanced usage
Per-user setup
When ensure_user creates a genuinely new user, an optional hook runs exactly once — the place to configure per-user resources such as a custom ontology, custom extraction instructions, or user summary instructions. Pass the hook as on_created (TypeScript: onCreated); in Go, branch on the created bool that EnsureUser returns.
The hook fires only when the user is genuinely new — not for users that already exist. If the hook raises an exception, the exception propagates; the user was still created, so retrying ensure_user will not re-run the hook. Keep the hook idempotent and re-run its logic directly to recover from a partial failure.
See custom ontology, custom instructions, and user summary instructions for details on each API.
Custom context builder
By default, the integration uses thread.add_messages(return_context=True) — a single API call that persists the message and retrieves context. This works well for most use cases.
For advanced scenarios — multi-graph searches, custom filtering, or combining multiple Zep API calls — you can provide a context builder: context_builder on ZepContextTool (Python), contextBuilder on createZepBeforeModelCallback, ZepContextTool, or createZepCallbacks (TypeScript), or WithContextBuilder on NewBeforeModelCallback (Go). The builder receives a single input object bundling everything it needs.
When a builder is set, message persistence and context building run concurrently for lower latency, and each is isolated from the other’s failure: if the builder fails, a warning is logged and injection is skipped, but persistence still completes; if persistence fails, the turn is not marked as persisted (so it can be retried), but a successful builder result may still be injected. Return None (TypeScript: undefined) from the builder to skip injection for that turn without affecting persistence.
The Python type signatures (both importable from zep_adk):
TypeScript exports the equivalent ContextBuilder and ContextBuilderInput types; Go’s builder is func(ctx context.Context, in zepadk.ContextInput) (string, error).
See advanced context block construction and context templates for more on assembling custom context.
Injection template
The retrieved (or built) context block is wrapped in a template before it is injected into the system instruction. The default — DEFAULT_CONTEXT_TEMPLATE (Python and TypeScript) or DefaultContextTemplate (Go) — introduces the context and wraps it in <ZEP_CONTEXT> tags; the wording is identical across all three languages. Override it with context_template / contextTemplate / WithContextTemplate:
The template must contain a literal {context} placeholder. It is rendered by plain string replacement — never str.format or another format-string engine — so templates and context text containing {, }, %, or $ are always safe to inject. In Go, WithContextPrefix is deprecated in favor of WithContextTemplate.
Graph search tool
ZepContextTool injects context automatically on every turn. For cases where the model needs to actively search the knowledge graph — e.g. looking up specific facts, entities, or prior messages — you can add ZepGraphSearchTool (Go: NewGraphSearchTool). This is a model-callable tool: the model sees it in its tool list and decides when to invoke it.
The tool automatically resolves the user identity from session state, so the model only needs to provide a search query. Unless pinned, the model can also choose the scope (edges, nodes, episodes, observations, thread_summaries, auto), the reranker (rrf, mmr, node_distance, episode_mentions, cross_encoder), limit, mmr_lambda, and center_node_uuid — see search parameters.
Pinning and hiding parameters
Every search parameter is independently in one of three states at construction time:
Defaults when exposed: scope="edges", reranker="rrf", limit=10; mmr_lambda and center_node_uuid have no default and are omitted unless the model supplies one. search_filters and bfs_origin_node_uuids (TypeScript: searchFilters/bfsOriginNodeUuids, Go: WithToolSearchFilters/WithToolBFSOriginNodeUUIDs) are always constructor-only — never exposed to the model, always applied to every search when set.
An invalid enum value sent by the model never reaches Zep and never crashes the agent: TypeScript falls back to the documented default and logs a warning; Go rejects it through ADK’s schema validation and surfaces a tool error the model can correct on its next call.
Shared documentation graph
To search a fixed graph that all users share (e.g. a documentation knowledge base), pass graph_id. The tool will search that graph instead of the current user’s personal graph. Use distinct name and description values when combining multiple instances:
The model sees two distinct tools and chooses which to call based on the user’s query.
Memory service
All three packages implement ADK’s native memory extension point: ZepMemoryService (Python and TypeScript) implements BaseMemoryService, and NewMemoryService (Go) returns an ADK memory.Service. Registered on the Runner, it lets ADK’s built-in load_memory/preload_memory tools (Go: ToolContext.SearchMemory) search the calling user’s Zep graph whenever the model decides memory is relevant.
The two extension points are complementary: ZepContextTool (or the before-model callback) guarantees injection — it runs on every turn regardless of what the model decides. The memory service is model-opt-in — the model decides, per turn, whether to call load_memory. Pair them: keep the context tool for always-on context, and add the memory service when you also want the model to dig further on demand, or when integrating with ADK code paths that expect a memory service (e.g. evaluation harnesses).
Each memory search runs graph.search against the calling user’s graph with a configurable scope — the same six scopes as the graph search tool (edges, nodes, episodes, observations, thread_summaries, auto) — and maps each result into an ADK memory entry. A Zep failure is logged and returns an empty result rather than raising into the agent, so a memory lookup can never break a turn.
add_session_to_memory (TypeScript: addSessionToMemory) is a deliberate no-op: Zep already ingests each turn live via the context tool and after-model callback, so flushing the full session again would persist the same conversation into the graph twice.
In TypeScript, the memory service requires the full Runner, not InMemoryRunner — only Runner’s RunnerConfig accepts a memoryService option. Wiring Runner directly means providing a sessionService yourself; an InMemorySessionService works for development.
Backfill strategy for existing users
If you have existing users with conversation history, you can backfill their data into Zep so they get rich context from day one. Use direct thread.add_messages calls for small or session-scale imports. For large historical imports, use the Batch API with thread_message items so Zep can process the backfill as an asynchronous job.
ID matching
Use the same user IDs and thread IDs. The backfill script must create Zep users and threads with the exact same IDs used in ADK:
- User IDs must match what you pass as
user_idto ADK’screate_session(). This links live sessions to the correct knowledge graph. Mismatched user IDs mean backfilled history is orphaned. - Thread IDs must match the ADK
session_idfor each conversation. If a user continues an existing session after cutover, the integration uses that session ID as the Zep thread ID. If the backfill used a different thread ID, the conversation history is split — the continued thread won’t see the backfilled messages in its thread context.
Example small backfill script
This runs outside of ADK as a standalone script using the Zep Python SDK directly, with zep-adk’s idempotent provisioning helpers. It keeps each thread.add_messages call within Zep’s limits: at most 30 messages per request, and below the 4,096-character hard limit per message. The sample uses a 4,000-character safety margin, matching the other integration examples. Map source-system roles to Zep’s canonical roles before sending: user, assistant, system, function, tool, or norole.
After backfilling, allow time for Zep to process the messages and build knowledge graphs. Zep processes messages asynchronously — the graph won’t be available instantly. For large backfills, prefer the Batch API over manual sleeps and direct SDK loops.
Transition gap
There is a window between when the backfill runs and when the Zep-integrated agent goes live. Any messages sent to existing threads during this window won’t be in Zep. For most use cases this is acceptable — the knowledge graph catches up quickly once the agent is live. But if thread-level continuity is critical, consider a dual-write period: after the backfill completes but before full cutover, have your application write new messages to Zep (via the SDK directly) alongside the existing system. This ensures no messages are missed in the transition.
Cutover checklist
- Run the backfill script — Zep now has knowledge graphs for existing users
- Update your agent — Add
ZepContextTooland the after-model callback - Add session state keys — Include
zep_first_nameandzep_last_nameincreate_session()calls - Provision at onboarding — Call
ensure_user(including the user’s email) andensure_threadin your app’s onboarding or session-creation code, before the first turn of every conversation - Deploy — Existing users get rich context from their first message; new users build context over time
Next steps
- Explore customizing graph structure for advanced knowledge organization
- Learn about searching the graph for direct graph queries and how to tune search
- See the Zep Python SDK reference for all available API methods