Skip to content

Commit 87455d7

Browse files
Feiueliuhua
and
liuhua
authored
Add api for list agents and agent seesions (#3835)
### 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]>
1 parent 821fdf0 commit 87455d7

File tree

6 files changed

+141
-8
lines changed

6 files changed

+141
-8
lines changed

api/apps/canvas_app.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ def save():
6565
req["dsl"] = json.loads(req["dsl"])
6666
if "id" not in req:
6767
if UserCanvasService.query(user_id=current_user.id, title=req["title"].strip()):
68-
return server_error_response(ValueError("Duplicated title."))
68+
return get_data_error_result(f"{req['title'].strip()} already exists.")
6969
req["id"] = get_uuid()
7070
if not UserCanvasService.save(**req):
7171
return get_data_error_result(message="Fail to save canvas.")

api/apps/sdk/agent.py

+39
Original file line numberDiff line numberDiff line change
@@ -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

+5-2
Original file line numberDiff line numberDiff line change
@@ -104,9 +104,12 @@ def create(tenant_id):
104104
"parameters": [
105105
{"key": "knowledge", "optional": False}
106106
],
107-
"empty_response": "Sorry! No relevant content was found in the knowledge base!"
107+
"empty_response": "Sorry! No relevant content was found in the knowledge base!",
108+
"quote":True,
109+
"tts":False,
110+
"refine_multiturn":True
108111
}
109-
key_list_2 = ["system", "prologue", "parameters", "empty_response"]
112+
key_list_2 = ["system", "prologue", "parameters", "empty_response","quote","tts","refine_multiturn"]
110113
if "prompt_config" not in req:
111114
req['prompt_config'] = {}
112115
for key in key_list_2:

api/apps/sdk/session.py

+61-5
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,6 @@ def create(tenant_id,chat_id):
6363
@manager.route('/agents/<agent_id>/sessions', methods=['POST'])
6464
@token_required
6565
def create_agent_session(tenant_id, agent_id):
66-
req = request.json
6766
e, cvs = UserCanvasService.get_by_id(agent_id)
6867
if not e:
6968
return get_error_data_result("Agent not found.")
@@ -77,7 +76,7 @@ def create_agent_session(tenant_id, agent_id):
7776
conv = {
7877
"id": get_uuid(),
7978
"dialog_id": cvs.id,
80-
"user_id": req.get("usr_id","") if isinstance(req, dict) else "",
79+
"user_id": tenant_id,
8180
"message": [{"role": "assistant", "content": canvas.get_prologue()}],
8281
"source": "agent",
8382
"dsl":json.loads(cvs.dsl)
@@ -112,13 +111,16 @@ def update(tenant_id,chat_id,session_id):
112111
@manager.route('/chats/<chat_id>/completions', methods=['POST'])
113112
@token_required
114113
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")
115117
req = request.json
116118
if not req.get("session_id"):
117119
conv = {
118120
"id": get_uuid(),
119121
"dialog_id": chat_id,
120122
"name": req.get("name", "New session"),
121-
"message": [{"role": "assistant", "content": "Hi! I am your assistant,can I help you?"}]
123+
"message": [{"role": "assistant", "content": dia[0].prompt_config.get("prologue")}]
122124
}
123125
if not conv.get("name"):
124126
return get_error_data_result(message="`name` can not be empty.")
@@ -133,8 +135,6 @@ def completion(tenant_id, chat_id):
133135
if not conv:
134136
return get_error_data_result(message="Session does not exist")
135137
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")
138138
msg = []
139139
question = {
140140
"content": req.get("question"),
@@ -374,6 +374,8 @@ def sse():
374374
rename_field(result)
375375
return get_result(data=result)
376376

377+
378+
377379
@manager.route('/chats/<chat_id>/sessions', methods=['GET'])
378380
@token_required
379381
def list_session(chat_id,tenant_id):
@@ -427,6 +429,60 @@ def list_session(chat_id,tenant_id):
427429
del conv["reference"]
428430
return get_result(data=convs)
429431

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+
430486

431487
@manager.route('/chats/<chat_id>/sessions', methods=["DELETE"])
432488
@token_required

api/db/services/api_service.py

+16
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,22 @@ def used(cls, token):
3939
class API4ConversationService(CommonService):
4040
model = API4Conversation
4141

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+
4258
@classmethod
4359
@DB.connection_context()
4460
def append_message(cls, id, conversation):

api/db/services/canvas_service.py

+19
Original file line numberDiff line numberDiff line change
@@ -25,3 +25,22 @@ class CanvasTemplateService(CommonService):
2525

2626
class UserCanvasService(CommonService):
2727
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())

0 commit comments

Comments
 (0)