RGA DEMO 下部

复制代码
#加载llm模型通过ollama最好别用ollama我是没经济条件
from langchain_community.llms import Ollama
llm = Ollama(model="qwen1_5-4b-chat-q2_k")


#pip install langchain_ollama -i https://pypi.tuna.tsinghua.edu.cn/simple
#OllamaEmbeddings 要写地址本地也要写, Ollama_llm本地的不用写地址
from langchain_ollama import OllamaEmbeddings
embeddings = OllamaEmbeddings(model="lrs33/bce-embedding-base_v1",base_url="http://localhost:11434/")


#pip install -qU langchain-postgres -i https://pypi.tuna.tsinghua.edu.cn/simple
from langchain_postgres import PGVector
from langchain_postgres.vectorstores import PGVector

CONNECTION_STRING = "postgresql+psycopg2://postgres:[email protected]:5432/postgres"
# 矢量存储名
COLLECTION_NAME = "yaofang_test"
# 连接数据库创建"客户端"
vectorstore = PGVector(
    collection_name=COLLECTION_NAME,
    connection=CONNECTION_STRING,
    embeddings=embeddings,
)

#设置检索条件
retriever = vectorstore.as_retriever(search_type="similarity", search_kwargs={"k": 6})
# 一个对话模板,内含2个变量context和question
template = """根据以下上下文回答问题:
{context}
回答: {question}
"""
# 基于模板生成提示
from langchain_core.prompts import ChatPromptTemplate
prompt = ChatPromptTemplate.from_template(template)


# 生成输出解析器
from langchain_core.output_parsers import StrOutputParser
output_parser = StrOutputParser()

# 将检索索引器和输入内容(问题)生成检索
from langchain_core.runnables import RunnableParallel, RunnablePassthrough
setup_and_retrieval = RunnableParallel(
    {"context": retriever, "question": RunnablePassthrough()}
)

def format_docs(docs):
    return "\n\n".join(doc.page_content for doc in docs)

rag_chain = (
    {"context": retriever | format_docs, "question": RunnablePassthrough()}
    | prompt
    | llm
    | StrOutputParser()
)

#流式输出
for chunk in rag_chain.stream("java 共有多少种设计模式"):
    print(chunk, end="", flush=True)

输出结果:

此代码流程是:创建向量数据库客户端,连接对应表,设置检索问题向量距离最近的top回调数据,大语言模型推理答案流式输出。

结合这上下部简单的RGA demo 就完成了,当然距离真正的RGA 差十万八千里后续会基于这个骨架开发进一步功能至少提供个UI界面正在考虑使用javaAPI模式,还是python gradio方式好纠结。

相关推荐
森哥的歌31 分钟前
Python uv包管理器使用指南:从入门到精通
python·开发工具·uv·虚拟环境·包管理
qq_2147826134 分钟前
给你的matplotlib images添加scale Bar
python·数据分析·matplotlib
Johny_Zhao1 小时前
Vmware workstation安装部署微软SCCM服务系统
网络·人工智能·python·sql·网络安全·信息安全·微软·云计算·shell·系统运维·sccm
waterHBO1 小时前
python + flask 做一个图床
python
ZWaruler2 小时前
二: 字典及函数的使用
python
蚰蜒螟2 小时前
深入解析JVM字节码解释器执行流程(OpenJDK 17源码实现)
开发语言·jvm·python
墨绿色的摆渡人2 小时前
pytorch小记(二十):深入解析 PyTorch 的 `torch.randn_like`:原理、参数与实战示例
人工智能·pytorch·python
英英_3 小时前
python 自动化教程
开发语言·python·自动化
万能程序员-传康Kk3 小时前
【Python+flask+mysql】网易云数据可视化分析(全网首发)
python·mysql·信息可视化·数据分析·flask·可视化·网易云
先做个垃圾出来………3 小时前
汉明距离(Hamming Distance)
开发语言·python·算法