Agent实践三:基于Chroma的RAG检索

embeding.py

python 复制代码
import function
import chromadb
from google import genai

google_client = genai.Client()
EMBEDDING_MODEL = "gemini-embedding-exp-03-07"
LLM_MODEL = "gemini-2.5-flash-preview-05-20"

chromadb_client = chromadb.PersistentClient("./chroma.db")
chromadb_collection = chromadb_client.get_or_create_collection("question")

def embed(text: str, store: bool) -> list[float]:
    result = google_client.models.embed_content(
        model=EMBEDDING_MODEL,
        contents=text,
        config={
            "task_type": "RETRIEVAL_DOCUMENT" if store else "RETRIEVAL_QUERY"
        }
    )

    assert result.embeddings
    assert result.embeddings[0].values
    return result.embeddings[0].values

def create_db() -> None:
    for idx, c in enumerate(function.get_chunks()):
        print(f"Process: {c}")
        embedding = embed(c, store=True)
        chromadb_collection.upsert(
            ids=str(idx),
            documents=c,
            embeddings=embedding
        )

def query_db(question: str) -> list[str]:
    question_embedding = embed(question, store=False)
    result = chromadb_collection.query(
        query_embeddings=question_embedding,
        n_results=5
    )
    assert result["documents"]
    return result["documents"][0]


if __name__ == '__main__':
    question = "question"
    # create_db()
    chunks = query_db(question)
    prompt = "Please answer user's question according to context\n"
    prompt += f"Question: {question}\n"
    prompt += "Context:\n"
    for c in chunks:
        prompt += f"{c}\n"
        prompt += "-------------\n"
    
    result = google_client.models.generate_content(
        model=LLM_MODEL,
        contents=prompt
    )
    print(result)

function.py

python 复制代码
def read_data() -> str:
    with open("data.md", "r", encoding="utf-8") as f:
        return f.read()
 
def get_chunks() -> list[str]:
    content = read_data()
    chunks = content.split('\n\n')
    
    result = []
    header = ""
    for c in chunks:
        if c.startswith("#"):
            header += f"{c}\n"
        else:
            result.append(f"{header}{c}")
            header = ""

    return result

if __name__ == '__main__':
    chunks = get_chunks()
    for c in chunks:
        print(c)
        print("--------------")
相关推荐
ServBay5 分钟前
9 个 Python 第三方库推荐,不用 AI 都好像多出一个团队
后端·python
用户8356290780517 分钟前
如何使用 Python 添加和管理 Excel 批注(完整示例)
后端·python
用户83562907805120 分钟前
使用 Python 管理 Excel 工作表:创建、复制、删除与重命名
后端·python
想要成为糕糕手1 小时前
深入理解AI Agent工具调用:从原理到代码实现
llm·agent
Sokach10152 小时前
Windows使用hermes桌面端个人出现的问题
agent
leeyi2 小时前
Agent Transfer:让 AI 把任务交给更合适的 AI
aigc·agent·ai编程
后端小肥肠2 小时前
Codex + Obsidian 做人生副本视频:输入主题文案,直通剪映草稿
人工智能·aigc·agent
花椒技术3 小时前
Agent 不只会聊天:我们如何用 CLI 整理业务能力入口
agent·ai编程·mcp
DigitalOcean4 小时前
在云端运行 Codex —— DigitalOcean Codex 插件正式推出
agent
FanetheDivine4 小时前
学习Agent开发6 langgraph速览
agent·ai编程