调用ragflow api实现俩个模型根据知识库的内容来进行对话 简易版

调用ragflow接口实现俩个模型对话 简易版

用到的库

  1. requests 调用api 发送请求
  2. streamlit 做一个简单的页面
  3. json 解析接口返回的内容

流程

根据ragflow官方api文档中的内容,我们需要先将api键需要放到请求头中,然后再调用new_conversation来创建会话,最后再调用completion来获取答案

代码

import requests
import streamlit as st
import json

# 设置API的基础URL
base_url = "http://192.168.1.115/v1/api"
api_key_model_1 = "ragflow-Y4MDVkMWM4NTlkZjExZWZhOWMzMDI0Mm"  # 模型1的api键
api_key_model_2 = "ragflow-c3MTZkNTQyNjAyYzExZWY4NzdkMDI0Mm"  # 模型2的api键

# 设置请求头
headers_model_1 = {
    "Content-Type": "application/json",
    "Authorization": f"Bearer {api_key_model_1}"
}

headers_model_2 = {
    "Content-Type": "application/json",
    "Authorization": f"Bearer {api_key_model_2}"
}


# 调用 /api/new_conversation 创建会话
def create_new_conversation(headers):
    url = f"{base_url}/new_conversation"
    response = requests.get(url, headers=headers)

    if response.status_code == 200:
        conversation_data = response.json()
        conversation_id = conversation_data.get("data", {}).get("id")
        if conversation_id:
            print(f"New conversation ID: {conversation_id}")  # 控制台输出会话ID
            return conversation_id
        else:
            st.error("API响应不包含有效的会话ID。")
            return None
    else:
        st.error(f"请求失败,状态码: {response.status_code}")
        st.error(f"响应内容: {response.text}")
        return None


# 调用 /api/completion 获取答案
def get_completion(conversation_id, message, headers, model_name):
    url_completion = f"{base_url}/completion"
    data = {
        "conversation_id": conversation_id,
        "messages": [
            {
                "role": "user",
                "content": message
            }
        ],
        "model": model_name  # 替换为实际的模型名称
    }

    response = requests.post(url_completion, json=data, headers=headers)

    # 打印原始响应内容以调试
    print("Raw response status code:", response.status_code)  # 控制台打印状态码
    print("Raw response content:", response.text)  # 控制台打印完整响应内容

    if response.status_code == 200:
        try:
            # 处理最后一次返回的数据
            last_answer = ""
            for line in response.text.splitlines():
                print("Processing line:", line)  # 控制台打印当前处理的行
                if line.startswith("data:"):
                    line_content = line[len("data:"):]
                    try:
                        json_data = json.loads(line_content)
                        print("Parsed JSON data:", json_data)  # 控制台打印解析后的JSON数据
                        if "data" in json_data and isinstance(json_data["data"], dict):
                            last_answer = json_data["data"].get("answer", "")
                            print("Current last answer:", last_answer)  # 控制台打印当前的最后答案
                        elif json_data["data"] is True:
                            print("Received end signal, processing complete.")  # 控制台打印结束信号
                            break
                    except json.JSONDecodeError as e:
                        st.error(f"无法解析JSON: {e}")
                        continue
            if last_answer:
                # 使用repr以保留所有特殊字符在返回内容中的显示
                print("Final last answer:", repr(last_answer))  # 控制台打印最终的最后答案
                return last_answer
            else:
                st.error("没有接收到有效的答案。")
                return None
        except ValueError as e:
            st.error(f"JSON解析失败: {e}")
            return None
    else:
        st.error(f"请求失败,状态码: {response.status_code}")
        st.error(f"响应内容: {response.text}")
        return None


# Streamlit 主程序
def main():
    st.title("模型对话系统")

    user_question = st.text_input("输入你的问题:")

    if st.button("提交"):
        # Step 1: 为每个模型创建新会话
        st.write("正在为第一个模型创建新会话...")
        conversation_id_model_1 = create_new_conversation(headers_model_1)
        st.write("正在为第二个模型创建新会话...")
        conversation_id_model_2 = create_new_conversation(headers_model_2)

        if not conversation_id_model_1 or not conversation_id_model_2:
            st.error("无法创建新的会话,终止操作。")
            return

        # Step 2: 获取第一个模型的回答
        st.write("第一个模型正在生成答案...")
        model_1_answer = get_completion(conversation_id_model_1, user_question, headers_model_1, "your_model_name_1")

        if model_1_answer:
            st.write("第一个模型的回答:")
            st.markdown(model_1_answer)  # 使用 st.markdown 解析并显示 Markdown 内容
        else:
            st.error("第一个模型无法生成答案,终止操作。")
            return

        # Step 3: 使用第二个模型对第一个模型的回答进行评估
        st.write("第二个模型正在评估第一个模型的回答...")
        evaluation_message = f"请评估以下回答的准确性和完整性:\n\n{model_1_answer}"
        model_2_evaluation = get_completion(conversation_id_model_2, evaluation_message, headers_model_2,
                                            "your_model_name_2")

        if model_2_evaluation:
            st.write("第二个模型的评估结果:")
            st.markdown(model_2_evaluation)  # 使用 st.markdown 解析并显示 Markdown 内容
        else:
            st.error("第二个模型无法进行评估,终止操作。")


if __name__ == "__main__":
    main()

参考文献

  • ragflow官方api文档 https://github.com/infiniflow/ragflow/blob/main/docs/references/api.md
### 如何在 RagFlow调用 API 为了实现RagFlow调用 API 的功能,可以按照如下方式构建简易版本的应用程序。此应用程序允许两个模型基于知识库内容进行对话,并利用 `requests` 库来发送 HTTP 请求给目标 API。 #### 使用 Requests 库发起请求 Python 的 `requests` 库用于简化向 Web 服务发出 GET 或 POST 请求的过程。对于 RagFlow 来说,在 Python 脚本中可以通过该库轻松地与远程服务器交互并获取响应数据[^1]。 ```python import requests def call_api(api_url, payload=None): headers = {'Content-Type': 'application/json'} response = None try: if payload is not None: response = requests.post(url=api_url, json=payload, headers=headers) else: response = requests.get(url=api_url, headers=headers) if response.status_code == 200: return response.json() except Exception as e: print(f"Error occurred while calling the API: {str(e)}") return {} ``` 这段代码展示了如何定义一个函数 `call_api()` ,它接受 URL 和可选的有效载荷参数作为输入,并尝试通过 POST 方法提交 JSON 数据至指定地址;如果没有提供有效载荷,则执行 GET 请求。成功接收到状态码为 200 的回复时会解析返回的数据为字典形式输出。 #### Streamlit 构建简单界面 Streamlit 是一种快速创建 web 页面的强大工具,特别适合于展示机器学习项目的结果或与其他开发者分享工作成果。在这个例子中,将使用 Streamlit 创建一个简洁美观的前端供用户操作。 ```python import streamlit as st st.title('RagFlow Model Interaction') input_text = st.text_input(label='Enter your query here:') if st.button('Submit'): result = call_api("http://example.com/api", {"query": input_text}) st.write(result['response']) ``` 上述代码片段说明了怎样设置一个文本框让用户输入查询字符串以及按钮触发事件处理逻辑——当点击 Submit 后端将会调用之前定义好的 `call_api()` 函数并将结果显示出来。 #### 处理 API 返回的内容 通常情况下,API 将以 JSON 格式的字符串回应客户端请求。因此需要对这些信息进一步分析提取有用的部分显示给最终使用者查看。这一步骤可能涉及到遍历列表、访问特定键值等常规操作。 ```python data = { "key1": ["valueA", "valueB"], "key2": [{"subKey": "anotherValue"}] } for item in data["key1"]: print(item) print(data["key2"][0]["subKey"]) ``` 以上示例演示了一个简单的 JSON 结构及其对应的读取方法。实际应用中应当根据具体 API 接口文档调整相应的字段名称和路径。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

龙_尧

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值