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

# AI Agents with Knowledge

> Learn how to create AI agents with custom knowledge bases

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
flowchart LR
    subgraph In[Input]
        PDF[PDF]
        TXT[TXT]
        MD[MD]
    end

    subgraph Router[Vector Store]
        DB[(Vector DB)]
    end
    
    subgraph Out[Agents]
        A1[Agent 1]
        A2[Agent 2]
        A3[Agent 3]
    end

    In --> Router
    Router --> A1
    Router --> A2
    Router --> A3

    style In fill:#8B0000,color:#fff
    style Router fill:#2E8B57,color:#fff
    style Out fill:#8B0000,color:#fff
```

| Feature     | [Knowledge](/concepts/knowledge)       | [Memory](/concepts/memory)                 |
| ----------- | -------------------------------------- | ------------------------------------------ |
| When Used   | Pre-loaded before agent execution      | Created and updated during runtime         |
| Purpose     | Provide static reference information   | Store dynamic context and interactions     |
| Storage     | Read-only knowledge base               | Read-write memory store                    |
| Persistence | Permanent until explicitly changed     | Can be temporary (STM) or persistent (LTM) |
| Updates     | Manual updates through knowledge files | Automatic updates during agent execution   |

## Quick Start

<Steps>
  <Step title="Install Package">
    Install PraisonAI Agents with knowledge support:

    ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    pip install "praisonaiagents[knowledge]"
    ```
  </Step>

  <Step title="Set API Key">
    Set your OpenAI API key:

    ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    export OPENAI_API_KEY=xxxxx
    ```
  </Step>

  <Step title="Create Script">
    Create a new file `app.py`:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonaiagents import Agent

    agent = Agent(
        name="Knowledge Agent",
        instructions="You answer questions based on the provided knowledge.",
        knowledge=["small.pdf"]
    )

    agent.start("What is KAG in one line?")
    ```
  </Step>
</Steps>

## Basic Usage

The simplest way to create a knowledge-based agent is without any configuration:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent

agent = Agent(
    name="Knowledge Agent",
    instructions="You answer questions based on the provided knowledge.",
    knowledge=["small.pdf"]
)

agent.start("What is KAG in one line?")
```

## Advanced Configuration

For more control over retrieval behavior, use the knowledge dict:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent

agent = Agent(
    name="Knowledge Agent",
    instructions="You answer questions based on the provided knowledge.",
    knowledge={
        "sources": ["small.pdf"],
        "retrieval_k": 5,                 # Number of chunks to retrieve
        "rerank": True,                   # Enable reranking for better relevance
    }
)

agent.start("What is KAG in one line?")
```

## Getting Answers with Citations

Use `agent.query()` for structured answers with source citations:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent

agent = Agent(
    name="Research Agent",
    instructions="You answer questions based on the provided knowledge.",
    knowledge={
        "sources": ["research_paper.pdf"],
        "retrieval_k": 5,
    }
)

# Get structured result with citations
result = agent.query("What are the main findings?")

print(result.answer)
for citation in result.citations:
    print(f"  [{citation.id}] {citation.source}")
```

## Retrieval-Only (No LLM Generation)

Use `agent.retrieve()` to get context without LLM generation:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# Get context pack for manual processing
context = agent.retrieve("What are the key findings?")

print(f"Found {len(context.citations)} sources")
print(context.context)

# Use with chat_with_context for custom workflows
response = agent.chat_with_context("Summarize these findings", context)
```

## Multi-Agent Knowledge System

For more complex scenarios, you can create a knowledge-based system with multiple agents:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent, Task, AgentTeam
import logging
import os

# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

# Define the configuration for the Knowledge instance
config = {
    "vector_store": {
        "provider": "chroma",
        "config": {
            "collection_name": "knowledge_test",
            "path": ".praison",
        }
    }
}

# Create an agent with knowledge capabilities
knowledge_agent = Agent(
    name="KnowledgeAgent",
    role="Information Specialist",
    goal="Store and retrieve knowledge efficiently",
    backstory="Expert in managing and utilizing stored knowledge",
    knowledge={
        "sources": ["sample.pdf"],
        "vector_store": {
            "provider": "chroma",
            "config": {
                "collection_name": "knowledge_test",
                "path": ".praison",
            }
        }
    },
)

# Define a task for the agent
knowledge_task = Task(
    name="knowledge_task",
    description="Who is Mervin Praison?",
    expected_output="Answer to the question",
    agent=knowledge_agent
)

# Create and start the agents
agents = AgentTeam(
    agents=[knowledge_agent],
    tasks=[knowledge_task],
    process="sequential",
)

# Start execution
result = agents.start()
```

## Understanding Knowledge Configuration

<AccordionGroup>
  <Accordion title="Vector Store Options">
    * **Provider**: Choose between different vector store backends (e.g., "chroma")
    * **Collection Name**: Name for your knowledge collection
    * **Path**: Location to store the vector database
  </Accordion>

  <Accordion title="Supported File Types">
    * PDF documents (\*.pdf)
    * Text files (\*.txt)
    * Markdown files (\*.md, \*.mdx)
    * And more...
  </Accordion>

  <Accordion title="Multi-Agent Setup">
    * **Role**: Define specialized roles for knowledge agents
    * **Goal**: Set specific knowledge management objectives
    * **Process**: Choose between sequential or parallel execution
  </Accordion>
</AccordionGroup>

## Features

<CardGroup cols={2}>
  <Card title="Custom Knowledge" icon="book">
    Import your own documents and data as knowledge sources
  </Card>

  <Card title="Vector Storage" icon="database">
    Efficient storage and retrieval of knowledge embeddings
  </Card>

  <Card title="Multiple Sources" icon="layer-group">
    Combine multiple documents and file types
  </Card>

  <Card title="Persistent Storage" icon="hard-drive">
    Save and reuse knowledge bases across sessions
  </Card>
</CardGroup>

## Best Practices

1. **Document Preparation**
   * Clean and well-formatted documents work best
   * Break large documents into smaller chunks
   * Use consistent formatting

2. **Knowledge Organization**
   * Group related documents together
   * Use meaningful file names
   * Keep knowledge bases focused and relevant

3. **Performance Optimization**
   * Monitor vector store size
   * Clean up unused collections
   * Use appropriate chunk sizes

4. **Multi-Agent Coordination**
   * Define clear roles and responsibilities
   * Set appropriate logging levels for debugging
   * Use unique collection names for different agent groups

## Next Steps

* Learn about [Memory Management](/concepts/memory) for long-term recall
* Explore [Tool Integration](/concepts/tools) for enhanced capabilities
* Check out [Examples](/examples) for implementation ideas
