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

# Google ADK

> Integrate Memvid with Google Agent Development Kit

Integrate Memvid with Google's Agent Development Kit (ADK) to build Gemini-powered agents with persistent memory. The `google-adk` adapter provides native ADK function declarations.

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

    ```bash theme={null}
    npm install @memvid/sdk @google/generative-ai
    ```

    ## Quick Start

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

    // Open with Google ADK adapter
    const mem = await use('google-adk', 'knowledge.mv2');

    // Access ADK function declarations
    const tools = mem.tools;       // FunctionDeclaration[] for Gemini API
    const executors = mem.functions; // Function executors by name
    ```

    ## Available Functions

    The Google ADK adapter provides three function declarations:

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

    ## Basic Usage with Gemini

    ```typescript theme={null}
    import { use } from '@memvid/sdk';
    import { GoogleGenerativeAI } from '@google/generative-ai';

    // Initialize Memvid with Google ADK adapter
    const mem = await use('google-adk', 'knowledge.mv2');

    // Get function declarations and executors
    const tools = mem.tools as any[];
    const executors = mem.functions as Record<string, (args: any) => Promise<string>>;

    // Create Gemini client
    const geminiKey = process.env.GEMINI_API_KEY ?? process.env.GOOGLE_API_KEY;
    if (!geminiKey) throw new Error("Set GEMINI_API_KEY (or legacy GOOGLE_API_KEY)");
    const genAI = new GoogleGenerativeAI(geminiKey);

    // Create model with Memvid tools
    const model = genAI.getGenerativeModel({
      model: 'gemini-2.0-flash',
      tools: [{ functionDeclarations: tools }],
    });

    // Start a chat
    const chat = model.startChat();
    const result = await chat.sendMessage('Search for authentication information');

    // Handle function calls
    const response = result.response;
    const parts = response.candidates?.[0]?.content?.parts || [];

    for (const part of parts) {
      if (part.functionCall) {
        const { name, args } = part.functionCall;
        console.log(`Function call: ${name}`);

        // Execute the function
        if (executors[name]) {
          const funcResult = await executors[name](args as Record<string, unknown>);
          console.log(`Result: ${funcResult}`);

          // Send result back to model
          const followUp = await chat.sendMessage([{
            functionResponse: {
              name,
              response: { result: funcResult },
            },
          }]);
          console.log(`Model response: ${followUp.response.text()}`);
        }
      } else if (part.text) {
        console.log(`Response: ${part.text}`);
      }
    }
    ```

    ## Direct Tool Execution

    Use the function executors directly without Gemini:

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

    const mem = await use('google-adk', 'knowledge.mv2', { mode: 'create' });
    const executors = mem.functions as Record<string, (args: any) => Promise<string>>;

    // Store documents
    const putResult = await executors.memvid_put({
      title: 'API Documentation',
      label: 'docs',
      text: 'Authentication uses JWT tokens with refresh capability.',
    });
    console.log(putResult);
    // Output: Document stored with frame_id: 2

    // Search documents
    const findResult = await executors.memvid_find({
      query: 'authentication',
      top_k: 5,
    });
    console.log(findResult);
    // Output: Found 1 results:
    // 1. [API Documentation] (score: 2.34): Authentication uses JWT tokens...

    // Ask questions
    const askResult = await executors.memvid_ask({
      question: 'How does authentication work?',
      mode: 'auto',
    });
    console.log(askResult);
    // Output: Answer: Authentication uses JWT tokens with refresh capability.
    // Sources: API Documentation
    ```

    ## Complete Agentic Example

    ```typescript theme={null}
    import { use } from '@memvid/sdk';
    import { GoogleGenerativeAI } from '@google/generative-ai';

    async function runGeminiAgent() {
      // Initialize
      const mem = await use('google-adk', 'knowledge.mv2');
      const tools = mem.tools as any[];
      const executors = mem.functions as Record<string, (args: any) => Promise<string>>;

      // Store some knowledge first
      await executors.memvid_put({
        title: 'Gemini Overview',
        label: 'google-ai',
        text: 'Gemini is Google\\'s most capable AI model family.',
      });

      await executors.memvid_put({
        title: 'Agent Development Kit',
        label: 'frameworks',
        text: 'ADK is Google\\'s framework for building AI agents.',
      });

      // Create Gemini client
      const geminiKey = process.env.GEMINI_API_KEY ?? process.env.GOOGLE_API_KEY;
      if (!geminiKey) throw new Error("Set GEMINI_API_KEY (or legacy GOOGLE_API_KEY)");
      const genAI = new GoogleGenerativeAI(geminiKey);
      const model = genAI.getGenerativeModel({
        model: 'gemini-2.0-flash',
        tools: [{ functionDeclarations: tools }],
        systemInstruction: 'You are a helpful assistant with access to a knowledge base. ' +
          'Use memvid_find to search and memvid_ask to answer questions.',
      });

      // Run agentic loop
      const chat = model.startChat();

      async function processMessage(userMessage: string): Promise<string> {
        let result = await chat.sendMessage(userMessage);

        // Handle function calls iteratively
        while (true) {
          const parts = result.response.candidates?.[0]?.content?.parts || [];
          const functionCalls = parts.filter((p: any) => p.functionCall);

          if (functionCalls.length === 0) {
            // No more function calls, return text response
            return result.response.text() || 'No response';
          }

          // Execute all function calls
          const responses: any[] = [];
          for (const part of functionCalls) {
            const { name, args } = (part as any).functionCall;
            if (executors[name]) {
              const funcResult = await executors[name](args);
              responses.push({
                functionResponse: { name, response: { result: funcResult } },
              });
            }
          }

          // Send results back
          result = await chat.sendMessage(responses);
        }
      }

      // Example conversation
      const answer = await processMessage(
        'What is Google ADK and how does it relate to Gemini?'
      );
      console.log('Agent response:', answer);

      await mem.seal();
    }

    runGeminiAgent().catch(console.error);
    ```
  </Tab>

  <Tab title="Python">
    ## Installation

    ```bash theme={null}
    pip install memvid-sdk google-genai
    ```

    ## Quick Start

    ```python theme={null}
    from memvid_sdk import use

    # Open with Google ADK adapter
    mem = use('google-adk', 'knowledge.mv2')

    # Access ADK tools
    tools = mem.tools  # Returns ADK tool definitions
    ```

    ## Basic Usage

    ```python theme={null}
    from google import genai
    from google.genai import types
    from memvid_sdk import use

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

    # Get tool definitions
    tools = mem.tools

    # Create Gemini client
    client = genai.Client()

    # Create chat with tools
    chat = client.chats.create(
        model="gemini-2.0-flash",
        config=types.GenerateContentConfig(
            tools=tools,
            system_instruction="You are a helpful assistant with access to a knowledge base."
        )
    )

    # Send message
    response = chat.send_message("What are the best practices for deployment?")
    print(response.text)
    ```

    ## Function Calling

    ```python theme={null}
    from google import genai
    from memvid_sdk import use

    mem = use('google-adk', 'knowledge.mv2', read_only=True)

    # Define tool functions
    def memvid_search(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])

    def memvid_ask(question: str) -> str:
        """Ask a question and get an AI-synthesized answer."""
        answer = mem.ask(question)
        return str(answer.get("answer", ""))

    # Register functions
    tools = [memvid_search, memvid_ask]

    # Create client and generate
    client = genai.Client()
    response = client.models.generate_content(
        model="gemini-2.0-flash",
        contents="Search for information about authentication",
        config=types.GenerateContentConfig(tools=tools)
    )

    # Handle function calls
    for part in response.candidates[0].content.parts:
        if hasattr(part, 'function_call'):
            fn = part.function_call
            if fn.name == "memvid_search":
                result = memvid_search(fn.args["query"])
                print(result)
    ```

    ## Multi-Tool Agent

    ```python theme={null}
    from google import genai
    from google.genai import types
    from memvid_sdk import use

    mem = use('google-adk', 'knowledge.mv2', read_only=True)

    # Define multiple tools
    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])

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

    def get_stats() -> str:
        """Get statistics about the knowledge base."""
        stats = mem.stats()
        return f"Documents: {stats['frame_count']}, Size: {stats['size_bytes']} bytes"

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

    # Create client with all tools
    client = genai.Client()
    chat = client.chats.create(
        model="gemini-2.0-flash",
        config=types.GenerateContentConfig(
            tools=[search_knowledge, get_timeline, get_stats, ask_question],
            system_instruction="You are a helpful assistant with full access to a knowledge base."
        )
    )

    # Interactive session
    response = chat.send_message("Show me recent entries and then search for authentication info")
    print(response.text)
    ```

    ## Streaming Responses

    ```python theme={null}
    from google import genai
    from memvid_sdk import use

    mem = use('google-adk', 'knowledge.mv2', read_only=True)
    client = genai.Client()

    # Stream response
    for chunk in client.models.generate_content_stream(
        model="gemini-2.0-flash",
        contents="Explain the architecture based on the knowledge base",
        config=types.GenerateContentConfig(
            tools=mem.tools,
            system_instruction="You have access to a knowledge base."
        )
    ):
        print(chunk.text, end="")
    ```
  </Tab>
</Tabs>

## Function Declaration Schema

The `memvid_put` function declaration:

```json theme={null}
{
  "name": "memvid_put",
  "description": "Store a document in Memvid memory for later retrieval.",
  "parameters": {
    "type": "object",
    "properties": {
      "title": { "type": "string", "description": "Title of the document" },
      "label": { "type": "string", "description": "Category or label" },
      "text": { "type": "string", "description": "Text content to store" },
      "metadata": { "type": "object", "description": "Optional key-value metadata" }
    },
    "required": ["title", "label", "text"]
  }
}
```

The `memvid_find` function declaration:

```json theme={null}
{
  "name": "memvid_find",
  "description": "Search Memvid memory for documents matching a query.",
  "parameters": {
    "type": "object",
    "properties": {
      "query": { "type": "string", "description": "Search query string" },
      "top_k": { "type": "number", "description": "Number of results (default: 5)" }
    },
    "required": ["query"]
  }
}
```

The `memvid_ask` function declaration:

```json theme={null}
{
  "name": "memvid_ask",
  "description": "Ask a question and get an answer from Memvid memory using RAG.",
  "parameters": {
    "type": "object",
    "properties": {
      "question": { "type": "string", "description": "Question to answer" },
      "mode": { "type": "string", "enum": ["auto", "lex", "sem"], "description": "Search mode" }
    },
    "required": ["question"]
  }
}
```

## Best Practices

1. **Use read-only mode** for retrieval agents
2. **Handle function calls** appropriately in responses
3. **Use streaming** for long responses
4. **Close the memory** when done

<Tabs>
  <Tab title="Node.js">
    ```typescript theme={null}
    const mem = await use('google-adk', 'knowledge.mv2', { readOnly: true });
    try {
      // Create agent and run queries
      const geminiKey = process.env.GEMINI_API_KEY ?? process.env.GOOGLE_API_KEY;
      if (!geminiKey) throw new Error("Set GEMINI_API_KEY (or legacy GOOGLE_API_KEY)");
      const genAI = new GoogleGenerativeAI(geminiKey);
      // ... use client
    } finally {
      // No explicit close needed; dropping the handle releases the shared lock.
    }
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    mem = use('google-adk', 'knowledge.mv2', read_only=True)
    try:
        # Create agent and run queries
        client = genai.Client()
        # ... use client
    finally:
        mem.close()
    ```
  </Tab>
</Tabs>

## Next Steps

<CardGroup cols={2}>
  <Card title="CrewAI" icon="users" href="/frameworks/crewai">
    CrewAI integration
  </Card>

  <Card title="Semantic Kernel" icon="brain" href="/frameworks/semantic-kernel">
    Semantic Kernel integration
  </Card>
</CardGroup>
