liuhua
liuhua
commited on
Commit
·
4d2f593
1
Parent(s):
43bceb7
Add api for list agents and agent seesions (#3835)
Browse files### What problem does this PR solve?
Add api for list agents and agent seesions
### Type of change
- [x] New Feature (non-breaking change which adds functionality)
Co-authored-by: liuhua <[email protected]>
- api/apps/canvas_app.py +1 -1
- api/apps/sdk/agent.py +39 -0
- api/apps/sdk/chat.py +5 -2
- api/apps/sdk/session.py +61 -5
- api/db/services/api_service.py +16 -0
- api/db/services/canvas_service.py +19 -0
api/apps/canvas_app.py
CHANGED
|
@@ -65,7 +65,7 @@ def save():
|
|
| 65 |
req["dsl"] = json.loads(req["dsl"])
|
| 66 |
if "id" not in req:
|
| 67 |
if UserCanvasService.query(user_id=current_user.id, title=req["title"].strip()):
|
| 68 |
-
return
|
| 69 |
req["id"] = get_uuid()
|
| 70 |
if not UserCanvasService.save(**req):
|
| 71 |
return get_data_error_result(message="Fail to save canvas.")
|
|
|
|
| 65 |
req["dsl"] = json.loads(req["dsl"])
|
| 66 |
if "id" not in req:
|
| 67 |
if UserCanvasService.query(user_id=current_user.id, title=req["title"].strip()):
|
| 68 |
+
return get_data_error_result(f"{req['title'].strip()} already exists.")
|
| 69 |
req["id"] = get_uuid()
|
| 70 |
if not UserCanvasService.save(**req):
|
| 71 |
return get_data_error_result(message="Fail to save canvas.")
|
api/apps/sdk/agent.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#
|
| 2 |
+
# Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
#
|
| 16 |
+
|
| 17 |
+
from api.db.services.canvas_service import CanvasTemplateService, UserCanvasService
|
| 18 |
+
from api.utils.api_utils import get_error_data_result, token_required
|
| 19 |
+
from api.utils.api_utils import get_result
|
| 20 |
+
from flask import request
|
| 21 |
+
|
| 22 |
+
@manager.route('/agents', methods=['GET'])
|
| 23 |
+
@token_required
|
| 24 |
+
def list_agents(tenant_id):
|
| 25 |
+
id = request.args.get("id")
|
| 26 |
+
title = request.args.get("title")
|
| 27 |
+
if id or title:
|
| 28 |
+
canvas = UserCanvasService.query(id=id, title=title, user_id=tenant_id)
|
| 29 |
+
if not canvas:
|
| 30 |
+
return get_error_data_result("The agent doesn't exist.")
|
| 31 |
+
page_number = int(request.args.get("page", 1))
|
| 32 |
+
items_per_page = int(request.args.get("page_size", 30))
|
| 33 |
+
orderby = request.args.get("orderby", "update_time")
|
| 34 |
+
if request.args.get("desc") == "False" or request.args.get("desc") == "false":
|
| 35 |
+
desc = False
|
| 36 |
+
else:
|
| 37 |
+
desc = True
|
| 38 |
+
canvas = UserCanvasService.get_list(tenant_id,page_number,items_per_page,orderby,desc,id,title)
|
| 39 |
+
return get_result(data=canvas)
|
api/apps/sdk/chat.py
CHANGED
|
@@ -104,9 +104,12 @@ def create(tenant_id):
|
|
| 104 |
"parameters": [
|
| 105 |
{"key": "knowledge", "optional": False}
|
| 106 |
],
|
| 107 |
-
"empty_response": "Sorry! No relevant content was found in the knowledge base!"
|
|
|
|
|
|
|
|
|
|
| 108 |
}
|
| 109 |
-
key_list_2 = ["system", "prologue", "parameters", "empty_response"]
|
| 110 |
if "prompt_config" not in req:
|
| 111 |
req['prompt_config'] = {}
|
| 112 |
for key in key_list_2:
|
|
|
|
| 104 |
"parameters": [
|
| 105 |
{"key": "knowledge", "optional": False}
|
| 106 |
],
|
| 107 |
+
"empty_response": "Sorry! No relevant content was found in the knowledge base!",
|
| 108 |
+
"quote":True,
|
| 109 |
+
"tts":False,
|
| 110 |
+
"refine_multiturn":True
|
| 111 |
}
|
| 112 |
+
key_list_2 = ["system", "prologue", "parameters", "empty_response","quote","tts","refine_multiturn"]
|
| 113 |
if "prompt_config" not in req:
|
| 114 |
req['prompt_config'] = {}
|
| 115 |
for key in key_list_2:
|
api/apps/sdk/session.py
CHANGED
|
@@ -63,7 +63,6 @@ def create(tenant_id,chat_id):
|
|
| 63 |
@manager.route('/agents/<agent_id>/sessions', methods=['POST'])
|
| 64 |
@token_required
|
| 65 |
def create_agent_session(tenant_id, agent_id):
|
| 66 |
-
req = request.json
|
| 67 |
e, cvs = UserCanvasService.get_by_id(agent_id)
|
| 68 |
if not e:
|
| 69 |
return get_error_data_result("Agent not found.")
|
|
@@ -77,7 +76,7 @@ def create_agent_session(tenant_id, agent_id):
|
|
| 77 |
conv = {
|
| 78 |
"id": get_uuid(),
|
| 79 |
"dialog_id": cvs.id,
|
| 80 |
-
"user_id":
|
| 81 |
"message": [{"role": "assistant", "content": canvas.get_prologue()}],
|
| 82 |
"source": "agent",
|
| 83 |
"dsl":json.loads(cvs.dsl)
|
|
@@ -112,13 +111,16 @@ def update(tenant_id,chat_id,session_id):
|
|
| 112 |
@manager.route('/chats/<chat_id>/completions', methods=['POST'])
|
| 113 |
@token_required
|
| 114 |
def completion(tenant_id, chat_id):
|
|
|
|
|
|
|
|
|
|
| 115 |
req = request.json
|
| 116 |
if not req.get("session_id"):
|
| 117 |
conv = {
|
| 118 |
"id": get_uuid(),
|
| 119 |
"dialog_id": chat_id,
|
| 120 |
"name": req.get("name", "New session"),
|
| 121 |
-
"message": [{"role": "assistant", "content":
|
| 122 |
}
|
| 123 |
if not conv.get("name"):
|
| 124 |
return get_error_data_result(message="`name` can not be empty.")
|
|
@@ -133,8 +135,6 @@ def completion(tenant_id, chat_id):
|
|
| 133 |
if not conv:
|
| 134 |
return get_error_data_result(message="Session does not exist")
|
| 135 |
conv = conv[0]
|
| 136 |
-
if not DialogService.query(id=chat_id, tenant_id=tenant_id, status=StatusEnum.VALID.value):
|
| 137 |
-
return get_error_data_result(message="You do not own the chat")
|
| 138 |
msg = []
|
| 139 |
question = {
|
| 140 |
"content": req.get("question"),
|
|
@@ -374,6 +374,8 @@ def agent_completion(tenant_id, agent_id):
|
|
| 374 |
rename_field(result)
|
| 375 |
return get_result(data=result)
|
| 376 |
|
|
|
|
|
|
|
| 377 |
@manager.route('/chats/<chat_id>/sessions', methods=['GET'])
|
| 378 |
@token_required
|
| 379 |
def list_session(chat_id,tenant_id):
|
|
@@ -427,6 +429,60 @@ def list_session(chat_id,tenant_id):
|
|
| 427 |
del conv["reference"]
|
| 428 |
return get_result(data=convs)
|
| 429 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 430 |
|
| 431 |
@manager.route('/chats/<chat_id>/sessions', methods=["DELETE"])
|
| 432 |
@token_required
|
|
|
|
| 63 |
@manager.route('/agents/<agent_id>/sessions', methods=['POST'])
|
| 64 |
@token_required
|
| 65 |
def create_agent_session(tenant_id, agent_id):
|
|
|
|
| 66 |
e, cvs = UserCanvasService.get_by_id(agent_id)
|
| 67 |
if not e:
|
| 68 |
return get_error_data_result("Agent not found.")
|
|
|
|
| 76 |
conv = {
|
| 77 |
"id": get_uuid(),
|
| 78 |
"dialog_id": cvs.id,
|
| 79 |
+
"user_id": tenant_id,
|
| 80 |
"message": [{"role": "assistant", "content": canvas.get_prologue()}],
|
| 81 |
"source": "agent",
|
| 82 |
"dsl":json.loads(cvs.dsl)
|
|
|
|
| 111 |
@manager.route('/chats/<chat_id>/completions', methods=['POST'])
|
| 112 |
@token_required
|
| 113 |
def completion(tenant_id, chat_id):
|
| 114 |
+
dia= DialogService.query(id=chat_id, tenant_id=tenant_id, status=StatusEnum.VALID.value)
|
| 115 |
+
if not dia:
|
| 116 |
+
return get_error_data_result(message="You do not own the chat")
|
| 117 |
req = request.json
|
| 118 |
if not req.get("session_id"):
|
| 119 |
conv = {
|
| 120 |
"id": get_uuid(),
|
| 121 |
"dialog_id": chat_id,
|
| 122 |
"name": req.get("name", "New session"),
|
| 123 |
+
"message": [{"role": "assistant", "content": dia[0].prompt_config.get("prologue")}]
|
| 124 |
}
|
| 125 |
if not conv.get("name"):
|
| 126 |
return get_error_data_result(message="`name` can not be empty.")
|
|
|
|
| 135 |
if not conv:
|
| 136 |
return get_error_data_result(message="Session does not exist")
|
| 137 |
conv = conv[0]
|
|
|
|
|
|
|
| 138 |
msg = []
|
| 139 |
question = {
|
| 140 |
"content": req.get("question"),
|
|
|
|
| 374 |
rename_field(result)
|
| 375 |
return get_result(data=result)
|
| 376 |
|
| 377 |
+
|
| 378 |
+
|
| 379 |
@manager.route('/chats/<chat_id>/sessions', methods=['GET'])
|
| 380 |
@token_required
|
| 381 |
def list_session(chat_id,tenant_id):
|
|
|
|
| 429 |
del conv["reference"]
|
| 430 |
return get_result(data=convs)
|
| 431 |
|
| 432 |
+
@manager.route('/agents/<agent_id>/sessions', methods=['GET'])
|
| 433 |
+
@token_required
|
| 434 |
+
def list_agent_session(agent_id,tenant_id):
|
| 435 |
+
if not UserCanvasService.query(user_id=tenant_id, id=agent_id):
|
| 436 |
+
return get_error_data_result(message=f"You don't own the agent {agent_id}.")
|
| 437 |
+
id = request.args.get("id")
|
| 438 |
+
if not API4ConversationService.query(id=id,user_id=tenant_id):
|
| 439 |
+
return get_error_data_result(f"You don't own the session {id}")
|
| 440 |
+
page_number = int(request.args.get("page", 1))
|
| 441 |
+
items_per_page = int(request.args.get("page_size", 30))
|
| 442 |
+
orderby = request.args.get("orderby", "update_time")
|
| 443 |
+
if request.args.get("desc") == "False" or request.args.get("desc") == "false":
|
| 444 |
+
desc = False
|
| 445 |
+
else:
|
| 446 |
+
desc = True
|
| 447 |
+
convs = API4ConversationService.get_list(agent_id,tenant_id,page_number,items_per_page,orderby,desc,id)
|
| 448 |
+
if not convs:
|
| 449 |
+
return get_result(data=[])
|
| 450 |
+
for conv in convs:
|
| 451 |
+
conv['messages'] = conv.pop("message")
|
| 452 |
+
infos = conv["messages"]
|
| 453 |
+
for info in infos:
|
| 454 |
+
if "prompt" in info:
|
| 455 |
+
info.pop("prompt")
|
| 456 |
+
conv["agent_id"] = conv.pop("dialog_id")
|
| 457 |
+
if conv["reference"]:
|
| 458 |
+
messages = conv["messages"]
|
| 459 |
+
message_num = 0
|
| 460 |
+
chunk_num = 0
|
| 461 |
+
while message_num < len(messages):
|
| 462 |
+
if message_num != 0 and messages[message_num]["role"] != "user":
|
| 463 |
+
chunk_list = []
|
| 464 |
+
if "chunks" in conv["reference"][chunk_num]:
|
| 465 |
+
chunks = conv["reference"][chunk_num]["chunks"]
|
| 466 |
+
for chunk in chunks:
|
| 467 |
+
new_chunk = {
|
| 468 |
+
"id": chunk["chunk_id"],
|
| 469 |
+
"content": chunk["content"],
|
| 470 |
+
"document_id": chunk["doc_id"],
|
| 471 |
+
"document_name": chunk["docnm_kwd"],
|
| 472 |
+
"dataset_id": chunk["kb_id"],
|
| 473 |
+
"image_id": chunk.get("image_id", ""),
|
| 474 |
+
"similarity": chunk["similarity"],
|
| 475 |
+
"vector_similarity": chunk["vector_similarity"],
|
| 476 |
+
"term_similarity": chunk["term_similarity"],
|
| 477 |
+
"positions": chunk["positions"],
|
| 478 |
+
}
|
| 479 |
+
chunk_list.append(new_chunk)
|
| 480 |
+
chunk_num += 1
|
| 481 |
+
messages[message_num]["reference"] = chunk_list
|
| 482 |
+
message_num += 1
|
| 483 |
+
del conv["reference"]
|
| 484 |
+
return get_result(data=convs)
|
| 485 |
+
|
| 486 |
|
| 487 |
@manager.route('/chats/<chat_id>/sessions', methods=["DELETE"])
|
| 488 |
@token_required
|
api/db/services/api_service.py
CHANGED
|
@@ -39,6 +39,22 @@ class APITokenService(CommonService):
|
|
| 39 |
class API4ConversationService(CommonService):
|
| 40 |
model = API4Conversation
|
| 41 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
@classmethod
|
| 43 |
@DB.connection_context()
|
| 44 |
def append_message(cls, id, conversation):
|
|
|
|
| 39 |
class API4ConversationService(CommonService):
|
| 40 |
model = API4Conversation
|
| 41 |
|
| 42 |
+
@classmethod
|
| 43 |
+
@DB.connection_context()
|
| 44 |
+
def get_list(cls,dialog_id, tenant_id,
|
| 45 |
+
page_number, items_per_page, orderby, desc, id):
|
| 46 |
+
sessions = cls.model.select().where(cls.model.dialog_id ==dialog_id)
|
| 47 |
+
if id:
|
| 48 |
+
sessions = sessions.where(cls.model.id == id)
|
| 49 |
+
if desc:
|
| 50 |
+
sessions = sessions.order_by(cls.model.getter_by(orderby).desc())
|
| 51 |
+
else:
|
| 52 |
+
sessions = sessions.order_by(cls.model.getter_by(orderby).asc())
|
| 53 |
+
sessions = sessions.where(cls.model.user_id == tenant_id)
|
| 54 |
+
sessions = sessions.paginate(page_number, items_per_page)
|
| 55 |
+
|
| 56 |
+
return list(sessions.dicts())
|
| 57 |
+
|
| 58 |
@classmethod
|
| 59 |
@DB.connection_context()
|
| 60 |
def append_message(cls, id, conversation):
|
api/db/services/canvas_service.py
CHANGED
|
@@ -25,3 +25,22 @@ class CanvasTemplateService(CommonService):
|
|
| 25 |
|
| 26 |
class UserCanvasService(CommonService):
|
| 27 |
model = UserCanvas
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
class UserCanvasService(CommonService):
|
| 27 |
model = UserCanvas
|
| 28 |
+
|
| 29 |
+
@classmethod
|
| 30 |
+
@DB.connection_context()
|
| 31 |
+
def get_list(cls, tenant_id,
|
| 32 |
+
page_number, items_per_page, orderby, desc, id, title):
|
| 33 |
+
agents = cls.model.select()
|
| 34 |
+
if id:
|
| 35 |
+
agents = agents.where(cls.model.id == id)
|
| 36 |
+
if title:
|
| 37 |
+
agents = agents.where(cls.model.title == title)
|
| 38 |
+
agents = agents.where(cls.model.user_id == tenant_id)
|
| 39 |
+
if desc:
|
| 40 |
+
agents = agents.order_by(cls.model.getter_by(orderby).desc())
|
| 41 |
+
else:
|
| 42 |
+
agents = agents.order_by(cls.model.getter_by(orderby).asc())
|
| 43 |
+
|
| 44 |
+
agents = agents.paginate(page_number, items_per_page)
|
| 45 |
+
|
| 46 |
+
return list(agents.dicts())
|