Update agent session API, to support uploading files while create a new session (#5039)

### What problem does this PR solve?
Update the agent session API "POST /api/v1/agents/{agent_id}/sessions",
to support uploading files while create a new session:
- currently, the API only supports requesting with a json body. If user
wants to upload a doc or image when create session, like what is already
supported on the web client, we need to update the API.
- if upload an image, ragflow will call image2text, and a user_id is
needed for the image2text model. So we need to send user_id in the API
request. As form-data is needed to upload files, not json body, seems we
need to put the user_id in the url as an optional parameter (currently
user_id is an optional in json body).


### Type of change

- [x] Documentation Update
- [x] Other (please describe):
This commit is contained in:
flygithub 2025-02-18 09:45:40 +08:00 committed by GitHub
parent 9ff825f39d
commit 409310aae9
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 47 additions and 15 deletions

View File

@ -33,7 +33,7 @@ from api.utils import get_uuid
from api.utils.api_utils import get_error_data_result
from api.utils.api_utils import get_result, token_required
from api.db.services.llm_service import LLMBundle
from api.db.services.file_service import FileService
@manager.route('/chats/<chat_id>/sessions', methods=['POST']) # noqa: F821
@ -68,6 +68,11 @@ def create(tenant_id, chat_id):
@token_required
def create_agent_session(tenant_id, agent_id):
req = request.json
if not request.is_json:
req = request.form
files = request.files
user_id = request.args.get('user_id', '')
e, cvs = UserCanvasService.get_by_id(agent_id)
if not e:
return get_error_data_result("Agent not found.")
@ -84,15 +89,33 @@ def create_agent_session(tenant_id, agent_id):
if query:
for ele in query:
if not ele["optional"]:
if not req.get(ele["key"]):
return get_error_data_result(f"`{ele['key']}` is required")
ele["value"] = req[ele["key"]]
if ele["optional"]:
if req.get(ele["key"]):
ele["value"] = req[ele['key']]
if ele["type"] == "file":
if files is None or not files.get(ele["key"]):
return get_error_data_result(f"`{ele['key']}` with type `{ele['type']}` is required")
upload_file = files.get(ele["key"])
file_content = FileService.parse_docs([upload_file], user_id)
file_name = upload_file.filename
ele["value"] = file_name + "\n" + file_content
else:
if "value" in ele:
ele.pop("value")
if req is None or not req.get(ele["key"]):
return get_error_data_result(f"`{ele['key']}` with type `{ele['type']}` is required")
ele["value"] = req[ele["key"]]
else:
if ele["type"] == "file":
if files is not None and files.get(ele["key"]):
upload_file = files.get(ele["key"])
file_content = FileService.parse_docs([upload_file], user_id)
file_name = upload_file.filename
ele["value"] = file_name + "\n" + file_content
else:
if "value" in ele:
ele.pop("value")
else:
if req is not None and req.get(ele["key"]):
ele["value"] = req[ele['key']]
else:
if "value" in ele:
ele.pop("value")
else:
for ans in canvas.run(stream=False):
pass
@ -100,7 +123,7 @@ def create_agent_session(tenant_id, agent_id):
conv = {
"id": get_uuid(),
"dialog_id": cvs.id,
"user_id": req.get("user_id", "") if isinstance(req, dict) else "",
"user_id": user_id,
"message": [{"role": "assistant", "content": canvas.get_prologue()}],
"source": "agent",
"dsl": cvs.dsl

View File

@ -2171,15 +2171,14 @@ Creates a session with an agent.
#### Request
- Method: POST
- URL: `/api/v1/agents/{agent_id}/sessions`
- URL: `/api/v1/agents/{agent_id}/sessions?user_id={user_id}`
- Headers:
- `'content-Type: application/json'`
- `'content-Type: application/json' or 'multipart/form-data'`
- `'Authorization: Bearer <YOUR_API_KEY>'`
- Body:
- the required parameters:`str`
- the optional parameters:`str`
- `"user_id"`: `string`
The optional user-defined ID.
- other parameters:
The parameters in the begin component.
##### Request example
If `begin` component in the agent doesn't have required parameters:
@ -2202,11 +2201,21 @@ curl --request POST \
"file":"Who are you"
}'
```
If `begin` component in the agent has required file parameters:
```bash
curl --request POST \
--url http://{address}/api/v1/agents/{agent_id}/sessions?user_id={user_id} \
--header 'Content-Type: multipart/form-data' \
--header 'Authorization: Bearer <YOUR_API_KEY>' \
--form '<FILE_KEY>=@./test1.png'
```
##### Request parameters
- `agent_id`: (*Path parameter*)
The ID of the associated agent.
- `user_id`: (*Filter parameter*), string
The optional user-defined ID for parsing docs(especially images) when creating session while uploading files.
#### Response