Feat: add 'delete' for agent's sessions api and unify apis of agent sdk (#5525)

### What problem does this PR solve?

Add sessions deletion support for agent in http and python api

### Type of change

- [ ] Bug Fix (non-breaking change which fixes an issue)
- [x] New Feature (non-breaking change which adds functionality)
- [ ] Documentation Update
- [x] Refactoring
- [ ] Performance Improvement
- [ ] Other (please describe):

---------

Co-authored-by: Kevin Hu <kevinhu.sh@gmail.com>
This commit is contained in:
Debug Doctor 2025-03-03 17:15:16 +08:00 committed by GitHub
parent 65d7c19979
commit 76cb4cd174
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
5 changed files with 158 additions and 35 deletions

View File

@ -511,6 +511,38 @@ def delete(tenant_id, chat_id):
return get_result()
@manager.route('/agents/<agent_id>/sessions', methods=["DELETE"]) # noqa: F821
@token_required
def delete_agent_session(tenant_id, agent_id):
req = request.json
cvs = UserCanvasService.query(user_id=tenant_id, id=agent_id)
if not cvs:
return get_error_data_result(f"You don't own the agent {agent_id}")
convs = API4ConversationService.query(dialog_id=agent_id)
if not convs:
return get_error_data_result(f"Agent {agent_id} has no sessions")
if not req:
ids = None
else:
ids = req.get("ids")
if not ids:
conv_list = []
for conv in convs:
conv_list.append(conv.id)
else:
conv_list = ids
for session_id in conv_list:
conv = API4ConversationService.query(id=session_id, dialog_id=agent_id)
if not conv:
return get_error_data_result(f"The agent doesn't own the session ${session_id}")
API4ConversationService.delete_by_id(session_id)
return get_result()
@manager.route('/sessions/ask', methods=['POST']) # noqa: F821
@token_required
def ask_about(tenant_id):

View File

@ -2914,6 +2914,62 @@ Failure:
---
### Delete agent's sessions
**DELETE** `/api/v1/agents/{agent_id}/sessions`
Deletes sessions of a agent by ID.
#### Request
- Method: DELETE
- URL: `/api/v1/agents/{agent_id}/sessions`
- Headers:
- `'content-Type: application/json'`
- `'Authorization: Bearer <YOUR_API_KEY>'`
- Body:
- `"ids"`: `list[string]`
##### Request example
```bash
curl --request DELETE \
--url http://{address}/api/v1/agents/{agent_id}/sessions \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer <YOUR_API_KEY>' \
--data '
{
"ids": ["test_1", "test_2"]
}'
```
##### Request Parameters
- `agent_id`: (*Path parameter*)
The ID of the associated agent.
- `"ids"`: (*Body Parameter*), `list[string]`
The IDs of the sessions to delete. If it is not specified, all sessions associated with the specified agent will be deleted.
#### Response
Success:
```json
{
"code": 0
}
```
Failure:
```json
{
"code": 102,
"message": "The agent doesn't own the session cbd31e52f73911ef93b232903b842af6"
}
```
---
## AGENT MANAGEMENT
---

View File

@ -1460,21 +1460,13 @@ while True:
### Create session with agent
```python
Agent.create_session(id,rag, **kwargs) -> Session
Agent.create_session(**kwargs) -> Session
```
Creates a session with the current agent.
#### Parameters
##### id: `str`, *Required*
The id of agent
##### rag:`RAGFlow object`
The RAGFlow object
##### **kwargs
The parameters in `begin` component.
@ -1494,7 +1486,8 @@ from ragflow_sdk import RAGFlow, Agent
rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
AGENT_ID = "AGENT_ID"
session = Agent.create_session(AGENT_ID, rag_object)
agent = rag_object.list_agents(id = AGENT_id)[0]
session = agent.create_session()
```
---
@ -1571,7 +1564,8 @@ from ragflow_sdk import RAGFlow, Agent
rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
AGENT_id = "AGENT_ID"
session = Agent.create_session(AGENT_id, rag_object)
agent = rag_object.list_agents(id = AGENT_id)[0]
session = agent.create_session()
print("\n===== Miss R ====\n")
print("Hello. What can I do for you?")
@ -1592,8 +1586,6 @@ while True:
```python
Agent.list_sessions(
agent_id,
rag
page: int = 1,
page_size: int = 30,
orderby: str = "update_time",
@ -1640,11 +1632,42 @@ The ID of the agent session to retrieve. Defaults to `None`.
from ragflow_sdk import RAGFlow
rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
agent_id = "2710f2269b4611ef8fdf0242ac120006"
sessions=Agent.list_sessions(agent_id,rag_object)
AGENT_id = "AGENT_ID"
agent = rag_object.list_agents(id = AGENT_id)[0]
sessons = agent.list_sessions()
for session in sessions:
print(session)
```
---
### Delete agent's sessions
```python
Agent.delete_sessions(ids: list[str] = None)
```
Deletes sessions of a agent by ID.
#### Parameters
##### ids: `list[str]`
The IDs of the sessions to delete. Defaults to `None`. If it is not specified, all sessions associated with the agent will be deleted.
#### Returns
- Success: No value is returned.
- Failure: `Exception`
#### Examples
```python
from ragflow_sdk import RAGFlow
rag_object = RAGFlow(api_key="<YOUR_API_KEY>", base_url="http://<YOUR_BASE_URL>:9380")
AGENT_id = "AGENT_ID"
agent = rag_object.list_agents(id = AGENT_id)[0]
agent.delete_sessions(ids=["id_1","id_2"])
```
---

View File

@ -16,11 +16,10 @@
from .base import Base
from .session import Session
import requests
class Agent(Base):
def __init__(self,rag,res_dict):
def __init__(self, rag, res_dict):
self.id = None
self.avatar = None
self.canvas_type = None
@ -29,7 +28,7 @@ class Agent(Base):
super().__init__(rag, res_dict)
class Dsl(Base):
def __init__(self,rag,res_dict):
def __init__(self, rag, res_dict):
self.answer = []
self.components = {
"begin": {
@ -64,28 +63,32 @@ class Agent(Base):
self.messages = []
self.path = []
self.reference = []
super().__init__(rag,res_dict)
super().__init__(rag, res_dict)
@staticmethod
def create_session(id,rag,**kwargs) -> Session:
res = requests.post(f"{rag.api_url}/agents/{id}/sessions",headers={"Authorization": f"Bearer {rag.user_key}"},json=kwargs)
def create_session(self, **kwargs) -> Session:
res = self.post(f"/agents/{self.id}/sessions", json=kwargs)
res = res.json()
if res.get("code") == 0:
return Session(rag,res.get("data"))
return Session(self.rag, res.get("data"))
raise Exception(res.get("message"))
@staticmethod
def list_sessions(agent_id,rag,page: int = 1, page_size: int = 30, orderby: str = "create_time", desc: bool = True,
def list_sessions(self, page: int = 1, page_size: int = 30, orderby: str = "create_time", desc: bool = True,
id: str = None) -> list[Session]:
url = f"{rag.api_url}/agents/{agent_id}/sessions"
headers = {"Authorization": f"Bearer {rag.user_key}"}
params = {"page": page, "page_size": page_size, "orderby": orderby, "desc": desc, "id": id}
res = requests.get(url=url,headers=headers,params=params)
res = self.get(f"/agents/{self.id}/sessions",
{"page": page, "page_size": page_size, "orderby": orderby, "desc": desc, "id": id})
res = res.json()
if res.get("code") == 0:
result_list = []
for data in res.get("data"):
temp_agent = Session(rag,data)
temp_agent = Session(self.rag, data)
result_list.append(temp_agent)
return result_list
raise Exception(res.get("message"))
def delete_sessions(self, ids: list[str] | None = None):
res = self.rm(f"/agents/{self.id}/sessions", {"ids": ids})
res = res.json()
if res.get("code") != 0:
raise Exception(res.get("message"))

View File

@ -14,7 +14,7 @@
# limitations under the License.
#
from ragflow_sdk import RAGFlow, Agent
from ragflow_sdk import RAGFlow
from common import HOST_ADDRESS
import pytest
@ -117,20 +117,29 @@ def test_list_sessions_with_success(get_api_key_fixture):
def test_create_agent_session_with_success(get_api_key_fixture):
API_KEY = "ragflow-BkOGNhYjIyN2JiODExZWY5MzVhMDI0Mm"
rag = RAGFlow(API_KEY, HOST_ADDRESS)
Agent.create_session("2e45b5209c1011efa3e90242ac120006", rag)
agent = rag.list_agents(id="2e45b5209c1011efa3e90242ac120006")[0]
agent.create_session()
@pytest.mark.skip(reason="")
def test_create_agent_conversation_with_success(get_api_key_fixture):
API_KEY = "ragflow-BkOGNhYjIyN2JiODExZWY5MzVhMDI0Mm"
rag = RAGFlow(API_KEY, HOST_ADDRESS)
session = Agent.create_session("2e45b5209c1011efa3e90242ac120006", rag)
agent = rag.list_agents(id="2e45b5209c1011efa3e90242ac120006")[0]
session = agent.create_session()
session.ask("What is this job")
@pytest.mark.skip(reason="")
def test_list_agent_sessions_with_success(get_api_key_fixture):
API_KEY = "ragflow-BkOGNhYjIyN2JiODExZWY5MzVhMDI0Mm"
agent_id = "2710f2269b4611ef8fdf0242ac120006"
rag = RAGFlow(API_KEY, HOST_ADDRESS)
Agent.list_sessions(agent_id, rag)
agent = rag.list_agents(id="2e45b5209c1011efa3e90242ac120006")[0]
agent.list_sessions()
@pytest.mark.skip(reason="")
def test_delete_session_of_agent_with_success(get_api_key_fixture):
API_KEY = "ragflow-BkOGNhYjIyN2JiODExZWY5MzVhMDI0Mm"
rag = RAGFlow(API_KEY, HOST_ADDRESS)
agent = rag.list_agents(id="2e45b5209c1011efa3e90242ac120006")[0]
agent.delete_sessions(ids=["test_1"])