调用ragflow接口实现俩个模型对话 简易版
- 用到的库
- 流程
- 代码
- 参考文献
用到的库
- requests 调用api 发送请求
- streamlit 做一个简单的页面
- json 解析接口返回的内容
流程
根据ragflow官方api文档中的内容,我们需要先将api键需要放到请求头中,然后再调用new_conversation来创建会话,最后再调用completion来获取答案
代码
python">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}") # 控制台输出会话IDreturn conversation_idelse:st.error("API响应不包含有效的会话ID。")return Noneelse: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.") # 控制台打印结束信号breakexcept json.JSONDecodeError as e:st.error(f"无法解析JSON: {e}")continueif last_answer:# 使用repr以保留所有特殊字符在返回内容中的显示print("Final last answer:", repr(last_answer)) # 控制台打印最终的最后答案return last_answerelse:st.error("没有接收到有效的答案。")return Noneexcept ValueError as e:st.error(f"JSON解析失败: {e}")return Noneelse: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