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("--------------")
相关推荐
马***41111 小时前
适配成人英语学习痛点,打造落地性强的学习辅助方式
人工智能·学习
lifloveyou11 小时前
table接口结构
python
DO_Community13 小时前
DigitalOcean 的 AI 推理路由器是如何构建的
人工智能·开源·agent·claude·deepseek
Warson_L13 小时前
class 扩展
python
小拉达不是臭老鼠13 小时前
Unity学习_ScriptableObject
学习·unity
冬奇Lab14 小时前
Agent 系列(12):Agent 评估框架——怎么知道你的 Agent 到底好不好
人工智能·agent
前端与小赵14 小时前
Python 数据结构陷阱与复数运算优化:列表、元组、字典成员操作辨析及 NumPy 高效实践
python
天天进步201514 小时前
Python全栈项目--基于深度学习的视频目标跟踪系统
python·深度学习·音视频
MartinYeung514 小时前
[论文学习]LLM 与其他 AI 模型的隐私考量:输入与输出隐私框架方法
人工智能·学习
天天进步201514 小时前
Python全栈项目--Python自动化运维工具开发
运维·python·自动化