liuhua
liuhua
commited on
Commit
·
c2d189b
1
Parent(s):
2e19fac
SDK for session (#2354)
Browse files### What problem does this PR solve?
Includes SDK for creating, updating sessions, getting sessions, listing
sessions, and dialogues
#1102
### Type of change
- [x] New Feature (non-breaking change which adds functionality)
---------
Co-authored-by: liuhua <[email protected]>
api/apps/sdk/session.py
CHANGED
|
@@ -14,13 +14,13 @@
|
|
| 14 |
# limitations under the License.
|
| 15 |
#
|
| 16 |
import json
|
| 17 |
-
from copy import deepcopy
|
| 18 |
from uuid import uuid4
|
| 19 |
|
| 20 |
from flask import request, Response
|
| 21 |
|
| 22 |
from api.db import StatusEnum
|
| 23 |
from api.db.services.dialog_service import DialogService, ConversationService, chat
|
|
|
|
| 24 |
from api.utils import get_uuid
|
| 25 |
from api.utils.api_utils import get_data_error_result
|
| 26 |
from api.utils.api_utils import get_json_result, token_required
|
|
@@ -31,12 +31,6 @@ from api.utils.api_utils import get_json_result, token_required
|
|
| 31 |
def set_conversation(tenant_id):
|
| 32 |
req = request.json
|
| 33 |
conv_id = req.get("id")
|
| 34 |
-
if "messages" in req:
|
| 35 |
-
req["message"] = req.pop("messages")
|
| 36 |
-
if req["message"]:
|
| 37 |
-
for message in req["message"]:
|
| 38 |
-
if "reference" in message:
|
| 39 |
-
req["reference"] = message.pop("reference")
|
| 40 |
if "assistant_id" in req:
|
| 41 |
req["dialog_id"] = req.pop("assistant_id")
|
| 42 |
if "id" in req:
|
|
@@ -52,10 +46,12 @@ def set_conversation(tenant_id):
|
|
| 52 |
return get_data_error_result(retmsg="You do not own the assistant")
|
| 53 |
if "dialog_id" in req and not req.get("dialog_id"):
|
| 54 |
return get_data_error_result(retmsg="assistant_id can not be empty.")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
if "name" in req and not req.get("name"):
|
| 56 |
return get_data_error_result(retmsg="name can not be empty.")
|
| 57 |
-
if "message" in req and not req.get("message"):
|
| 58 |
-
return get_data_error_result(retmsg="messages can not be empty")
|
| 59 |
if not ConversationService.update_by_id(conv_id, req):
|
| 60 |
return get_data_error_result(retmsg="Session updates error")
|
| 61 |
return get_json_result(data=True)
|
|
@@ -69,22 +65,17 @@ def set_conversation(tenant_id):
|
|
| 69 |
"id": get_uuid(),
|
| 70 |
"dialog_id": req["dialog_id"],
|
| 71 |
"name": req.get("name", "New session"),
|
| 72 |
-
"message":
|
| 73 |
-
"reference": req.get("reference", [])
|
| 74 |
}
|
| 75 |
if not conv.get("name"):
|
| 76 |
return get_data_error_result(retmsg="name can not be empty.")
|
| 77 |
-
if not conv.get("message"):
|
| 78 |
-
return get_data_error_result(retmsg="messages can not be empty")
|
| 79 |
ConversationService.save(**conv)
|
| 80 |
e, conv = ConversationService.get_by_id(conv["id"])
|
| 81 |
if not e:
|
| 82 |
return get_data_error_result(retmsg="Fail to new session!")
|
| 83 |
conv = conv.to_dict()
|
| 84 |
-
conv[
|
| 85 |
conv["assistant_id"] = conv.pop("dialog_id")
|
| 86 |
-
for message in conv["messages"]:
|
| 87 |
-
message["reference"] = conv.get("reference")
|
| 88 |
del conv["reference"]
|
| 89 |
return get_json_result(data=conv)
|
| 90 |
|
|
@@ -96,31 +87,28 @@ def completion(tenant_id):
|
|
| 96 |
# req = {"conversation_id": "9aaaca4c11d311efa461fa163e197198", "messages": [
|
| 97 |
# {"role": "user", "content": "上海有吗?"}
|
| 98 |
# ]}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
msg = []
|
| 100 |
question = {
|
| 101 |
"content": req.get("question"),
|
| 102 |
"role": "user",
|
| 103 |
"id": str(uuid4())
|
| 104 |
}
|
| 105 |
-
|
| 106 |
-
for m in
|
| 107 |
if m["role"] == "system": continue
|
| 108 |
if m["role"] == "assistant" and not msg: continue
|
| 109 |
-
m["id"] = m.get("id", str(uuid4()))
|
| 110 |
msg.append(m)
|
| 111 |
message_id = msg[-1].get("id")
|
| 112 |
-
conv = ConversationService.query(id=req["id"])
|
| 113 |
-
conv = conv[0]
|
| 114 |
-
if not conv:
|
| 115 |
-
return get_data_error_result(retmsg="Session does not exist")
|
| 116 |
-
if not DialogService.query(id=conv.dialog_id, tenant_id=tenant_id, status=StatusEnum.VALID.value):
|
| 117 |
-
return get_data_error_result(retmsg="You do not own the session")
|
| 118 |
-
conv.message = deepcopy(req["messages"])
|
| 119 |
e, dia = DialogService.get_by_id(conv.dialog_id)
|
| 120 |
-
if not e:
|
| 121 |
-
return get_data_error_result(retmsg="Dialog not found!")
|
| 122 |
del req["id"]
|
| 123 |
-
del req["messages"]
|
| 124 |
|
| 125 |
if not conv.reference:
|
| 126 |
conv.reference = []
|
|
@@ -166,3 +154,110 @@ def completion(tenant_id):
|
|
| 166 |
ConversationService.update_by_id(conv.id, conv.to_dict())
|
| 167 |
break
|
| 168 |
return get_json_result(data=answer)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
# limitations under the License.
|
| 15 |
#
|
| 16 |
import json
|
|
|
|
| 17 |
from uuid import uuid4
|
| 18 |
|
| 19 |
from flask import request, Response
|
| 20 |
|
| 21 |
from api.db import StatusEnum
|
| 22 |
from api.db.services.dialog_service import DialogService, ConversationService, chat
|
| 23 |
+
from api.settings import RetCode
|
| 24 |
from api.utils import get_uuid
|
| 25 |
from api.utils.api_utils import get_data_error_result
|
| 26 |
from api.utils.api_utils import get_json_result, token_required
|
|
|
|
| 31 |
def set_conversation(tenant_id):
|
| 32 |
req = request.json
|
| 33 |
conv_id = req.get("id")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
if "assistant_id" in req:
|
| 35 |
req["dialog_id"] = req.pop("assistant_id")
|
| 36 |
if "id" in req:
|
|
|
|
| 46 |
return get_data_error_result(retmsg="You do not own the assistant")
|
| 47 |
if "dialog_id" in req and not req.get("dialog_id"):
|
| 48 |
return get_data_error_result(retmsg="assistant_id can not be empty.")
|
| 49 |
+
if "message" in req:
|
| 50 |
+
return get_data_error_result(retmsg="message can not be change")
|
| 51 |
+
if "reference" in req:
|
| 52 |
+
return get_data_error_result(retmsg="reference can not be change")
|
| 53 |
if "name" in req and not req.get("name"):
|
| 54 |
return get_data_error_result(retmsg="name can not be empty.")
|
|
|
|
|
|
|
| 55 |
if not ConversationService.update_by_id(conv_id, req):
|
| 56 |
return get_data_error_result(retmsg="Session updates error")
|
| 57 |
return get_json_result(data=True)
|
|
|
|
| 65 |
"id": get_uuid(),
|
| 66 |
"dialog_id": req["dialog_id"],
|
| 67 |
"name": req.get("name", "New session"),
|
| 68 |
+
"message": [{"role": "assistant", "content": "Hi! I am your assistant,can I help you?"}]
|
|
|
|
| 69 |
}
|
| 70 |
if not conv.get("name"):
|
| 71 |
return get_data_error_result(retmsg="name can not be empty.")
|
|
|
|
|
|
|
| 72 |
ConversationService.save(**conv)
|
| 73 |
e, conv = ConversationService.get_by_id(conv["id"])
|
| 74 |
if not e:
|
| 75 |
return get_data_error_result(retmsg="Fail to new session!")
|
| 76 |
conv = conv.to_dict()
|
| 77 |
+
conv['messages'] = conv.pop("message")
|
| 78 |
conv["assistant_id"] = conv.pop("dialog_id")
|
|
|
|
|
|
|
| 79 |
del conv["reference"]
|
| 80 |
return get_json_result(data=conv)
|
| 81 |
|
|
|
|
| 87 |
# req = {"conversation_id": "9aaaca4c11d311efa461fa163e197198", "messages": [
|
| 88 |
# {"role": "user", "content": "上海有吗?"}
|
| 89 |
# ]}
|
| 90 |
+
if "id" not in req:
|
| 91 |
+
return get_data_error_result(retmsg="id is required")
|
| 92 |
+
conv = ConversationService.query(id=req["id"])
|
| 93 |
+
if not conv:
|
| 94 |
+
return get_data_error_result(retmsg="Session does not exist")
|
| 95 |
+
conv = conv[0]
|
| 96 |
+
if not DialogService.query(id=conv.dialog_id, tenant_id=tenant_id, status=StatusEnum.VALID.value):
|
| 97 |
+
return get_data_error_result(retmsg="You do not own the session")
|
| 98 |
msg = []
|
| 99 |
question = {
|
| 100 |
"content": req.get("question"),
|
| 101 |
"role": "user",
|
| 102 |
"id": str(uuid4())
|
| 103 |
}
|
| 104 |
+
conv.message.append(question)
|
| 105 |
+
for m in conv.message:
|
| 106 |
if m["role"] == "system": continue
|
| 107 |
if m["role"] == "assistant" and not msg: continue
|
|
|
|
| 108 |
msg.append(m)
|
| 109 |
message_id = msg[-1].get("id")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
e, dia = DialogService.get_by_id(conv.dialog_id)
|
|
|
|
|
|
|
| 111 |
del req["id"]
|
|
|
|
| 112 |
|
| 113 |
if not conv.reference:
|
| 114 |
conv.reference = []
|
|
|
|
| 154 |
ConversationService.update_by_id(conv.id, conv.to_dict())
|
| 155 |
break
|
| 156 |
return get_json_result(data=answer)
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
@manager.route('/get', methods=['GET'])
|
| 160 |
+
@token_required
|
| 161 |
+
def get(tenant_id):
|
| 162 |
+
req = request.args
|
| 163 |
+
if "id" not in req:
|
| 164 |
+
return get_data_error_result(retmsg="id is required")
|
| 165 |
+
conv_id = req["id"]
|
| 166 |
+
conv = ConversationService.query(id=conv_id)
|
| 167 |
+
if not conv:
|
| 168 |
+
return get_data_error_result(retmsg="Session does not exist")
|
| 169 |
+
if not DialogService.query(id=conv[0].dialog_id, tenant_id=tenant_id, status=StatusEnum.VALID.value):
|
| 170 |
+
return get_data_error_result(retmsg="You do not own the session")
|
| 171 |
+
conv = conv[0].to_dict()
|
| 172 |
+
conv['messages'] = conv.pop("message")
|
| 173 |
+
conv["assistant_id"] = conv.pop("dialog_id")
|
| 174 |
+
if conv["reference"]:
|
| 175 |
+
messages = conv["messages"]
|
| 176 |
+
message_num = 0
|
| 177 |
+
chunk_num = 0
|
| 178 |
+
while message_num < len(messages):
|
| 179 |
+
if message_num != 0 and messages[message_num]["role"] != "user":
|
| 180 |
+
chunk_list = []
|
| 181 |
+
if "chunks" in conv["reference"][chunk_num]:
|
| 182 |
+
chunks = conv["reference"][chunk_num]["chunks"]
|
| 183 |
+
for chunk in chunks:
|
| 184 |
+
new_chunk = {
|
| 185 |
+
"id": chunk["chunk_id"],
|
| 186 |
+
"content": chunk["content_with_weight"],
|
| 187 |
+
"document_id": chunk["doc_id"],
|
| 188 |
+
"document_name": chunk["docnm_kwd"],
|
| 189 |
+
"knowledgebase_id": chunk["kb_id"],
|
| 190 |
+
"image_id": chunk["img_id"],
|
| 191 |
+
"similarity": chunk["similarity"],
|
| 192 |
+
"vector_similarity": chunk["vector_similarity"],
|
| 193 |
+
"term_similarity": chunk["term_similarity"],
|
| 194 |
+
"positions": chunk["positions"],
|
| 195 |
+
}
|
| 196 |
+
chunk_list.append(new_chunk)
|
| 197 |
+
chunk_num += 1
|
| 198 |
+
messages[message_num]["reference"] = chunk_list
|
| 199 |
+
message_num += 1
|
| 200 |
+
del conv["reference"]
|
| 201 |
+
return get_json_result(data=conv)
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
@manager.route('/list', methods=["GET"])
|
| 205 |
+
@token_required
|
| 206 |
+
def list(tenant_id):
|
| 207 |
+
assistant_id = request.args["assistant_id"]
|
| 208 |
+
if not DialogService.query(tenant_id=tenant_id, id=assistant_id, status=StatusEnum.VALID.value):
|
| 209 |
+
return get_json_result(
|
| 210 |
+
data=False, retmsg=f'Only owner of the assistant is authorized for this operation.',
|
| 211 |
+
retcode=RetCode.OPERATING_ERROR)
|
| 212 |
+
convs = ConversationService.query(
|
| 213 |
+
dialog_id=assistant_id,
|
| 214 |
+
order_by=ConversationService.model.create_time,
|
| 215 |
+
reverse=True)
|
| 216 |
+
convs = [d.to_dict() for d in convs]
|
| 217 |
+
for conv in convs:
|
| 218 |
+
conv['messages'] = conv.pop("message")
|
| 219 |
+
conv["assistant_id"] = conv.pop("dialog_id")
|
| 220 |
+
if conv["reference"]:
|
| 221 |
+
messages = conv["messages"]
|
| 222 |
+
message_num = 0
|
| 223 |
+
chunk_num = 0
|
| 224 |
+
while message_num < len(messages):
|
| 225 |
+
if message_num != 0 and messages[message_num]["role"] != "user":
|
| 226 |
+
chunk_list = []
|
| 227 |
+
if "chunks" in conv["reference"][chunk_num]:
|
| 228 |
+
chunks = conv["reference"][chunk_num]["chunks"]
|
| 229 |
+
for chunk in chunks:
|
| 230 |
+
new_chunk = {
|
| 231 |
+
"id": chunk["chunk_id"],
|
| 232 |
+
"content": chunk["content_with_weight"],
|
| 233 |
+
"document_id": chunk["doc_id"],
|
| 234 |
+
"document_name": chunk["docnm_kwd"],
|
| 235 |
+
"knowledgebase_id": chunk["kb_id"],
|
| 236 |
+
"image_id": chunk["img_id"],
|
| 237 |
+
"similarity": chunk["similarity"],
|
| 238 |
+
"vector_similarity": chunk["vector_similarity"],
|
| 239 |
+
"term_similarity": chunk["term_similarity"],
|
| 240 |
+
"positions": chunk["positions"],
|
| 241 |
+
}
|
| 242 |
+
chunk_list.append(new_chunk)
|
| 243 |
+
chunk_num += 1
|
| 244 |
+
messages[message_num]["reference"] = chunk_list
|
| 245 |
+
message_num += 1
|
| 246 |
+
del conv["reference"]
|
| 247 |
+
return get_json_result(data=convs)
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
@manager.route('/delete', methods=["DELETE"])
|
| 251 |
+
@token_required
|
| 252 |
+
def delete(tenant_id):
|
| 253 |
+
id = request.args.get("id")
|
| 254 |
+
if not id:
|
| 255 |
+
return get_data_error_result(retmsg="`id` is required in deleting operation")
|
| 256 |
+
conv = ConversationService.query(id=id)
|
| 257 |
+
if not conv:
|
| 258 |
+
return get_data_error_result(retmsg="Session doesn't exist")
|
| 259 |
+
conv = conv[0]
|
| 260 |
+
if not DialogService.query(id=conv.dialog_id, tenant_id=tenant_id, status=StatusEnum.VALID.value):
|
| 261 |
+
return get_data_error_result(retmsg="You don't own the session")
|
| 262 |
+
ConversationService.delete_by_id(id)
|
| 263 |
+
return get_json_result(data=True)
|
sdk/python/ragflow/__init__.py
CHANGED
|
@@ -4,4 +4,5 @@ __version__ = importlib.metadata.version("ragflow")
|
|
| 4 |
|
| 5 |
from .ragflow import RAGFlow
|
| 6 |
from .modules.dataset import DataSet
|
| 7 |
-
from .modules.
|
|
|
|
|
|
| 4 |
|
| 5 |
from .ragflow import RAGFlow
|
| 6 |
from .modules.dataset import DataSet
|
| 7 |
+
from .modules.assistant import Assistant
|
| 8 |
+
from .modules.session import Session
|
sdk/python/ragflow/modules/{chat_assistant.py → assistant.py}
RENAMED
|
@@ -1,71 +1,86 @@
|
|
| 1 |
-
from typing import List
|
| 2 |
-
|
| 3 |
-
from .base import Base
|
| 4 |
-
from .session import Session
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
class Assistant(Base):
|
| 8 |
-
def __init__(self, rag, res_dict):
|
| 9 |
-
self.id = ""
|
| 10 |
-
self.name = "assistant"
|
| 11 |
-
self.avatar = "path/to/avatar"
|
| 12 |
-
self.knowledgebases = ["kb1"]
|
| 13 |
-
self.llm = Assistant.LLM(rag, {})
|
| 14 |
-
self.prompt = Assistant.Prompt(rag, {})
|
| 15 |
-
super().__init__(rag, res_dict)
|
| 16 |
-
|
| 17 |
-
class LLM(Base):
|
| 18 |
-
def __init__(self, rag, res_dict):
|
| 19 |
-
self.model_name = "deepseek-chat"
|
| 20 |
-
self.temperature = 0.1
|
| 21 |
-
self.top_p = 0.3
|
| 22 |
-
self.presence_penalty = 0.4
|
| 23 |
-
self.frequency_penalty = 0.7
|
| 24 |
-
self.max_tokens = 512
|
| 25 |
-
super().__init__(rag, res_dict)
|
| 26 |
-
|
| 27 |
-
class Prompt(Base):
|
| 28 |
-
def __init__(self, rag, res_dict):
|
| 29 |
-
self.similarity_threshold = 0.2
|
| 30 |
-
self.keywords_similarity_weight = 0.7
|
| 31 |
-
self.top_n = 8
|
| 32 |
-
self.variables = [{"key": "knowledge", "optional": True}]
|
| 33 |
-
self.rerank_model = None
|
| 34 |
-
self.empty_response = None
|
| 35 |
-
self.opener = "Hi! I'm your assistant, what can I do for you?"
|
| 36 |
-
self.show_quote = True
|
| 37 |
-
self.prompt = (
|
| 38 |
-
"You are an intelligent assistant. Please summarize the content of the knowledge base to answer the question. "
|
| 39 |
-
"Please list the data in the knowledge base and answer in detail. When all knowledge base content is irrelevant to the question, "
|
| 40 |
-
"your answer must include the sentence 'The answer you are looking for is not found in the knowledge base!' "
|
| 41 |
-
"Answers need to consider chat history.\nHere is the knowledge base:\n{knowledge}\nThe above is the knowledge base."
|
| 42 |
-
)
|
| 43 |
-
super().__init__(rag, res_dict)
|
| 44 |
-
|
| 45 |
-
def save(self) -> bool:
|
| 46 |
-
res = self.post('/assistant/save',
|
| 47 |
-
{"id": self.id, "name": self.name, "avatar": self.avatar, "knowledgebases": self.knowledgebases,
|
| 48 |
-
"llm": self.llm.to_json(), "prompt": self.prompt.to_json()
|
| 49 |
-
})
|
| 50 |
-
res = res.json()
|
| 51 |
-
if res.get("retmsg") == "success": return True
|
| 52 |
-
raise Exception(res["retmsg"])
|
| 53 |
-
|
| 54 |
-
def delete(self) -> bool:
|
| 55 |
-
res = self.rm('/assistant/delete',
|
| 56 |
-
{"id": self.id})
|
| 57 |
-
res = res.json()
|
| 58 |
-
if res.get("retmsg") == "success": return True
|
| 59 |
-
raise Exception(res["retmsg"])
|
| 60 |
-
|
| 61 |
-
def create_session(self, name: str = "New session"
|
| 62 |
-
{"
|
| 63 |
-
|
| 64 |
-
res
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import List
|
| 2 |
+
|
| 3 |
+
from .base import Base
|
| 4 |
+
from .session import Session
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class Assistant(Base):
|
| 8 |
+
def __init__(self, rag, res_dict):
|
| 9 |
+
self.id = ""
|
| 10 |
+
self.name = "assistant"
|
| 11 |
+
self.avatar = "path/to/avatar"
|
| 12 |
+
self.knowledgebases = ["kb1"]
|
| 13 |
+
self.llm = Assistant.LLM(rag, {})
|
| 14 |
+
self.prompt = Assistant.Prompt(rag, {})
|
| 15 |
+
super().__init__(rag, res_dict)
|
| 16 |
+
|
| 17 |
+
class LLM(Base):
|
| 18 |
+
def __init__(self, rag, res_dict):
|
| 19 |
+
self.model_name = "deepseek-chat"
|
| 20 |
+
self.temperature = 0.1
|
| 21 |
+
self.top_p = 0.3
|
| 22 |
+
self.presence_penalty = 0.4
|
| 23 |
+
self.frequency_penalty = 0.7
|
| 24 |
+
self.max_tokens = 512
|
| 25 |
+
super().__init__(rag, res_dict)
|
| 26 |
+
|
| 27 |
+
class Prompt(Base):
|
| 28 |
+
def __init__(self, rag, res_dict):
|
| 29 |
+
self.similarity_threshold = 0.2
|
| 30 |
+
self.keywords_similarity_weight = 0.7
|
| 31 |
+
self.top_n = 8
|
| 32 |
+
self.variables = [{"key": "knowledge", "optional": True}]
|
| 33 |
+
self.rerank_model = None
|
| 34 |
+
self.empty_response = None
|
| 35 |
+
self.opener = "Hi! I'm your assistant, what can I do for you?"
|
| 36 |
+
self.show_quote = True
|
| 37 |
+
self.prompt = (
|
| 38 |
+
"You are an intelligent assistant. Please summarize the content of the knowledge base to answer the question. "
|
| 39 |
+
"Please list the data in the knowledge base and answer in detail. When all knowledge base content is irrelevant to the question, "
|
| 40 |
+
"your answer must include the sentence 'The answer you are looking for is not found in the knowledge base!' "
|
| 41 |
+
"Answers need to consider chat history.\nHere is the knowledge base:\n{knowledge}\nThe above is the knowledge base."
|
| 42 |
+
)
|
| 43 |
+
super().__init__(rag, res_dict)
|
| 44 |
+
|
| 45 |
+
def save(self) -> bool:
|
| 46 |
+
res = self.post('/assistant/save',
|
| 47 |
+
{"id": self.id, "name": self.name, "avatar": self.avatar, "knowledgebases": self.knowledgebases,
|
| 48 |
+
"llm": self.llm.to_json(), "prompt": self.prompt.to_json()
|
| 49 |
+
})
|
| 50 |
+
res = res.json()
|
| 51 |
+
if res.get("retmsg") == "success": return True
|
| 52 |
+
raise Exception(res["retmsg"])
|
| 53 |
+
|
| 54 |
+
def delete(self) -> bool:
|
| 55 |
+
res = self.rm('/assistant/delete',
|
| 56 |
+
{"id": self.id})
|
| 57 |
+
res = res.json()
|
| 58 |
+
if res.get("retmsg") == "success": return True
|
| 59 |
+
raise Exception(res["retmsg"])
|
| 60 |
+
|
| 61 |
+
def create_session(self, name: str = "New session") -> Session:
|
| 62 |
+
res = self.post("/session/save", {"name": name, "assistant_id": self.id})
|
| 63 |
+
res = res.json()
|
| 64 |
+
if res.get("retmsg") == "success":
|
| 65 |
+
return Session(self.rag, res['data'])
|
| 66 |
+
raise Exception(res["retmsg"])
|
| 67 |
+
|
| 68 |
+
def list_session(self) -> List[Session]:
|
| 69 |
+
res = self.get('/session/list', {"assistant_id": self.id})
|
| 70 |
+
res = res.json()
|
| 71 |
+
if res.get("retmsg") == "success":
|
| 72 |
+
result_list = []
|
| 73 |
+
for data in res["data"]:
|
| 74 |
+
result_list.append(Session(self.rag, data))
|
| 75 |
+
return result_list
|
| 76 |
+
raise Exception(res["retmsg"])
|
| 77 |
+
|
| 78 |
+
def get_session(self, id) -> Session:
|
| 79 |
+
res = self.get("/session/get", {"id": id})
|
| 80 |
+
res = res.json()
|
| 81 |
+
if res.get("retmsg") == "success":
|
| 82 |
+
return Session(self.rag, res["data"])
|
| 83 |
+
raise Exception(res["retmsg"])
|
| 84 |
+
|
| 85 |
+
def get_prologue(self):
|
| 86 |
+
return self.prompt.opener
|
sdk/python/ragflow/modules/base.py
CHANGED
|
@@ -18,8 +18,8 @@ class Base(object):
|
|
| 18 |
pr[name] = value
|
| 19 |
return pr
|
| 20 |
|
| 21 |
-
def post(self, path, param):
|
| 22 |
-
res = self.rag.post(path, param)
|
| 23 |
return res
|
| 24 |
|
| 25 |
def get(self, path, params):
|
|
|
|
| 18 |
pr[name] = value
|
| 19 |
return pr
|
| 20 |
|
| 21 |
+
def post(self, path, param, stream=False):
|
| 22 |
+
res = self.rag.post(path, param, stream=stream)
|
| 23 |
return res
|
| 24 |
|
| 25 |
def get(self, path, params):
|
sdk/python/ragflow/modules/session.py
CHANGED
|
@@ -8,17 +8,17 @@ class Session(Base):
|
|
| 8 |
self.id = None
|
| 9 |
self.name = "New session"
|
| 10 |
self.messages = [{"role": "assistant", "content": "Hi! I am your assistant,can I help you?"}]
|
| 11 |
-
|
| 12 |
self.assistant_id = None
|
| 13 |
super().__init__(rag, res_dict)
|
| 14 |
|
| 15 |
def chat(self, question: str, stream: bool = False):
|
|
|
|
|
|
|
|
|
|
| 16 |
res = self.post("/session/completion",
|
| 17 |
-
{"id": self.id, "question": question, "stream": stream,
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
message_list = []
|
| 21 |
-
for line in response_lines:
|
| 22 |
if line.startswith("data:"):
|
| 23 |
json_data = json.loads(line[5:])
|
| 24 |
if json_data["data"] != True:
|
|
@@ -26,26 +26,49 @@ class Session(Base):
|
|
| 26 |
reference = json_data["data"]["reference"]
|
| 27 |
temp_dict = {
|
| 28 |
"content": answer,
|
| 29 |
-
"role": "assistant"
|
| 30 |
-
"reference": reference
|
| 31 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
message = Message(self.rag, temp_dict)
|
| 33 |
-
|
| 34 |
-
return message_list
|
| 35 |
|
| 36 |
def save(self):
|
| 37 |
res = self.post("/session/save",
|
| 38 |
-
{"id": self.id, "
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
res = res.json()
|
| 40 |
if res.get("retmsg") == "success": return True
|
| 41 |
raise Exception(res.get("retmsg"))
|
| 42 |
|
|
|
|
| 43 |
class Message(Base):
|
| 44 |
def __init__(self, rag, res_dict):
|
| 45 |
-
self.content = "
|
| 46 |
-
self.reference =
|
| 47 |
self.role = "assistant"
|
| 48 |
-
self.prompt=None
|
| 49 |
super().__init__(rag, res_dict)
|
| 50 |
|
| 51 |
|
|
|
|
| 8 |
self.id = None
|
| 9 |
self.name = "New session"
|
| 10 |
self.messages = [{"role": "assistant", "content": "Hi! I am your assistant,can I help you?"}]
|
|
|
|
| 11 |
self.assistant_id = None
|
| 12 |
super().__init__(rag, res_dict)
|
| 13 |
|
| 14 |
def chat(self, question: str, stream: bool = False):
|
| 15 |
+
for message in self.messages:
|
| 16 |
+
if "reference" in message:
|
| 17 |
+
message.pop("reference")
|
| 18 |
res = self.post("/session/completion",
|
| 19 |
+
{"id": self.id, "question": question, "stream": stream}, stream=True)
|
| 20 |
+
for line in res.iter_lines():
|
| 21 |
+
line = line.decode("utf-8")
|
|
|
|
|
|
|
| 22 |
if line.startswith("data:"):
|
| 23 |
json_data = json.loads(line[5:])
|
| 24 |
if json_data["data"] != True:
|
|
|
|
| 26 |
reference = json_data["data"]["reference"]
|
| 27 |
temp_dict = {
|
| 28 |
"content": answer,
|
| 29 |
+
"role": "assistant"
|
|
|
|
| 30 |
}
|
| 31 |
+
if "chunks" in reference:
|
| 32 |
+
chunks = reference["chunks"]
|
| 33 |
+
chunk_list = []
|
| 34 |
+
for chunk in chunks:
|
| 35 |
+
new_chunk = {
|
| 36 |
+
"id": chunk["chunk_id"],
|
| 37 |
+
"content": chunk["content_with_weight"],
|
| 38 |
+
"document_id": chunk["doc_id"],
|
| 39 |
+
"document_name": chunk["docnm_kwd"],
|
| 40 |
+
"knowledgebase_id": chunk["kb_id"],
|
| 41 |
+
"image_id": chunk["img_id"],
|
| 42 |
+
"similarity": chunk["similarity"],
|
| 43 |
+
"vector_similarity": chunk["vector_similarity"],
|
| 44 |
+
"term_similarity": chunk["term_similarity"],
|
| 45 |
+
"positions": chunk["positions"],
|
| 46 |
+
}
|
| 47 |
+
chunk_list.append(new_chunk)
|
| 48 |
+
temp_dict["reference"] = chunk_list
|
| 49 |
message = Message(self.rag, temp_dict)
|
| 50 |
+
yield message
|
|
|
|
| 51 |
|
| 52 |
def save(self):
|
| 53 |
res = self.post("/session/save",
|
| 54 |
+
{"id": self.id, "assistant_id": self.assistant_id, "name": self.name})
|
| 55 |
+
res = res.json()
|
| 56 |
+
if res.get("retmsg") == "success": return True
|
| 57 |
+
raise Exception(res.get("retmsg"))
|
| 58 |
+
|
| 59 |
+
def delete(self):
|
| 60 |
+
res = self.rm("/session/delete", {"id": self.id})
|
| 61 |
res = res.json()
|
| 62 |
if res.get("retmsg") == "success": return True
|
| 63 |
raise Exception(res.get("retmsg"))
|
| 64 |
|
| 65 |
+
|
| 66 |
class Message(Base):
|
| 67 |
def __init__(self, rag, res_dict):
|
| 68 |
+
self.content = "Hi! I am your assistant,can I help you?"
|
| 69 |
+
self.reference = None
|
| 70 |
self.role = "assistant"
|
| 71 |
+
self.prompt = None
|
| 72 |
super().__init__(rag, res_dict)
|
| 73 |
|
| 74 |
|
sdk/python/ragflow/ragflow.py
CHANGED
|
@@ -17,7 +17,7 @@ from typing import List
|
|
| 17 |
|
| 18 |
import requests
|
| 19 |
|
| 20 |
-
from .modules.
|
| 21 |
from .modules.dataset import DataSet
|
| 22 |
|
| 23 |
|
|
@@ -30,8 +30,8 @@ class RAGFlow:
|
|
| 30 |
self.api_url = f"{base_url}/api/{version}"
|
| 31 |
self.authorization_header = {"Authorization": "{} {}".format("Bearer", self.user_key)}
|
| 32 |
|
| 33 |
-
def post(self, path, param):
|
| 34 |
-
res = requests.post(url=self.api_url + path, json=param, headers=self.authorization_header)
|
| 35 |
return res
|
| 36 |
|
| 37 |
def get(self, path, params=None):
|
|
|
|
| 17 |
|
| 18 |
import requests
|
| 19 |
|
| 20 |
+
from .modules.assistant import Assistant
|
| 21 |
from .modules.dataset import DataSet
|
| 22 |
|
| 23 |
|
|
|
|
| 30 |
self.api_url = f"{base_url}/api/{version}"
|
| 31 |
self.authorization_header = {"Authorization": "{} {}".format("Bearer", self.user_key)}
|
| 32 |
|
| 33 |
+
def post(self, path, param, stream=False):
|
| 34 |
+
res = requests.post(url=self.api_url + path, json=param, headers=self.authorization_header, stream=stream)
|
| 35 |
return res
|
| 36 |
|
| 37 |
def get(self, path, params=None):
|
sdk/python/test/t_session.py
CHANGED
|
@@ -1,27 +1,60 @@
|
|
| 1 |
-
from ragflow import RAGFlow
|
| 2 |
|
| 3 |
from common import API_KEY, HOST_ADDRESS
|
| 4 |
|
| 5 |
|
| 6 |
-
class
|
| 7 |
def test_create_session(self):
|
| 8 |
rag = RAGFlow(API_KEY, HOST_ADDRESS)
|
| 9 |
kb = rag.create_dataset(name="test_create_session")
|
| 10 |
assistant = rag.create_assistant(name="test_create_session", knowledgebases=[kb])
|
| 11 |
session = assistant.create_session()
|
| 12 |
-
assert
|
| 13 |
-
assert session is not None, "Failed to create a session."
|
| 14 |
|
| 15 |
def test_create_chat_with_success(self):
|
| 16 |
rag = RAGFlow(API_KEY, HOST_ADDRESS)
|
| 17 |
kb = rag.create_dataset(name="test_create_chat")
|
| 18 |
assistant = rag.create_assistant(name="test_create_chat", knowledgebases=[kb])
|
| 19 |
session = assistant.create_session()
|
| 20 |
-
assert session is not None, "Failed to create a session."
|
| 21 |
-
prologue = assistant.get_prologue()
|
| 22 |
-
assert isinstance(prologue, str), "Prologue is not a string."
|
| 23 |
-
assert len(prologue) > 0, "Prologue is empty."
|
| 24 |
question = "What is AI"
|
| 25 |
-
ans
|
| 26 |
-
|
| 27 |
-
assert
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from ragflow import RAGFlow,Session
|
| 2 |
|
| 3 |
from common import API_KEY, HOST_ADDRESS
|
| 4 |
|
| 5 |
|
| 6 |
+
class TestSession:
|
| 7 |
def test_create_session(self):
|
| 8 |
rag = RAGFlow(API_KEY, HOST_ADDRESS)
|
| 9 |
kb = rag.create_dataset(name="test_create_session")
|
| 10 |
assistant = rag.create_assistant(name="test_create_session", knowledgebases=[kb])
|
| 11 |
session = assistant.create_session()
|
| 12 |
+
assert isinstance(session,Session), "Failed to create a session."
|
|
|
|
| 13 |
|
| 14 |
def test_create_chat_with_success(self):
|
| 15 |
rag = RAGFlow(API_KEY, HOST_ADDRESS)
|
| 16 |
kb = rag.create_dataset(name="test_create_chat")
|
| 17 |
assistant = rag.create_assistant(name="test_create_chat", knowledgebases=[kb])
|
| 18 |
session = assistant.create_session()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
question = "What is AI"
|
| 20 |
+
for ans in session.chat(question, stream=True):
|
| 21 |
+
pass
|
| 22 |
+
assert ans.content!="\n**ERROR**", "Please check this error."
|
| 23 |
+
|
| 24 |
+
def test_delete_session_with_success(self):
|
| 25 |
+
rag = RAGFlow(API_KEY, HOST_ADDRESS)
|
| 26 |
+
kb = rag.create_dataset(name="test_delete_session")
|
| 27 |
+
assistant = rag.create_assistant(name="test_delete_session",knowledgebases=[kb])
|
| 28 |
+
session=assistant.create_session()
|
| 29 |
+
res=session.delete()
|
| 30 |
+
assert res, "Failed to delete the dataset."
|
| 31 |
+
|
| 32 |
+
def test_update_session_with_success(self):
|
| 33 |
+
rag=RAGFlow(API_KEY,HOST_ADDRESS)
|
| 34 |
+
kb=rag.create_dataset(name="test_update_session")
|
| 35 |
+
assistant = rag.create_assistant(name="test_update_session",knowledgebases=[kb])
|
| 36 |
+
session=assistant.create_session(name="old session")
|
| 37 |
+
session.name="new session"
|
| 38 |
+
res=session.save()
|
| 39 |
+
assert res,"Failed to update the session"
|
| 40 |
+
|
| 41 |
+
def test_get_session_with_success(self):
|
| 42 |
+
rag=RAGFlow(API_KEY,HOST_ADDRESS)
|
| 43 |
+
kb=rag.create_dataset(name="test_get_session")
|
| 44 |
+
assistant = rag.create_assistant(name="test_get_session",knowledgebases=[kb])
|
| 45 |
+
session = assistant.create_session()
|
| 46 |
+
session_2= assistant.get_session(id=session.id)
|
| 47 |
+
assert session.to_json()==session_2.to_json(),"Failed to get the session"
|
| 48 |
+
|
| 49 |
+
def test_list_session_with_success(self):
|
| 50 |
+
rag=RAGFlow(API_KEY,HOST_ADDRESS)
|
| 51 |
+
kb=rag.create_dataset(name="test_list_session")
|
| 52 |
+
assistant=rag.create_assistant(name="test_list_session",knowledgebases=[kb])
|
| 53 |
+
assistant.create_session("test_1")
|
| 54 |
+
assistant.create_session("test_2")
|
| 55 |
+
sessions=assistant.list_session()
|
| 56 |
+
if isinstance(sessions,list):
|
| 57 |
+
for session in sessions:
|
| 58 |
+
assert isinstance(session,Session),"Non-Session elements exist in the list"
|
| 59 |
+
else :
|
| 60 |
+
assert False,"Failed to retrieve the session list."
|