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

# Using as Tool

> Use KnowledgeBase as a tool in Agent or Task

## Overview

KnowledgeBase can be used as a tool, allowing the agent to actively search and retrieve information from your knowledge base during task execution. When added as a tool, the agent gains access to a `search` method that it can call to query the knowledge base.

## Key Benefits

* **Active Retrieval**: Agent decides when and how to search the knowledge base
* **Dynamic Queries**: Agent can formulate multiple queries based on context
* **Tool Integration**: Works seamlessly with other tools in the agent's toolkit
* **Automatic Setup**: KnowledgeBase is automatically set up when first used

## Basic Usage

Add KnowledgeBase to the `tools` parameter of a Task or Agent:

```python theme={null}
from upsonic import Agent, Task, KnowledgeBase
from upsonic.embeddings import OpenAIEmbedding, OpenAIEmbeddingConfig
from upsonic.vectordb import ChromaProvider, ChromaConfig, ConnectionConfig, Mode
from upsonic.loaders.pdf import PdfLoader
from upsonic.loaders.config import PdfLoaderConfig

# Step 1: Setup embedding provider
embedding = OpenAIEmbedding(OpenAIEmbeddingConfig(
    model_name="text-embedding-3-small"
))

# Step 2: Setup vector database
vectordb = ChromaProvider(ChromaConfig(
    collection_name="my_rag_kb",
    vector_size=1536,
    connection=ConnectionConfig(
        mode=Mode.EMBEDDED,
        db_path="./rag_database"
    )
))

# Step 3: Setup PDF loader
loader = PdfLoader(PdfLoaderConfig())

# Step 4: Create knowledge base with documents
kb = KnowledgeBase(
    sources=["document.pdf"],
    embedding_provider=embedding,
    vectordb=vectordb,
    loaders=[loader]
)

# Step 5: Create agent
agent = Agent("anthropic/claude-sonnet-4-5")

# Step 6: Create task with knowledge base as a tool
task = Task(
    description="What are the main topics discussed in the document?",
    tools=[kb]
)

# Step 7: Execute and get results
result = agent.do(task)
print(result)
```

## How It Works

1. **Tool Registration**: When you add KnowledgeBase to `tools`, the agent automatically registers the `search` method as an available tool
2. **Automatic Setup**: The KnowledgeBase is automatically set up.
3. **Agent Control**: The agent decides when to call the search tool and what queries to make
4. **Results Integration**: Search results are returned to the agent, which uses them to answer your questions

## Tool vs Context

**Using as Tool** (this feature):

* Agent actively searches when needed
* Agent can make multiple queries
* Agent controls the search strategy
* Best for: Complex tasks requiring multiple searches

**Using as Context** (traditional RAG):

* Knowledge base is queried once before task execution
* Results are added to the context automatically
* Simpler, but less flexible
* Best for: Simple Q\&A tasks

## Multiple Knowledge Bases

You can add multiple KnowledgeBase instances as tools. **When using multiple knowledge bases, provide unique `name` and `description` attributes** so the agent can distinguish between them:

```python theme={null}
from upsonic import Agent, Task, KnowledgeBase
from upsonic.embeddings import OpenAIEmbedding, OpenAIEmbeddingConfig
from upsonic.vectordb import ChromaProvider, ChromaConfig, ConnectionConfig, Mode
from upsonic.loaders.pdf import PdfLoader
from upsonic.loaders.config import PdfLoaderConfig

# Setup dependencies
embedding = OpenAIEmbedding(OpenAIEmbeddingConfig())
vectordb = ChromaProvider(ChromaConfig(
    collection_name="my_kb",
    vector_size=1536,
    connection=ConnectionConfig(mode=Mode.EMBEDDED, db_path="./chroma_db")
))

loader = PdfLoader(PdfLoaderConfig())

# Each KnowledgeBase MUST have a unique name for multi-KB usage
kb1 = KnowledgeBase(
    sources=["technical_docs/"],
    embedding_provider=embedding,
    vectordb=vectordb,
    loaders=[loader],
    name="technical_docs",  # IMPORTANT: Unique name for this KB
    description="Technical API documentation including rate limits, authentication, and endpoints"
)

kb2 = KnowledgeBase(
    sources=["user_guides/"],
    embedding_provider=embedding,
    vectordb=vectordb,
    loaders=[loader],
    name="user_guides",  # IMPORTANT: Different unique name
    description="User guides and tutorials for end users including usage limits and best practices"
)

# Use with Agent
agent = Agent("anthropic/claude-sonnet-4-5")
task = Task(
    description="Compare the API rate limits defined in the technical documentation with the usage limits described in the user guide",
    tools=[kb1, kb2]
)

result = agent.do(task)
print(result)
```

### How Tool Names Are Generated

When you register multiple KnowledgeBase instances as tools, each one gets a **unique tool name** based on its `name` attribute:

| KnowledgeBase `name` | Registered Tool Name                                           |
| -------------------- | -------------------------------------------------------------- |
| `"technical_docs"`   | `search_technical_docs`                                        |
| `"user_guides"`      | `search_user_guides`                                           |
| (no name provided)   | `search_{auto_generated_id}` (e.g., `search_7c6432f612bb422a`) |

This allows the agent to call the appropriate knowledge base search tool:

* Call `search_technical_docs(query="API rate limits")` to search the technical documentation
* Call `search_user_guides(query="usage limits")` to search the user guides

<Warning>
  If you don't provide unique `name` attributes, tool names may collide and only one knowledge base will be accessible.
</Warning>

## Cleanup

Always close the KnowledgeBase when done to free resources:

```python theme={null}
await kb.close()
```
