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

# Knowledge Tools and RAG

> Enable semantic search across your documents using Retrieval-Augmented Generation

## Overview

Knowledge tools enable your AI persona to search uploaded documents and provide accurate, source-based answers using Retrieval-Augmented Generation (RAG). Instead of relying only on the LLM's training data, your persona can access your organization's specific documentation, policies, and knowledge base.

This guide covers how to create and optimize knowledge tools for maximum accuracy and relevance.

## Prerequisites

Before creating knowledge tools, you need:

* Knowledge folders created (see [Knowledge Base Setup](/personas/knowledge/setup))
* Documents uploaded and in READY status
* Basic understanding of RAG concepts (see [Knowledge Base Overview](/personas/knowledge/overview))

## Creating a Knowledge Tool

<Tabs>
  <Tab title="Stateful (Database-Saved)">
    Create reusable tools in the Anam Lab that can be attached to multiple personas.

    <Steps>
      <Step title="Create the tool">
        Navigate to `/tools` in the Anam Lab and create your knowledge tool:

        1. Click **Create Tool**

        2. Select **Knowledge Tool**

        3. Fill in the configuration:
           * **Name**: `search_product_docs` (snake\_case)
           * **Description**: Clear description of when to use this tool
           * **Knowledge Folders**: Select one or more folders

        4. Click **Create Tool**

        <Check>
          The tool is now saved with a unique ID and appears in your organization's tool library.
        </Check>
      </Step>

      <Step title="Attach tool to persona">
        Navigate to `/build/{personaId}` and attach the tool:

        1. Scroll to the **Tools** section
        2. Click **Add Tool**
        3. Select `search_product_docs` from the dropdown
        4. Save the persona

        <Check>
          The tool is now attached to this persona. When you create sessions with this persona, the tool will automatically be available.
        </Check>
      </Step>

      <Step title="Use in session">
        Create a session using the persona ID:

        ```javascript theme={"system"}
        const response = await fetch("https://api.anam.ai/v1/auth/session-token", {
          method: "POST",
          headers: {
            Authorization: "Bearer YOUR_API_KEY",
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            personaConfig: {
              personaId: "your-persona-id", // Tools loaded automatically
            },
          }),
        });
        ```
      </Step>
    </Steps>

    <Note>
      Stateful tools are ideal when you want to reuse the same tool across multiple personas or manage tools centrally.
    </Note>
  </Tab>
</Tabs>

## How Knowledge Tools Work

When the AI needs information to answer a question, it uses a knowledge tool to search your documents.

<Steps>
  <Step title="User asks a question">
    User: "How do I authenticate API requests?"
  </Step>

  <Step title="AI decides to search">
    The AI determines the question requires information from your documentation and automatically formulates a search query.

    <Info>
      The AI looks for the semantic meaning behind the user's question, not just literal keywords.
    </Info>
  </Step>

  <Step title="System finds relevant content">The system searches the folders associated with the tool and retrieves the most relevant snippets from your documents.</Step>

  <Step title="AI generates a response">
    The AI uses the retrieved information to construct an accurate, conversational answer.

    "To authenticate API requests, you'll need to include your API key in the Authorization header like this: `Authorization: Bearer YOUR_API_KEY`. You can get an API key from your dashboard."

    <Check>
      The user receives an answer grounded in your specific documentation.
    </Check>
  </Step>
</Steps>

## Monitoring Knowledge Tool Calls

Knowledge tool calls emit lifecycle events on the client that you can use for logging or analytics. Use `toolType` and `toolSubtype` to filter for knowledge-specific events:

```javascript theme={"system"}
import { AnamEvent } from "@anam-ai/js-sdk";

anamClient.addListener(AnamEvent.TOOL_CALL_STARTED, (event) => {
  if (event.toolType === "server" && event.toolSubtype === "knowledge") {
    console.log(`Knowledge search started: ${event.toolName}`);
  }
});

anamClient.addListener(AnamEvent.TOOL_CALL_COMPLETED, (event) => {
  if (event.toolType === "server" && event.toolSubtype === "knowledge") {
    console.log(`Knowledge search completed: ${event.toolName} in ${event.executionTime}ms`);
  }
});

anamClient.addListener(AnamEvent.TOOL_CALL_FAILED, (event) => {
  if (event.toolType === "server" && event.toolSubtype === "knowledge") {
    console.error(`Knowledge search failed: ${event.toolName} - ${event.errorMessage}`);
  }
});
```

<Tip>
  See the [Events SDK Reference](/javascript-sdk/reference/events#tool-call-events) for the full list of tool call event payloads and types.
</Tip>

## Next Steps

<CardGroup cols={2}>
  <Card title="Knowledge Base Setup" icon="upload" href="/personas/knowledge/setup">
    Create folders and upload documents
  </Card>

  <Card title="Client Tools" icon="browser" href="/personas/tools/client-tools">
    Trigger UI actions with client tools
  </Card>

  <Card title="Webhook Tools" icon="webhook" href="/personas/tools/webhook-tools">
    Integrate external APIs
  </Card>

  <Card title="API Reference" icon="code" href="/api-reference/tools/create-tool">
    Complete API documentation
  </Card>
</CardGroup>
