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:qaz142434@192.168.159.130: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方式好纠结。

相关推荐
Li emily2 小时前
解决了加密货币api多币种订阅时的数据乱序问题
人工智能·python·api·fastapi
2301_781571422 小时前
Golang格式化输出占位符都有什么_Golang fmt占位符教程【通俗】
jvm·数据库·python
asdzx672 小时前
使用 Python 为 PDF 添加页码 (详细教程)
python·pdf·页码
AI技术控3 小时前
《Transformers are Inherently Succinct》论文解读:从“能表达什么”到“多紧凑地表达”
人工智能·python·深度学习·机器学习·自然语言处理
金融大 k5 小时前
Python 全球指数监控面板:TickDB + REST + WebSocket 完整方案
python·websocket
啊哈哈121385 小时前
系统设计复盘:为什么 Agent 的 ReAct 循环必须内嵌确定性保护层——以 FitMind 健康助手的路由与步骤控制为例
人工智能·python·react
一颗牙牙6 小时前
安装mmcv
开发语言·python·深度学习
大数据魔法师6 小时前
Streamlit(二)- Streamlit 架构与运行机制
python·web
m0_470857646 小时前
PHP怎么实现工厂模式_Factory模式编写指南【指南】
jvm·数据库·python
大数据魔法师7 小时前
Streamlit(三)- Streamlit 多页面应用开发
python·web