一、概述
在上一篇文章中,介绍了text-to-sql,使用RAGflow Agent实现的。在业务系统中,需要调用它。
但是在Agent页面,没有相关API调用文档。
注意:RAGflow只有一个API调用设置
这里面,只是介绍了一部分API接口,显示并不完整。
官方API完整文档,链接:https://ragflow.io/docs/dev/http_api_reference
二、Agent API
官方文档链接:https://ragflow.io/docs/dev/http_api_reference#converse-with-agent
注意:调用text-to-sql agent的api接口,分2个步骤:
1. 请求api接口拿到session_id
2. 正式请求api接口,携带session_id,就可以正常拿到返回结果了。
完整python代码如下:
import requests
import json
API_HOST = "http://10.44.32.14:8081"
API_KEY = "ragflow-U2N***"
AGENT_ID = "002b4af814f411f0a9a80242c0a83006"
question = "成绩表中有多少条记录"
# 请求url
url = API_HOST + "/api/v1/agents/" + AGENT_ID + "/completions"
# print(url)
# 自定义请求头
headers = {
"Authorization": "Bearer %s" % API_KEY,
"Content-Type": "application/json",
}
class AgentStreamResponse:
def __init__(self):
pass
def get_session_id(self):
"""
获取会话 ID
"""
data = {"id": AGENT_ID}
response = requests.post(url, data=data, headers=headers)
try:
line_list=[]
with requests.post(
url, json=data, headers=headers, stream=True, timeout=30
) as response:
if response.status_code == 200:
for line in response.iter_lines():
if line: # 过滤掉空行
# print(line.decode("utf-8"))
line_list.append(line.decode("utf-8"))
else:
print(f"请求失败,状态码: {response.status_code}")
return False
# print("line_list",line_list)
first_line=line_list[0]
# 提取data内容
line_row=first_line.split("data:")[1]
# json解析
line_dict=json.loads(line_row)
# 获取session_id
session_id=line_dict["data"]["session_id"]
return session_id
except requests.exceptions.RequestException as e:
print(f"请求错误: {e}")
return False
def get_stream_data(self):
"""
获取流式数据
"""
try:
session_id = self.get_session_id()
data = {
"id": AGENT_ID,
"question": question,
"stream": "true",
"session_id": session_id,
}
with requests.post(
url, json=data, headers=headers, stream=True, timeout=30
) as response:
if response.status_code == 200:
for line in response.iter_lines():
if line: # 过滤掉空行
print(line.decode("utf-8"))
else:
print(f"请求失败,状态码: {response.status_code}")
return False
except requests.exceptions.RequestException as e:
print(f"请求错误: {e}")
return False
if __name__ == "__main__":
agent_stream_response = AgentStreamResponse()
agent_stream_response.get_stream_data()
注意,修改上面代码,红色部分的几个参数变量。
参数说明:
API_HOST = "http://10.44.32.14:8081",API地址
API_KEY = "ragflow-U2N***",API key
AGENT_ID = "002b4af814f411f0a9a80242c0a83006"
点击agent,页面地址的id
question = "成绩表中有多少条记录",要提问的问题。
执行python代码,效果如下:
注意:这里使用stream方式返回的,所以数据有点多。
使用postman调用,你会看到返回很多条数据
倒数第2条,就是最终结果
可以看到sql就是: