> ## 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.

# 基于 PgVector 的传统 RAG

## 代码

```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,
    # 通过将上下文从 `knowledge` 添加到用户提示中来启用 RAG。
    add_references=True,
    # 设置为 False，因为 Agent 默认为 `search_knowledge=True`
    search_knowledge=False,
    markdown=True,
)
agent.print_response(
    "How do I make chicken and galangal in coconut milk soup", stream=True
)
```

## 用法

<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 pypdf 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/traditional_rag_pgvector.py
      ```

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