---
title: 代理 RAG 与重排序
---

## 代码

```python
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.reranker.cohere import CohereReranker
from agno.vectordb.lancedb import LanceDb, SearchType

# 创建来自 URL 的 PDF 知识库
knowledge_base = PDFUrlKnowledgeBase(
    urls=["https://agno-public.s3.amazonaws.com/recipes/ThaiRecipes.pdf"],
    # 将 LanceDB 用作向量数据库,并将嵌入存储在 `recipes` 表中
    vector_db=LanceDb(
        table_name="recipes",
        uri="tmp/lancedb",
        search_type=SearchType.vector,
        embedder=OpenAIEmbedder(id="text-embedding-3-small"),
        reranker=CohereReranker(model="rerank-multilingual-v3.0"),  # 添加重排序器
    ),
)
# 加载知识库:首次运行后注释掉此行,因为知识库已加载
knowledge_base.load()

agent = Agent(
    model=OpenAIChat(id="gpt-4o"),
    knowledge=knowledge_base,
    # 添加一个搜索知识库的工具,以实现代理 RAG。
    # 当 `knowledge` 提供给 Agent 时,默认启用此功能。
    search_knowledge=True,
    show_tool_calls=True,
    markdown=True,
)
agent.print_response(
    "How do I make chicken and galangal in coconut milk soup", stream=True
)

用法

1

创建虚拟环境

打开 Terminal 并创建一个 python 虚拟环境。

python3 -m venv .venv
source .venv/bin/activate
2

设置您的 API 密钥

export OPENAI_API_KEY=xxx
export COHERE_API_KEY=xxx
3

安装库

pip install -U openai lancedb tantivy pypdf sqlalchemy agno cohere
4

运行 Agent

python cookbook/agent_concepts/rag/agentic_rag_with_reranking.py