RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.
Go agent-harnessagent-native-databaseagentic-aiagentic-retrievalagentic-searchaiai-agentscontext-enginecontext-engineeringcontext-managementharness-engineeringknowledge-compilationragretrieval-augmented-generationretrieval-harnesssearch-harness
Feat: add 'delete' for agent's sessions api and unify apis of agent sdk (#5525)
Debug Doctor76cb4cd174f2
diff --git a/api/apps/sdk/session.py b/api/apps/sdk/session.pyindex 414f99efda..eb56fce773 100644--- a/api/apps/sdk/session.py+++ b/api/apps/sdk/session.py@@ -511,6 +511,38 @@ def delete(tenant_id, chat_id):return get_result()[email protected]('/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_requireddef ask_about(tenant_id):diff --git a/docs/references/http_api_reference.md b/docs/references/http_api_reference.mdindex f66794a5e0..099139aa50 100644--- a/docs/references/http_api_reference.md+++ b/docs/references/http_api_reference.md@@ -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---diff --git a/docs/references/python_api_reference.md b/docs/references/python_api_reference.mdindex b96ab90680..a025b24087 100644--- a/docs/references/python_api_reference.md+++ b/docs/references/python_api_reference.md@@ -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-##### **kwargsThe parameters in `begin` component.@@ -1494,7 +1486,8 @@ from ragflow_sdk import RAGFlow, Agentrag_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, Agentrag_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:```pythonAgent.list_sessions(- agent_id,- ragpage: 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 RAGFlowrag_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"])+```---diff --git a/sdk/python/ragflow_sdk/modules/agent.py b/sdk/python/ragflow_sdk/modules/agent.pyindex 5579af98dc..42b97a88e8 100644--- a/sdk/python/ragflow_sdk/modules/agent.py+++ b/sdk/python/ragflow_sdk/modules/agent.py@@ -16,11 +16,10 @@from .base import Basefrom .session import Session-import requestsclass Agent(Base):- def __init__(self,rag,res_dict):+ def __init__(self, rag, res_dict):self.id = Noneself.avatar = Noneself.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_listraise 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"))\ No newline at end of filediff --git a/sdk/python/test/test_sdk_api/t_session.py b/sdk/python/test/test_sdk_api/t_session.pyindex 40932fdad0..81cc33eb5e 100644--- a/sdk/python/test/test_sdk_api/t_session.py+++ b/sdk/python/test/test_sdk_api/t_session.py@@ -14,7 +14,7 @@# limitations under the License.#-from ragflow_sdk import RAGFlow, Agent+from ragflow_sdk import RAGFlowfrom common import HOST_ADDRESSimport 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()+[email protected](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"])