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

# Agentic RAG with PgVector

## Code

```python theme={null}
from agno.agent import Agent
from agno.embedder.openai import OpenAIEmbedder
from agno.knowledge.pdf_url import PDFUrlKnowledgeBase
from agno.models.openai import OpenAIChat
from agno.vectordb.pgvector import PgVector, SearchType

db_url = "postgresql+psycopg://ai:ai@localhost:5532/ai"
# 创建一个包含来自 URL 的 PDF 的知识库
knowledge_base = PDFUrlKnowledgeBase(
    urls=["https://agno-public.s3.amazonaws.com/recipes/ThaiRecipes.pdf"],
    # 使用 PgVector 作为向量数据库，并将嵌入存储在 `ai.recipes` 表中
    vector_db=PgVector(
        table_name="recipes",
        db_url=db_url,
        search_type=SearchType.hybrid,
        embedder=OpenAIEmbedder(id="text-embedding-3-small"),
    ),
)
# 加载知识库：首次运行后注释掉此行，因为知识库已加载
knowledge_base.load(upsert=True)

agent = Agent(
    model=OpenAIChat(id="gpt-4o"),
    knowledge=knowledge_base,
    # 添加一个用于搜索知识库的工具，以启用 agentic RAG。
    # 当将 `knowledge` 提供给 Agent 时，默认启用此功能。
    search_knowledge=True,
    show_tool_calls=True,
    markdown=True,
)
agent.print_response(
    "如何制作冬阴功椰奶鸡汤", stream=True
)
```

## Usage

<Steps>
  <Snippet file="create-venv-step.mdx" />

  <Step title="设置您的 API 密钥">
    ```bash theme={null}
    export OPENAI_API_KEY=xxx
    ```
  </Step>

  <Step title="安装库">
    ```bash theme={null}
    pip install -U openai sqlalchemy 'psycopg[binary]' pgvector agno
    ```
  </Step>

  <Step title="运行 PgVector">
    ```bash theme={null}
    docker run -d \
      -e POSTGRES_DB=ai \
      -e POSTGRES_USER=ai \
      -e POSTGRES_PASSWORD=ai \
      -e PGDATA=/var/lib/postgresql/data/pgdata \
      -v pgvolume:/var/lib/postgresql/data \
      -p 5532:5432 \
      --name pgvector \
      agnohq/pgvector:16
    ```
  </Step>

  <Step title="运行 Agent">
    <CodeGroup>
      ```bash Mac theme={null}
      python cookbook/agent_concepts/rag/agentic_rag_pgvector.py
      ```

      ```bash Windows theme={null}
      python cookbook/agent_concepts/rag/agentic_rag_pgvector.py
      ```
    </CodeGroup>
  </Step>
</Steps>
