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("--------------")
相关推荐
水木流年追梦2 分钟前
大模型入门-应用篇3-Agent智能体
开发语言·python·算法·leetcode·正则表达式
小新同学^O^3 分钟前
简单学习 --> WebSocket
java·websocket·网络协议·学习
财经资讯数据_灵砚智能20 分钟前
基于全球经济类多源新闻的NLP情感分析与数据可视化(夜间-次晨)2026年5月12日
人工智能·python·信息可视化·自然语言处理·ai编程
世rui睿35 分钟前
Java 自研 ReAct Agent 半年后,我用 LangGraph 验证了这些设计取舍
langchain·agent
2301_8159019744 分钟前
C#怎么使用协变和逆变 C#泛型中的in和out关键字协变逆变是什么意思怎么用【语法】
jvm·数据库·python
Pkmer1 小时前
LeetCode 上极少见的工程级滑窗实现
python·leetcode
m0_463672201 小时前
SQL优化SQL关联查询中的排序字段_减少临时空间占用与内存开销
jvm·数据库·python
FreakStudio1 小时前
开源分享|用MicroPython 做了个 AI 小鸡,它会长大,还记得我所有的情绪
python·单片机·嵌入式·面向对象·并行计算·电子diy·电子计算机
iuvtsrt1 小时前
存储过程如何处理海量数据的批处理_循环提交与分段LIMIT结合
jvm·数据库·python
yexuhgu1 小时前
SQL如何检查字符串是否存在:INSTR与LOCATE函数使用
jvm·数据库·python