问答机器人prompt

def build_prompt(prompt_template, **kwargs):

'''将 Prompt 模板赋值'''

prompt = prompt_template

for k, v in kwargs.items():

if isinstance(v, str):

val = v

elif isinstance(v, list) and all(isinstance(elem, str) for elem in v):

val = '\n'.join(v)

else:

val = str(v)

prompt = prompt.replace(f"{k.upper()} ", val)

return prompt

prompt_template = """

你是一个问答机器人。

你的任务是根据下述给定的已知信息回答用户问题。

确保你的回复完全依据下述已知信息。不要编造答案。

如果下述已知信息不足以回答用户的问题,请直接回复"我无法回答您的问题"。

已知信息:
INFO

用户问:
QUERY

请用中文回答用户问题。

"""

import chromadb

from chromadb.config import Settings

class MyVectorDBConnector:

def init (self, collection_name, embedding_fn):

chroma_client = chromadb.Client(Settings(allow_reset=True))

复制代码
    # 为了演示,实际不需要每次 reset()
    chroma_client.reset()

    # 创建一个 collection
    self.collection = chroma_client.get_or_create_collection(name=collection_name)
    self.embedding_fn = embedding_fn

def add_documents(self, documents):
    '''向 collection 中添加文档与向量'''
    self.collection.add(
        embeddings=self.embedding_fn(documents),  # 每个文档的向量
        documents=documents,  # 文档的原文
        ids=[f"id{i}" for i in range(len(documents))]  # 每个文档的 id
    )

def search(self, query, top_n):
    '''检索向量数据库'''
    results = self.collection.query(
        query_embeddings=self.embedding_fn([query]),
        n_results=top_n
    )
    return results

class RAG_Bot:

def init (self, vector_db, llm_api, n_results=2):

self.vector_db = vector_db

self.llm_api = llm_api

self.n_results = n_results

复制代码
def chat(self, user_query):
    # 1. 检索
    search_results = self.vector_db.search(user_query, self.n_results)

    # 2. 构建 Prompt
    prompt = build_prompt(
        prompt_template, info=search_results['documents'][0], query=user_query)

    # 3. 调用 LLM
    response = self.llm_api(prompt)
    return response

创建一个RAG机器人

bot = RAG_Bot(

vector_db,

llm_api=get_completion

)

user_query = "llama 2有对话版吗?"

response = bot.chat(user_query)

print(response)

相关推荐
咚咚王者6 分钟前
人工智能之编程进阶 Python高级:第九章 爬虫类模块
开发语言·python
深蓝海拓41 分钟前
使matplot显示支持中文和负号
开发语言·python
AntBlack1 小时前
AI Agent : CrewAI 简单使用 + 尝试一下股票分析
后端·python·ai编程
一眼万里*e1 小时前
搭建本地deepseek大模型
python
1***Q7841 小时前
PyTorch图像分割实战,U-Net模型训练与部署
人工智能·pytorch·python
二进制的Liao2 小时前
【编程】脚本编写入门:从零到一的自动化之旅
数据库·python·算法·自动化·bash
Dxy12393102162 小时前
Python为什么要使用可迭代对象
开发语言·python
Keep_Trying_Go3 小时前
论文STEERER人群计数,车辆计数以及农作物计数算法详解(pytorch)
人工智能·pytorch·python
gzu_013 小时前
基于昇腾 配置pytorch环境
人工智能·pytorch·python
前进的李工3 小时前
LeetCode hot100:234 回文链表:快慢指针巧判回文链表
python·算法·leetcode·链表·快慢指针·回文链表