import { ZepClient, Zep } from '@getzep/zep-cloud'; import { LlmRequest, Context, LlmResponse, BaseTool, BaseMemoryService, SearchMemoryRequest, SearchMemoryResponse } from '@google/adk'; import { Content, FunctionDeclaration } from '@google/genai'; /** * Shared types and identity resolution for the Zep ADK integration. * * The ADK `Context` (passed to `beforeModelCallback`) and the tool `Context` * (passed to `BaseTool.processLlmRequest` / `runAsync`) both expose `userId`, * `sessionId`, `userContent`, and a delta-aware session `state`. This module * resolves a Zep identity from those, with optional explicit overrides. */ /** * Session-state keys read when resolving a Zep identity at runtime. * * Set these on the ADK session `state` to attribute persisted messages to * the user or to override the UUIDs derived from the ADK session. The user's * email on the Zep profile is a provisioning concern — pass it to * `createUser`, not session state. */ declare const STATE_KEYS: { /** Overrides the Zep user UUID (defaults to the ADK `userId`). */ readonly userUuid: "zep_user_uuid"; /** Overrides the Zep thread UUID (defaults to the ADK `sessionId`). */ readonly threadUuid: "zep_thread_uuid"; /** The user's first name — anchors the identity node in the graph. */ readonly firstName: "zep_first_name"; /** The user's last name. */ readonly lastName: "zep_last_name"; }; /** * Explicit Zep identity, supplied at construction time. * * Zep v4 addresses a user and a thread by their server-generated UUIDs. A * `userId` or a `threadId` is a name, not an address, so the integration * never accepts one here: resolve the UUID once during provisioning (see * `createUser` / `createThread`) and store it in your own database. * * When `userUuid` / `threadUuid` are provided they take precedence over any * values resolved from the ADK session at runtime. `firstName` and * `lastName` are attached as the author name on persisted messages so the * graph resolves identity. */ interface ZepIdentityOptions { /** Zep user UUID. Defaults to the ADK session `userId`. */ userUuid?: string; /** Zep thread UUID. Defaults to the ADK session `sessionId`. */ threadUuid?: string; /** User's first name. Recommended — used to anchor the user's graph node. */ firstName?: string; /** User's last name. */ lastName?: string; } /** A fully resolved Zep identity for a single turn. */ interface ResolvedIdentity { userUuid: string; threadUuid: string; firstName?: string; lastName?: string; /** Display name used as the `name` on persisted user messages. */ displayName?: string; } /** * Minimal structural view of the ADK `Context` / tool `Context` objects. * * Both `beforeModelCallback`'s `context` and `BaseTool`'s `toolContext` are * instances of ADK's `Context` class. We depend only on the fields we read, * which keeps the integration resilient to unrelated ADK changes. */ interface AdkContextLike { readonly userId: string; readonly sessionId: string; /** * The current ADK invocation id. Stable across the multiple * `beforeModelCallback` / `processLlmRequest` firings of a single * (possibly tool-using) turn, so it keys the same-turn dedup guard. */ readonly invocationId: string; readonly userContent?: Content; readonly state: { get(key: string, defaultValue?: T): T | undefined; }; } /** * Resolve a concrete Zep identity for the current turn. * * Resolution order for each field: * * - **userUuid**: explicit option → `zep_user_uuid` in state → ADK `userId` * - **threadUuid**: explicit option → `zep_thread_uuid` in state → ADK * `sessionId` * - **firstName / lastName**: explicit option → matching state key * * The ADK fallbacks apply only when the application sets the ADK `userId` * and `sessionId` to the Zep UUIDs. When it does not, pass the UUIDs * explicitly or set the state keys. * * @param context The ADK callback or tool context for this turn. * @param options Explicit identity overrides supplied at construction time. * @returns The resolved identity. * @throws {ZepIdentityError} If neither an explicit value, a state key, nor * the ADK session can provide a `userUuid` or `threadUuid`. */ declare function resolveIdentity(context: AdkContextLike, options?: ZepIdentityOptions): ResolvedIdentity; /** * Extract and join the text parts of an ADK `Content` value. * * `Content.parts` may interleave text with non-text parts (images, files, * function calls). Only text parts are returned, joined by spaces. * * @param content The ADK content to read, or `undefined`. * @returns The concatenated text, or `undefined` when there is no text. */ declare function extractText(content: Content | undefined): string | undefined; /** * Minimal logging abstraction. * * The integration logs Zep failures rather than throwing them, so a Zep * outage never crashes the host agent. Callers can supply their own logger; * the default writes to `console`. */ /** Structured logger used throughout the integration. */ interface Logger { debug(message: string, ...args: unknown[]): void; info(message: string, ...args: unknown[]): void; warn(message: string, ...args: unknown[]): void; error(message: string, ...args: unknown[]): void; } /** Default logger backed by `console`, namespaced with a `[zep-adk]` prefix. */ declare const defaultLogger: Logger; /** * Same-turn dedup guard shared by the before- and after-model callbacks (and * the tools). * * This module is internal: it no longer creates Zep users or threads (see * `src/provisioning.ts` for the explicit, out-of-band `createUser` / * `createThread` helpers callers are expected to use before the first turn). * All that remains here is the per-invocation dedup cache that prevents a * tool-using turn — which fires the before-model hook multiple times with * the same `invocationId` — from persisting the same user message more than * once. */ /** * Holds the per-invocation dedup state for user-message persistence. * * A single instance is shared by the before- and after-model callbacks (and * the tools) so the dedup guard is not split-brain across hooks that fire * within the same turn. */ declare class TurnDedup { /** * Same-turn dedup guard. Maps a thread UUID to the `invocationId` of the last * user turn whose message we successfully persisted to that thread. * * Within one ADK turn the before-model hook fires multiple times (tool-use * loops) with the *same* `invocationId`. Comparing it lets us persist the * user message once per invocation without blocking a legitimately repeated * message in a later turn (which carries a new `invocationId`). */ private readonly lastPersistedInvocation; /** * Whether the user message for `invocationId` has already been persisted to * `threadUuid` in the current turn. * * @returns `true` if this (thread, invocation) pair was already persisted and * the caller should skip re-persisting; `false` otherwise. */ alreadyPersisted(threadUuid: string, invocationId: string): boolean; /** * Record that the user message for `invocationId` was persisted to * `threadUuid`. Call this only AFTER `addMessages` succeeds, so a transient * failure never permanently suppresses the message. */ markPersisted(threadUuid: string, invocationId: string): void; } /** * Core persist-and-inject logic shared by `createZepBeforeModelCallback` and * `ZepContextTool`. * * On each turn it: * 1. Extracts the latest user message text. * 2. Resolves the Zep identity (explicit options → session state → ADK IDs). * 3. Persists the user message and retrieves a Context Block — either via a * single `thread.addMessages(returnContext: true)` round-trip (default), * or, when a custom `contextBuilder` is configured, by running * `thread.addMessages` (without `returnContext`) concurrently with the * builder. * 4. Injects the resulting context block into * `llmRequest.config.systemInstruction`, rendered through * `contextTemplate`. * * This function never creates the Zep user or thread. Callers must * provision them out-of-band before the first turn — see * `createUser` / `createThread` in `src/provisioning.ts`. If a persist call * fails with a Zep "not found" error (the user/thread was never * provisioned), a warning is logged naming the fix. * * Every Zep call is wrapped so a failure is logged and the turn proceeds * without injected context — a Zep outage never crashes the agent. */ /** * Default template used to wrap retrieved Zep context before injecting it * into the LLM's system instructions. Rendered via plain string replacement * (`template.split("{context}").join(contextText)`), never `String.prototype * .replace` with a pattern — so context text or a custom template containing * `{`/`}`/`%`/`$` is always safe to inject. * * This exact string is canonical across zep-adk's Python, Go, and TypeScript * implementations — keep them in sync. */ declare const DEFAULT_CONTEXT_TEMPLATE: string; /** * Build the system-instruction snippet that carries the Zep Context Block. * * Exposed for testing and for callers that assemble their own prompt. * * @param contextBlock The Context Block returned by Zep (or produced by a * custom `contextBuilder`). * @param template Template to render `contextBlock` into. Must contain a * literal `{context}` placeholder; ALL occurrences are replaced (matching * Python's `str.replace` semantics). Defaults to * {@link DEFAULT_CONTEXT_TEMPLATE}. * @returns A prompt-ready instruction with `{context}` replaced by * `contextBlock`. */ declare function formatContextInstruction(contextBlock: string, template?: string): string; /** * Input handed to a custom {@link ContextBuilder}. * * Bundling the builder's inputs into a single object (rather than positional * arguments) lets us add fields later without breaking existing builders. */ interface ContextBuilderInput { /** The `ZepClient` in use by the integration. */ zep: ZepClient; /** The resolved Zep user UUID for this turn. */ userUuid: string; /** The resolved Zep thread UUID for this turn. */ threadUuid: string; /** The user's message text for this turn. */ userMessage: string; /** The ADK context for this turn (session state, invocation metadata). */ context: AdkContextLike; /** The outgoing model request. */ llmRequest: LlmRequest; } /** * A custom context builder function. * * Receives a single {@link ContextBuilderInput} and returns the context block * to inject into the LLM prompt (or `undefined`/empty to skip injection). * * Error semantics: if the builder rejects, a warning is logged (lengths / * counts only) and injection is skipped for that turn — it never crashes the * host agent and never prevents message persistence from completing. See * {@link persistAndInject} for the full error-isolation contract between * persistence and the builder. */ type ContextBuilder = (input: ContextBuilderInput) => Promise; /** Options accepted by {@link persistAndInject}. */ interface InjectOptions extends ZepIdentityOptions { /** * Roles to exclude from Zep's knowledge-graph ingestion. The messages are * still stored in the thread and used to contextualize other messages. */ ignoreRoles?: Zep.RoleType[]; /** * An optional async function that builds the context block to inject, * instead of using `thread.addMessages(returnContext: true)`. * * When set, message persistence (`thread.addMessages`, without * `returnContext`) and the builder run **concurrently** for lower latency. * When unset (the default), the tool uses a single * `thread.addMessages(returnContext: true)` round-trip. * * Error isolation: persistence and the builder are isolated from each * other's failure — one raising/rejecting never cancels or masks the * other's result. See {@link persistAndInject} for the full contract. */ contextBuilder?: ContextBuilder; /** * Template used to wrap retrieved context before injecting it into the * LLM's system instructions. Must contain a literal `{context}` * placeholder, replaced with the retrieved context text via plain string * replacement (never a regex or `String.prototype.replace` pattern). * Defaults to {@link DEFAULT_CONTEXT_TEMPLATE}. */ contextTemplate?: string; } /** * Persist the latest user message to Zep and inject a Context Block into the * outgoing LLM request. * * This is the single implementation behind both the `beforeModelCallback` and * `ZepContextTool`. It never throws on a Zep error. * * By default, persistence and context retrieval happen in a single * `thread.addMessages(returnContext: true)` round-trip. When * `options.contextBuilder` is set, persistence (`thread.addMessages`, without * `returnContext`) and the builder run **concurrently** instead — each is * isolated from the other's failure (`Promise.allSettled` semantics): * * - If the builder rejects, a warning is logged and injection is skipped for * this turn — but persistence still completes and the turn is marked as * persisted (dedup) on success. * - If persistence rejects, a warning is logged and the turn is **not** * marked as persisted (so it can be retried on the next invocation) — but a * successful builder result may still be injected into the prompt. * * @returns The injected Context Block, or `undefined` if nothing was injected * (no user text, identity unresolved, builder skipped, or a Zep failure). */ declare function persistAndInject(params: { zep: ZepClient; dedup: TurnDedup; logger: Logger; context: AdkContextLike; llmRequest: LlmRequest; options: InjectOptions; }): Promise; /** * `createZepBeforeModelCallback` — the primary Zep integration for Google ADK. * * Returns a function compatible with ADK's `beforeModelCallback` on * `LlmAgentConfig`. On every model call it persists the latest user message to * Zep and injects the retrieved Context Block into the system instruction. * It always returns `undefined` so the (mutated) request proceeds to the model. */ /** Options for {@link createZepBeforeModelCallback}. */ interface ZepBeforeModelCallbackOptions extends ZepIdentityOptions { /** * Roles to exclude from Zep's knowledge-graph ingestion. Messages are still * stored in the thread and used to contextualize other messages. A common * value is `["assistant"]`. */ ignoreRoles?: Zep.RoleType[]; /** Logger for Zep failures. Defaults to a `console`-backed logger. */ logger?: Logger; /** * Same-turn dedup guard. Prevents this callback from re-persisting the same * user message when ADK re-invokes `beforeModelCallback` multiple times * within one turn (tool-use loops). The after-model callback has no dedup * guard of its own — it doesn't need one, since it only ever sees one final * (non-partial, non-function-call) response per turn. Defaults to a * callback-local `TurnDedup` instance if omitted. {@link createZepCallbacks} * creates and wires one automatically. */ dedup?: TurnDedup; /** * An optional async function that builds the context block to inject, * instead of the default `thread.addMessages(returnContext: true)` * round-trip. When set, persistence and the builder run concurrently. See * `persistAndInject` in `src/inject.ts` for the full error-isolation * contract. */ contextBuilder?: ContextBuilder; /** * Template used to wrap retrieved context before injecting it into the * LLM's system instructions. Must contain a literal `{context}` * placeholder. Defaults to `DEFAULT_CONTEXT_TEMPLATE`. */ contextTemplate?: string; } /** * The shape of the function returned by {@link createZepBeforeModelCallback}, * matching ADK's `SingleBeforeModelCallback`. */ type ZepBeforeModelCallback = (params: { context: Context; request: LlmRequest; }) => Promise; /** * Create a `beforeModelCallback` that wires Zep long-term memory into an ADK * `LlmAgent`. * * Pass the returned function to `new LlmAgent({ ..., beforeModelCallback })`. * On each model call it: * * 1. Persists the latest user message to the Zep thread. * 2. Retrieves the Context Block for the user's graph (single round-trip). * 3. Injects that block into `request.config.systemInstruction`. * * Identity is resolved per turn: explicit `userUuid` / `threadUuid` options * take precedence, then `zep_user_uuid` / `zep_thread_uuid` session-state * keys, then the ADK session's `userId` / `sessionId`. Omitting the UUIDs * lets one callback serve every user in a shared-agent deployment. * * This callback never creates the Zep user or thread. Provision them * out-of-band before the first turn with `createUser()` / `createThread()` * (see `src/provisioning.ts`) — e.g. during account/session onboarding. If * the user/thread do not exist, persistence for that turn is skipped and a * warning is logged. * * @example * ```ts * import { LlmAgent } from "@google/adk"; * import { ZepClient } from "@getzep/zep-cloud"; * import { createZepBeforeModelCallback } from "@getzep/zep-adk"; * * const zep = new ZepClient({ apiKey: process.env.ZEP_API_KEY! }); * const agent = new LlmAgent({ * name: "memory_agent", * model: "gemini-2.5-flash", * instruction: "You are a helpful assistant with long-term memory.", * beforeModelCallback: createZepBeforeModelCallback(zep, { * userUuid, * threadUuid, * firstName: "Jane", * lastName: "Smith", * }), * }); * ``` * * @param zep An initialised `ZepClient`. The integration never closes it — the * caller owns its lifecycle. * @param options Identity overrides and behaviour flags. * @returns An async `beforeModelCallback` that always resolves to `undefined` * (the model call proceeds with the mutated request). */ declare function createZepBeforeModelCallback(zep: ZepClient, options?: ZepBeforeModelCallbackOptions): ZepBeforeModelCallback; /** * `createZepAfterModelCallback` — persists assistant responses to Zep. * * Pair it with `createZepBeforeModelCallback` (or `ZepContextTool`) so both * sides of the conversation reach the user's graph. Returns a function * compatible with ADK's `afterModelCallback` on `LlmAgentConfig`. */ /** Options for {@link createZepAfterModelCallback}. */ interface ZepAfterModelCallbackOptions extends ZepIdentityOptions { /** Display name for the assistant in Zep messages. Defaults to `"Assistant"`. */ assistantName?: string; /** * Roles to exclude from Zep's knowledge-graph ingestion. Passed through to * `thread.addMessages`. */ ignoreRoles?: Zep.RoleType[]; /** Logger for Zep failures. Defaults to a `console`-backed logger. */ logger?: Logger; } /** * The shape of the function returned by {@link createZepAfterModelCallback}, * matching ADK's `SingleAfterModelCallback`. */ type ZepAfterModelCallback = (params: { context: Context; response: LlmResponse; }) => Promise; /** * Create an `afterModelCallback` that persists the assistant's response text to * the Zep thread. * * Intermediate responses that carry tool calls (the model's "thinking" turns) * are skipped, so only one clean assistant message per turn reaches Zep. * * This callback never creates the Zep user or thread. Provision them * out-of-band before the first turn with `createUser()` / `createThread()` * (see `src/provisioning.ts`) — e.g. during account/session onboarding. If * the user/thread do not exist, persistence for that turn is skipped and a * warning is logged naming the fix. * * @param zep An initialised `ZepClient`. The caller owns its lifecycle. * @param options Identity overrides and behaviour flags. * @returns An async `afterModelCallback` that always resolves to `undefined` * (the response passes through unmodified). */ declare function createZepAfterModelCallback(zep: ZepClient, options?: ZepAfterModelCallbackOptions): ZepAfterModelCallback; /** * `createZepCallbacks` — build a paired before- and after-model callback that * share a single {@link TurnDedup} guard. * * Wiring both callbacks through one guard keeps their same-turn dedup state in * sync, so they are not split-brain: the user turn is persisted exactly once * per invocation even when both hooks run. */ /** Options for {@link createZepCallbacks}. */ interface ZepCallbacksOptions extends ZepBeforeModelCallbackOptions, ZepAfterModelCallbackOptions { } /** The pair of callbacks returned by {@link createZepCallbacks}. */ interface ZepCallbacks { /** Wire into `LlmAgent.beforeModelCallback`. */ beforeModelCallback: ZepBeforeModelCallback; /** Wire into `LlmAgent.afterModelCallback`. */ afterModelCallback: ZepAfterModelCallback; /** The shared same-turn dedup guard backing both callbacks. */ dedup: TurnDedup; } /** * Create the before- and after-model callbacks together, backed by one shared * {@link TurnDedup} guard. * * Prefer this over constructing the two callbacks independently: a shared * guard means the same-turn dedup state is consistent across both hooks. * * @example * ```ts * import { LlmAgent } from "@google/adk"; * import { ZepClient } from "@getzep/zep-cloud"; * import { createZepCallbacks } from "@getzep/zep-adk"; * * const zep = new ZepClient({ apiKey: process.env.ZEP_API_KEY! }); * const { beforeModelCallback, afterModelCallback } = createZepCallbacks(zep, { * userUuid, * threadUuid, * }); * const agent = new LlmAgent({ * name: "memory_agent", * model: "gemini-2.5-flash", * instruction: "You are a helpful assistant with long-term memory.", * beforeModelCallback, * afterModelCallback, * }); * ``` * * @param zep An initialised `ZepClient`. The caller owns its lifecycle. * @param options Identity overrides and behaviour flags shared by both hooks. * @returns The paired callbacks and the shared dedup guard. */ declare function createZepCallbacks(zep: ZepClient, options?: ZepCallbacksOptions): ZepCallbacks; /** * `ZepContextTool` — a tool-centric alternative to * `createZepBeforeModelCallback`. * * It subclasses ADK's `BaseTool` and overrides `processLlmRequest`, the hook * ADK's own `PreloadMemoryTool` uses. The tool is never *called* by the model * (`_getDeclaration` returns `undefined`, `runAsync` is a no-op); instead it * preprocesses each outgoing LLM request to persist the user message and inject * the Zep Context Block. * * Use this when you prefer to compose memory as a tool in `LlmAgent.tools` * rather than wiring `beforeModelCallback`. Pick one or the other — running * both would persist each user message twice. */ /** Options for the {@link ZepContextTool} constructor. */ interface ZepContextToolOptions extends ZepIdentityOptions { /** An initialised `ZepClient`. The caller owns its lifecycle. */ zep: ZepClient; /** * Roles to exclude from Zep's knowledge-graph ingestion. Messages are still * stored in the thread and used to contextualize other messages. */ ignoreRoles?: Zep.RoleType[]; /** Tool name. Defaults to `"zep_context"`. */ name?: string; /** Tool description. Defaults to a short summary. */ description?: string; /** Logger for Zep failures. Defaults to a `console`-backed logger. */ logger?: Logger; /** * An optional async function that builds the context block to inject, * instead of the default `thread.addMessages(returnContext: true)` * round-trip. When set, persistence and the builder run concurrently. See * `persistAndInject` in `src/inject.ts` for the full error-isolation * contract. */ contextBuilder?: ContextBuilder; /** * Template used to wrap retrieved context before injecting it into the * LLM's system instructions. Must contain a literal `{context}` * placeholder. Defaults to `DEFAULT_CONTEXT_TEMPLATE`. */ contextTemplate?: string; } /** * An ADK `BaseTool` that injects Zep long-term memory into every LLM request. * * @example * ```ts * import { LlmAgent } from "@google/adk"; * import { ZepClient } from "@getzep/zep-cloud"; * import { ZepContextTool } from "@getzep/zep-adk"; * * const zep = new ZepClient({ apiKey: process.env.ZEP_API_KEY! }); * const agent = new LlmAgent({ * name: "memory_agent", * model: "gemini-2.5-flash", * instruction: "You are a helpful assistant with long-term memory.", * tools: [new ZepContextTool({ zep, userUuid, threadUuid })], * }); * ``` */ declare class ZepContextTool extends BaseTool { private readonly zep; private readonly logger; private readonly dedup; private readonly ignoreRoles?; private readonly identity; private readonly contextBuilder?; private readonly contextTemplate?; constructor(options: ZepContextToolOptions); /** * The tool is not model-callable, so it exposes no function declaration. * * Returning `undefined` keeps it out of the model's tool list while still * letting ADK invoke {@link ZepContextTool.processLlmRequest}. */ _getDeclaration(): FunctionDeclaration | undefined; /** * No-op: the tool is never invoked by the model. All work happens in * {@link ZepContextTool.processLlmRequest}. */ runAsync(): Promise; /** * Persist the latest user message to Zep and inject the Context Block into * the outgoing request's system instruction. * * Called by ADK before each LLM request. Never throws on a Zep error. */ processLlmRequest({ toolContext, llmRequest, }: { toolContext: Context; llmRequest: LlmRequest; }): Promise; } /** * `ZepGraphSearchTool` — a model-callable ADK tool for searching a Zep * knowledge graph on demand. * * Unlike `ZepContextTool` (which injects context automatically on every turn), * this tool appears in the model's tool list and is called when the model * decides it needs to look something up. * * Search target resolution: * - If `graphUuid` is set, every search targets that graph. * - Otherwise the graph of the current user is searched. The tool resolves * the user UUID from explicit options → `zep_user_uuid` state key → the * ADK `userId`, then reads the graph UUID of that user with * `user.get(userUuid)` and caches it for the life of the tool. * * ## Pin-or-expose parameter model * * Every search knob (`scope`, `reranker`, `limit`, `mmrLambda`, * `centerNodeUuid`) is **tri-state** at construction time: * * - **Concrete value** (e.g. `scope: "edges"`) → *pinned*. Hidden from the * model's tool schema and always used, regardless of what the model sends. * - **`null`** → *hidden*. Hidden from the model's tool schema AND omitted * from the search call entirely (useful for suppressing optional params, * e.g. `mmrLambda: null` when the reranker is never `"mmr"`). * - **`undefined` / omitted** → *exposed*. Included in the model's tool * schema with the documented default, so the model can choose a value. * * `searchFilters` and `bfsOriginNodeUuids` are always constructor-only — they * are never exposed to the model and, when set, are always applied. */ /** * The search scopes of the tool. * * Zep v4 has one search method for each scope, so the SDK no longer exports * a scope enum. The tool keeps the scope as its own parameter and calls the * matching v4 method. */ type ZepGraphSearchScope = "edges" | "nodes" | "episodes" | "observations" | "thread_summaries" | "auto"; type Reranker = Zep.SearchEdgesRequestReranker; /** Options for the {@link ZepGraphSearchTool} constructor. */ interface ZepGraphSearchToolOptions extends ZepIdentityOptions { /** An initialised `ZepClient`. The caller owns its lifecycle. */ zep: ZepClient; /** * Fixed graph UUID. When set, all searches target this graph regardless of * the active user. When omitted, the tool reads the graph UUID of the * resolved user from Zep and searches that graph. */ graphUuid?: string; /** Tool name shown to the model. Defaults to `"zep_graph_search"`. */ name?: string; /** Tool description shown to the model. */ description?: string; /** * Search scope: `"edges"` for facts and relationships, `"nodes"` for * entities and their summaries, `"episodes"` for raw text data * (unstructured text, messages, or JSON), `"observations"` for derived * memories, `"thread_summaries"` for incremental thread summaries, `"auto"` * to let Zep decide the best mix of results. * * Tri-state: a concrete value pins the scope (hidden from the model, * always used); `null` hides it AND omits it from the search call; * `undefined`/omitted exposes it to the model, defaulting to `"edges"`. */ scope?: ZepGraphSearchScope | null; /** * Result ordering algorithm: `"rrf"` (balanced), `"mmr"` (diverse), * `"cross_encoder"` (highest accuracy), `"episode_mentions"` (frequently * referenced), `"node_distance"` (near a specific entity). * * Each scope accepts only some rerankers: `edges` accepts all five, * `nodes` accepts all except `"episode_mentions"`, `episodes` accepts * `"rrf"` and `"mmr"`, and `observations` and `thread_summaries` accept * `"rrf"`, `"mmr"`, and `"cross_encoder"`. `"node_distance"` requires a * `centerNodeUuid`, and `"episode_mentions"` requires * `searchFilters.episodeUuids`. The constructor throws for a pinned value * that cannot work with the other pinned options. * * Tri-state: a concrete value pins the reranker (hidden from the model, * always used); `null` hides it AND omits it from the search call; * `undefined`/omitted exposes it to the model with no default: when the * model sends no reranker, the tool sends no reranker and Zep uses its * default ordering (`"rrf"`). The exposed list contains only the * rerankers that the tool can use. * * The `"auto"` scope takes no reranker. The constructor throws when * `scope` is pinned to `"auto"` and a reranker is pinned, and the tool * returns an error message when the model sends a reranker with * `"auto"`. */ reranker?: Reranker | null; /** * Maximum number of results to return. * * Tri-state: a concrete value pins the limit (hidden from the model, * always used); `null` hides it AND omits it from the search call; * `undefined`/omitted exposes it to the model, defaulting to `10`. */ limit?: number | null; /** * Balance between diversity (`0.0`) and relevance (`1.0`). Only used when * `reranker` is `"mmr"`. Zep requires it for `"mmr"`, so the tool sends * {@link DEFAULT_MMR_LAMBDA} when the reranker is `"mmr"` and no value is * set. * * Tri-state: a concrete value pins `mmrLambda` (hidden from the model, * always used); `null` hides it AND omits it from the search call, which * also removes `"mmr"` from the rerankers that the tool can use; * `undefined`/omitted exposes it to the model. */ mmrLambda?: number | null; /** * UUID of the center node for distance-based reranking. Required when * `reranker` is `"node_distance"`. * * Tri-state: a concrete value pins `centerNodeUuid` (hidden from the * model, always used); `null` hides it AND omits it from the search call; * `undefined`/omitted exposes it to the model with no default. */ centerNodeUuid?: string | null; /** * Search filters to apply (`nodeLabels`, `edgeTypes`, * `excludeNodeLabels`, `excludeEdgeTypes`, property filters, etc.). * Constructor-only — never exposed to the model. Always applied when set. */ searchFilters?: Zep.SearchFilters; /** * Node UUIDs seeding a breadth-first search. Constructor-only — never * exposed to the model. Always applied when set. */ bfsOriginNodeUuids?: string[]; /** Logger for Zep failures and invalid-argument warnings. Defaults to a `console`-backed logger. */ logger?: Logger; } /** * A model-callable tool that searches a Zep knowledge graph. * * Every search parameter (`scope`, `reranker`, `limit`, `mmrLambda`, * `centerNodeUuid`) can be pinned, hidden, or exposed to the model — see the * {@link ZepGraphSearchToolOptions} tri-state documentation. Only exposed * parameters appear in the model's tool schema; `query` is always required. * * Errors are returned to the model as text rather than thrown, so a Zep * failure cannot crash the agent run. * * @example * ```ts * import { LlmAgent } from "@google/adk"; * import { ZepClient } from "@getzep/zep-cloud"; * import { ZepGraphSearchTool } from "@getzep/zep-adk"; * * const zep = new ZepClient({ apiKey: process.env.ZEP_API_KEY! }); * const agent = new LlmAgent({ * name: "memory_agent", * model: "gemini-2.5-flash", * instruction: "You are a helpful assistant.", * tools: [new ZepGraphSearchTool({ zep, userUuid })], * }); * ``` * * @example Restoring the old "always pinned" behavior * ```ts * // Model only ever sees `query`; scope/reranker/limit are fixed. * new ZepGraphSearchTool({ * zep, * userUuid, * scope: "edges", * reranker: "rrf", * limit: 10, * mmrLambda: null, * centerNodeUuid: null, * }); * ``` */ declare class ZepGraphSearchTool extends BaseTool { private readonly zep; private readonly logger; private readonly graphUuid?; private readonly identity; private readonly declaration; /** Graph UUID for each resolved user UUID, cached for the life of the tool. */ private readonly graphUuidByUser; private readonly scopeState; private readonly rerankerState; private readonly limitState; private readonly mmrLambdaState; private readonly centerNodeUuidState; private readonly searchFilters?; private readonly bfsOriginNodeUuids?; /** The rerankers that the other options let the tool use, for any scope. */ private readonly usableRerankers; /** The scopes that the model can select. */ private readonly selectableScopes; constructor(options: ZepGraphSearchToolOptions); /** * Returns why the other options prevent the use of a reranker, or * `undefined` when the tool can use it. */ private rerankerUnavailableReason; /** Throws when a pinned reranker cannot work with the other options. */ private validatePinnedReranker; /** The scopes that support the pinned reranker, or every scope. */ private computeSelectableScopes; /** The usable rerankers that a scope accepts. */ private rerankersForScope; /** * The rerankers that the model can select: the usable rerankers that at * least one selectable scope accepts. */ private selectableRerankers; /** * Checks the resolved scope and reranker before the request. Returns an * error message for the model, or `undefined` when the pair is valid. */ private validateSearchSettings; /** * Builds the function declaration from exposed (non-pinned, non-hidden) * parameters only. `query` is always present and required. */ private buildDeclaration; /** Describes each selectable reranker and the scopes that accept it. */ private rerankerDescription; /** Exposes the declaration built from non-pinned, non-hidden parameters. */ _getDeclaration(): FunctionDeclaration; /** * Run the graph search and return formatted results as text for the model. * * Returns a human-readable error string (never throws) when the search * target cannot be resolved or the Zep call fails. */ runAsync(request: { args: Record; toolContext: Context; }): Promise; /** * Resolve an enum-valued parameter: pinned beats model-provided arg beats * default. An invalid model-provided value falls back to the default with * a logged warning rather than throwing. */ private resolveEnum; /** * Resolve the reranker: the pinned value, else the value from the model. * The reranker has no default, so the tool sends no reranker when the * model omits it. A value from the model that is not a reranker gives an * error message for the model. */ private resolveReranker; /** * Resolve a numeric parameter: pinned beats model-provided arg beats * default. A non-numeric model-provided value falls back to the default * (or is omitted, if there is none) with a logged warning. */ private resolveNumber; /** * Resolve a string parameter with no default: pinned beats model-provided * arg beats "unset" (`undefined`, meaning omitted from the SDK call). */ private resolveString; /** * Resolve the UUID of the graph to search. * * A configured `graphUuid` wins. Otherwise the tool resolves the user UUID * of the turn and reads the graph UUID of that user once, then serves * later turns of the same user from its cache. The tool never calls * `user.lookup`: a `userId` name is not an address in v4. */ private resolveGraphUuid; } /** * `ZepMemoryService` — an ADK-native `BaseMemoryService` backed by Zep. * * ADK's memory extension point (`BaseMemoryService`) lets a `Runner` search * long-term memory through a model-opt-in tool (`loadMemory` / * `preloadMemory`): the model decides when to call * `toolContext.searchMemory(query)`, which reaches this service via * `new Runner({ ..., memoryService: new ZepMemoryService(...) })`. * * This is a different extension point from `ZepContextTool` / * `createZepBeforeModelCallback`: * * - **ZepMemoryService** (this module) — ADK-native, model-opt-in. The model * decides, per turn, whether to call `loadMemory`/`preloadMemory`. Use this * when you want the model to actively decide when memory is relevant, or * when wiring into ADK code paths that already expect a `memoryService` * (e.g. ADK's own memory tools, evaluation harnesses). * - **ZepContextTool** / **createZepBeforeModelCallback** — guaranteed * injection. Runs on every LLM turn, so Zep context is always present * regardless of whether the model would have thought to ask for it. Use * this for the common case: an assistant that should always have the * user's long-term context available. * * The two are complementary, not mutually exclusive — e.g. use * `ZepContextTool` for always-on context and additionally register * `ZepMemoryService` so the model can explicitly search for more via * `loadMemory` when it decides the always-on context wasn't enough. * * Why `addSessionToMemory` is a no-op: Zep persistence already happens live, * on every turn, via `ZepContextTool` (or `createZepBeforeModelCallback` / * `createZepAfterModelCallback`, which call `thread.addMessages` directly). * ADK calls `addSessionToMemory` to flush a session's conversation into a * memory store at some point after it happens (e.g. session end); since Zep * already has every message as it's persisted turn-by-turn, doing it again * here would re-ingest the same conversation into the graph a second time. * This mirrors the Go integration's `NewMemoryService` and Python's * `ZepMemoryService`, whose `AddSessionToMemory`/`add_session_to_memory` are * the same intentional no-op for the same reason. */ interface SessionLike { id?: string; } /** Options for the {@link ZepMemoryService} constructor. */ interface ZepMemoryServiceOptions { /** An initialised `ZepClient`. The caller owns its lifecycle. */ zep: ZepClient; /** * Fixed graph UUID. When set, every `searchMemory` call targets this * graph. When omitted, the service reads the graph UUID of the user named * by `SearchMemoryRequest.userId`, which ADK carries from the session. In * Zep v4 that value must be the UUID of the Zep user. */ graphUuid?: string; /** * The Zep graph search scope to use for every `searchMemory` call. * Matches `ZepGraphSearchTool`'s scope enum: `"edges"` (facts, the * default), `"nodes"` (entities and summaries), `"episodes"` (raw * message/data content), `"observations"` (derived memories), * `"thread_summaries"` (incremental thread summaries), or `"auto"` (Zep's * own pre-assembled Context Block, returned as a single memory entry). */ scope?: ZepGraphSearchScope; /** * Maximum number of results per search. `undefined` (the default) omits * the parameter so the Zep SDK applies its own default. */ limit?: number; /** Logger for Zep failures and unsupported-scope warnings. Defaults to a `console`-backed logger. */ logger?: Logger; } /** * ADK-native memory service that searches a user's Zep knowledge graph. * * Register this on a `Runner` to give ADK's built-in memory tooling * (`loadMemory`, `preloadMemory`) access to Zep: * * @example * ```ts * import { Runner, LlmAgent } from "@google/adk"; * import { LOAD_MEMORY } from "@google/adk"; * import { ZepClient } from "@getzep/zep-cloud"; * import { ZepMemoryService } from "@getzep/zep-adk"; * * const zep = new ZepClient({ apiKey: process.env.ZEP_API_KEY! }); * const agent = new LlmAgent({ * name: "memory_agent", * model: "gemini-2.5-flash", * tools: [LOAD_MEMORY], * }); * const runner = new Runner({ * agent, * appName: "my_app", * sessionService, * memoryService: new ZepMemoryService({ zep }), * }); * ``` * * See the module docstring for guidance on when to use this versus * `ZepContextTool` / `createZepBeforeModelCallback`. */ declare class ZepMemoryService implements BaseMemoryService { private readonly zep; private readonly graphUuid?; private readonly scope; private readonly limit?; private readonly logger; /** Graph UUID for each user UUID, cached for the life of the service. */ private readonly graphUuidByUser; constructor(options: ZepMemoryServiceOptions); /** * No-op. See the module docstring for the no-double-persist rationale. * * Conversation turns are already persisted live via `ZepContextTool` (or * `createZepBeforeModelCallback`/`createZepAfterModelCallback`). Ingesting * the session again here would duplicate that work in Zep's graph. */ addSessionToMemory(_session: SessionLike): Promise; /** * Search the user's Zep graph and map results to `MemoryEntry` objects. * * `request.appName` has no Zep equivalent — Zep scopes memory by user * graph, not by application — so it is accepted (to satisfy the ADK * interface) but not forwarded to Zep. * * Zep v4 searches a graph by UUID. The service uses the configured * `graphUuid` when there is one. Otherwise it reads the graph UUID of * `request.userId` with `user.get`, which requires the ADK session to * carry the UUID of the Zep user. The service never calls `user.lookup`. * * On any Zep failure, logs a warning (lengths only, never query or result * content) and returns an empty response rather than throwing, so a * memory lookup never breaks the agent. * * An unsupported scope is rejected before the search is issued: like Go's * `memoryService.SearchMemory` (see `searchScopeSupported` in * `integrations/adk/go/memory.go`) and Python's `ZepMemoryService`, this * avoids spending a live network call on a scope we can never map into * memory entries. */ searchMemory(request: SearchMemoryRequest): Promise; /** Resolve the UUID of the graph to search for a user UUID. */ private resolveGraphUuid; } /** * Explicit, out-of-band Zep resource provisioning. * * The ADK turn path (`persistAndInject`, used by both * `createZepBeforeModelCallback` and `ZepContextTool`) never creates Zep * users or threads — it only persists messages and retrieves context. * Callers are expected to provision the Zep user and thread once, * out-of-band, before the first turn (e.g. during account/session * onboarding), using {@link createUser} and {@link createThread}. * * Zep v4 assigns the UUID of a user, of its graph, and of a thread on the * server, so a create call is not idempotent and there is no "already * exists" conflict to absorb. A v4 create call accepts no client-chosen * name, and a v4 resource has no name. Each helper returns the UUIDs of * the new resource. Store them in your own database and pass them back to the * integration as `userUuid` / `threadUuid`. Every failure (auth, network, * 5xx) throws — out-of-band provisioning is meant to fail loudly so * misconfiguration is caught before the agent ever runs. */ /** * Hook run exactly once, immediately after a Zep user is created. * * Receives the Zep client and the UUID of the new user. Use this to * configure per-user ontology, custom instructions, or user summary * instructions. Awaited before {@link createUser} returns; if it throws, the * exception propagates to the caller even though the user was successfully * created — see {@link CreateUserOptions.onCreated} for the half-provisioned * edge case this implies. */ type UserSetupHook = (zep: ZepClient, userUuid: string) => Promise; /** Options accepted by {@link createUser}. */ interface CreateUserOptions { /** Optional first name, passed through to `zep.user.create`. */ firstName?: string; /** Optional last name, passed through to `zep.user.create`. */ lastName?: string; /** Optional email, passed through to `zep.user.create`. */ email?: string; /** * Runs exactly once after the user is created; awaited before * `createUser` returns; errors propagate. * * **Half-provisioned edge case:** if the user is created but `onCreated` * then throws, the user now exists in Zep but its setup did not complete. * Write `onCreated` to be idempotent (safe to re-run against a user whose * setup only partially completed) and give the caller a separate way to * retry it if needed. */ onCreated?: UserSetupHook; } /** The UUIDs that Zep assigns to a new user. */ interface CreatedUser { /** The UUID of the user. This is the v4 address of the user. */ userUuid: string; /** The UUID of the graph of the user, used for graph search. */ graphUuid?: string; } /** * Create a Zep user and return its server-generated UUIDs. * * When `onCreated` is provided, the hook is awaited (with * `(zep, userUuid)`) **before** this function returns. If the hook throws, * the exception propagates to the caller even though the user was * successfully created — see {@link CreateUserOptions.onCreated}. * * @param zep An initialised `ZepClient`. The integration never closes it — * the caller owns its lifecycle. * @param options User fields and the optional `onCreated` hook. * @returns The UUID of the user and the UUID of its graph. * @throws Any failure from the Zep SDK (auth, network, 5xx), any error * thrown by `onCreated`, or an error when the response carries no UUID. */ declare function createUser(zep: ZepClient, options?: CreateUserOptions): Promise; /** Options accepted by {@link createThread}. */ interface CreateThreadOptions { /** The UUID of the Zep user that owns the thread. */ userUuid: string; } /** The UUIDs that Zep assigns to a new thread. */ interface CreatedThread { /** The UUID of the thread. This is the v4 address of the thread. */ threadUuid: string; /** The UUID of the graph that the thread writes to. */ graphUuid?: string; } /** * Create a Zep thread for a user and return its server-generated UUID. * * @param zep An initialised `ZepClient`. The caller owns its lifecycle. * @param options The UUID of the owning user. * @returns The UUID of the thread and the UUID of the graph it writes to. * @throws Any failure from the Zep SDK (auth, network, 5xx), or an error * when the response carries no UUID. */ declare function createThread(zep: ZepClient, options: CreateThreadOptions): Promise; /** * Zep size-limit handling. * * Zep rejects over-long payloads with a 400: * - A thread message's `content` must be <= 4,096 characters. * - `graph.add` data must be <= 10,000 characters. * * Rather than letting an over-long message 400 and be silently swallowed, we * truncate it (preferring a safety margin under the hard limit) and log a * warning. The warning carries ONLY lengths — never message content — so no * user text or PII reaches the logs. */ /** Hard Zep limit on a thread message's `content`, in characters. */ declare const MESSAGE_CONTENT_MAX = 4096; /** * Target length we truncate over-long messages to. Kept under * {@link MESSAGE_CONTENT_MAX} to leave headroom for any server-side encoding * differences. */ declare const MESSAGE_CONTENT_TRUNCATE_TO = 4000; /** Hard Zep limit on `graph.add` data, in characters. */ declare const GRAPH_DATA_MAX = 10000; /** * Truncate a thread-message content string to Zep's message limit, logging a * warning (lengths only — never content) when truncation happens. * * Content within the limit is returned unchanged. Over-long content is * truncated to {@link MESSAGE_CONTENT_TRUNCATE_TO} characters so the message is * persisted rather than dropped on a 400. * * @param content The message content to bound. * @param logger Logger used for the truncation warning. * @param label A short, non-PII label for the message (e.g. `"user"`, * `"assistant"`) included in the warning to aid debugging. * @returns The original content, or a truncated copy when it exceeds the limit. */ declare function truncateMessageContent(content: string, logger: Logger, label?: string): string; /** * Error types for the Zep Google ADK integration. */ /** * Raised when Zep identity (user ID / thread ID) cannot be resolved from the * ADK callback or tool context. * * This is the only error the integration throws by design. All Zep API * failures are caught internally, logged, and swallowed so that a Zep outage * can never crash the host agent. */ declare class ZepIdentityError extends Error { constructor(message: string); } /** * Zep long-term memory integration for Google ADK (TypeScript). * * Two interchangeable ways to give an ADK `LlmAgent` persistent memory: * * - {@link createZepBeforeModelCallback} — the primary hook. Wire it into * `LlmAgent.beforeModelCallback`; it persists the user message and injects * the Zep Context Block on every turn. * - {@link ZepContextTool} — the same behaviour packaged as a `BaseTool`, for * teams that prefer composing memory through `LlmAgent.tools`. * * Pair either with {@link createZepAfterModelCallback} to persist assistant * responses, and add {@link ZepGraphSearchTool} to let the model search the * graph on demand. * * Before the first turn, provision the Zep user and thread out-of-band with * {@link createUser} and {@link createThread} — the turn path never creates * them itself. Zep v4 addresses a user and a thread by UUID, so store the * UUIDs that the two helpers return and pass them back as `userUuid` and * `threadUuid`. * * On the turn path (callbacks and tools), every Zep call is wrapped: failures * are logged, never thrown, so a Zep outage cannot crash the host agent. The * out-of-band provisioning helpers ({@link createUser}, {@link createThread}) * are the deliberate exception — they throw on genuine failures so * misconfiguration is caught before the agent runs. * * @packageDocumentation */ /** The installed package version. */ declare const VERSION = "1.0.0"; export { type AdkContextLike, type ContextBuilder, type ContextBuilderInput, type CreateThreadOptions, type CreateUserOptions, type CreatedThread, type CreatedUser, DEFAULT_CONTEXT_TEMPLATE, GRAPH_DATA_MAX, type InjectOptions, type Logger, MESSAGE_CONTENT_MAX, MESSAGE_CONTENT_TRUNCATE_TO, type ResolvedIdentity, STATE_KEYS, TurnDedup, type UserSetupHook, VERSION, type ZepAfterModelCallback, type ZepAfterModelCallbackOptions, type ZepBeforeModelCallback, type ZepBeforeModelCallbackOptions, type ZepCallbacks, type ZepCallbacksOptions, ZepContextTool, type ZepContextToolOptions, type ZepGraphSearchScope, ZepGraphSearchTool, type ZepGraphSearchToolOptions, ZepIdentityError, type ZepIdentityOptions, ZepMemoryService, type ZepMemoryServiceOptions, createThread, createUser, createZepAfterModelCallback, createZepBeforeModelCallback, createZepCallbacks, defaultLogger, extractText, formatContextInstruction, persistAndInject, resolveIdentity, truncateMessageContent };