InfiniSynapse Server API Reference

This document is the HTTP API reference for the InfiniSynapse Server, intended for external users/SDKs. With a single API Key (Bearer Token) you can directly invoke it to run multi-turn AI task conversations, manage data sources, manage RAG knowledge bases, upload and download files, and more—without relying on any frontend UI.

If you only need command-line integration, refer to the "InfiniSynapse CLI API Reference" first; this document targets developers who need to issue HTTP requests directly.

1. Getting Started

Basic Information

ItemValue
Base URL (Mainland China)https://app.infinisynapse.cn
Base URL (Overseas)https://app.infinisynapse.com
Global path prefixAll endpoints start with /api
AuthenticationHTTP header Authorization: Bearer <API Key>
Default content typeapplication/json (file uploads use multipart/form-data)

Users in Mainland China should use the .cn domain, and overseas users should use the .com domain; for on-premises deployments, replace it with your own service address. The examples below consistently use the .cn domain; for overseas environments, simply replace it with .com.

Authentication

All business endpoints require a Bearer Token in the request header:

Authorization: Bearer <your API Key>

The server parses the user identity (userId) from the Token's sub claim, and all resources (tasks, data sources, knowledge bases, files) are isolated per user. A few endpoints marked "public read-only" require no authentication.

Language

The optional request header x-lang controls the language of the prompt text returned by the server. Possible values: zh_CN (default), en, ar, ja, ko, ru.

x-lang: zh_CN

Unified Response Structure

Most endpoints return a unified envelope:

{
  "code": 200,
  "message": "success",
  "data": { }
}
  • code === 200 indicates success, and the business data is in data.
  • code of 1101 / 1105: the Token has expired or is invalid, and the API Key needs to be replaced.
  • Parameter validation failures return HTTP 422, with message being the first validation error message.
  • File download endpoints return a binary stream directly (application/octet-stream or application/zip) and do not use this envelope.

Pagination Conventions

List endpoints (inheriting from the common pagination parameters) support the following Query parameters:

ParameterTypeDefaultDescription
pagenumber1Page number (starting from 1)
pageSizenumber10Items per page (generally capped at 100; the data source list is capped at 10000)
fieldstring-Sort field, e.g. updated_at
orderstringdescSort direction asc / desc

The data structure of a paginated response:

{
  "items": [ ],
  "meta": {
    "itemCount": 10,
    "totalItems": 42,
    "itemsPerPage": 10,
    "totalPages": 5,
    "currentPage": 1
  }
}

Quick Start Example

curl -X GET "https://app.infinisynapse.cn/api/ai_database/list?page=1&pageSize=10&source=all" \
  -H "Authorization: Bearer <your API Key>" \
  -H "x-lang: zh_CN"

2. AI Conversation and Task Execution

AI conversation uses an asynchronous "SSE long connection + message delivery" model: first subscribe to the event stream to receive real-time pushes, then send instructions via the message endpoint.

2.1 Subscribe to the Event Stream (SSE)

  • GET /api/ai/events
  • Establishes a Server-Sent Events long connection; the server actively pushes message changes, state-ready signals, notifications, and more.

Query parameters

ParameterRequiredDescription
connIdNoA client-generated connection ID (e.g. a UUID); use one per tab/connection for multiple tabs/connections so the server can target pushes. If omitted, the server generates one automatically

Request headers: Authorization: Bearer <token> is required; Accept: text/event-stream is recommended.

Event types (each formatted as event: <event>\ndata: <JSON>\n\n)

eventdataDescription
message.add{ taskId, message }Append a message to the task
message.update{ taskId, message }Update an existing message
message.partial{ taskId, message }Streaming incremental update (overwrite or append at the same ts)
message.remove{ taskId, messageTs: number[] }Remove the specified messages
state.ready{ taskId }State is ready; it is recommended to subsequently call /api/ai_task/tasks for a full fetch
notification{ type, title, message, duration? }Global notification
heartbeat"ping"Keep-alive; can be ignored

Agent message fields

mini-apps or SDKs usually only need to consume data.message inside message.add / message.partial:

FieldExampleDescription
message.typesay / asksay means Agent output; ask means the Agent is waiting for a client response
message.text"..."Streaming or final text; when partial=true, it is incremental/overwriting content
message.saycompletion_resultOne task completion signal
message.askcompletion_resultOne task completion signal
message.askupload_file_to_sandboxThe Agent asks the client to upload a local file to the current task sandbox; after uploading, send the upload result back with askResponse
curl -N "https://app.infinisynapse.cn/api/ai/events?connId=550e8400-e29b-41d4-a716-446655440000" \
  -H "Authorization: Bearer <your API Key>" \
  -H "Accept: text/event-stream"

2.2 Send a Message

  • POST /api/ai/message
  • Dispatches to different logic based on the body's type. Replies are pushed in real time to the SSE channel; this endpoint itself only returns the execution result.

Common type values and fields

typeRequired fieldsOptional fieldsDescription
newTasktexttaskId, connId, images, files, autoApprovalSettings, chatSettingsCreate a new task (performs data source billing validation and idempotency). The server can generate taskId, but clients may pre-generate a UUID for reliable polling in concurrent scenarios
askResponsetaskId, askResponsetext, images, files, connIdReply to the Agent's question and continue the multi-turn conversation; askResponse is generally messageResponse
cancelTasktaskId-Cancel a running task
clearTask-taskIdClear a task; if taskId is omitted, clear all
optionsResponsetaskId, connId, text-Multiple-choice reply
togglePlanActModechatSettingstaskIdToggle planning/execution mode
autoApprovalSettingsautoApprovalSettings-Update the auto-approval configuration
rollbackToSnapshottaskId, snapshotTs-Roll back to the specified snapshot
rollbackAndSendMessagetaskId, snapshotTs, textimages, filesRoll back and send a new message
editFirstMessageAndResendtaskId, textimages, filesEdit the first message and re-execute

files[] fields

Each files item on newTask / askResponse matches the server's WebviewMessageFileItemDto:

FieldTypeRequired by DTODescription
namestringYesOriginal file name
sizenumberYesFile size in bytes
typestringYesMIME type, for example application/pdf; taskUpload does not return this field, so the caller must preserve the MIME used for the upload
logicalPathstringNoPOSIX path relative to the task workspace. For a proactive upload attached to newTask, set this to data.logicalPath returned by taskUpload
fileTypedata | referenceNodata tells the Agent to treat the file as structured data; reference treats it as a reference document; the default is data
assetIdstringNoAttachment-store object ID returned by taskUpload; pass it through when available so rollback / first-message edits can rebuild the attachment

Response

  • Success is usually { "success": true };
  • newTask, rollback, editing the first message, etc. include { success: true, state, forceReplace? };
  • Failure may be { success: false, error } or { success: false, notification: { type, title, message } } (e.g. when billing validation fails).
# Create a new task
curl -X POST "https://app.infinisynapse.cn/api/ai/message" \
  -H "Authorization: Bearer <your API Key>" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "newTask",
    "taskId": "c3a2f9d0-your-generated-uuid",
    "connId": "550e8400-e29b-41d4-a716-446655440000",
    "text": "Read the attachment and analyze last month's sales trend",
    "images": [],
    "files": [
      {
        "name": "report-source.pdf",
        "size": 245760,
        "type": "application/pdf",
        "logicalPath": "upload_documents/report-source.pdf",
        "fileType": "reference"
      }
    ]
  }'

# Multi-turn follow-up
curl -X POST "https://app.infinisynapse.cn/api/ai/message" \
  -H "Authorization: Bearer <your API Key>" \
  -H "Content-Type: application/json" \
  -d '{"type":"askResponse","taskId":"task-001","askResponse":"messageResponse","text":"再按地区拆分"}'

Recommended mini-app / Agent integration flow

  1. Generate both a connId and a taskId; proactive attachments require the taskId before upload because it is part of the upload path.
  2. If the task starts with attachments, call POST /api/tools/taskUpload/:taskId once per file and map each response data object into files[]; preserve the caller's MIME as type and choose fileType.
  3. Open GET /api/ai/events?connId=<uuid> and wait for state.ready or a short timeout.
  4. Call POST /api/ai/message with type=newTask, the same connId, the same taskId, task text, the pre-uploaded files, and optional images, autoApprovalSettings, and chatSettings: { "mode": "act" }.
  5. Read progress from SSE message.partial / message.add; treat notification.type=error as task failure.
  6. If the running task emits message.type=ask with message.ask=upload_file_to_sandbox, use the reactive upload path and then send the upload result JSON back with type=askResponse, askResponse=messageResponse, the same taskId, and the same connId.
  7. After message.ask=completion_result or message.say=completion_result, read generated reports, charts, PDFs, Word files, and other artifacts through the task file endpoints.

2.2.1 End to end: proactively attach a file to an SSE-created task

The Bash example below requires curl, jq, and uuidgen. It uploads a file into a pre-generated taskId workspace, reads data.logicalPath from the unified response envelope, opens SSE, and then sends newTask with files[] using the same connId / taskId:

API_KEY='<your API Key>'
TASK_ID="$(uuidgen | tr '[:upper:]' '[:lower:]')"
CONN_ID="$(uuidgen | tr '[:upper:]' '[:lower:]')"
INPUT_FILE='./report-source.pdf'
MIME_TYPE='application/pdf'

# 1) Proactive pre-upload; business data is inside the unified response's data field
UPLOAD_RESPONSE="$(
  curl -fsS -X POST \
    "https://app.infinisynapse.cn/api/tools/taskUpload/${TASK_ID}?subdir=upload_documents&naming=original" \
    -H "Authorization: Bearer ${API_KEY}" \
    -F "file=@${INPUT_FILE}"
)"
UPLOAD_DATA="$(printf '%s' "${UPLOAD_RESPONSE}" | jq -ce '.data // .')"
FILE_NAME="$(printf '%s' "${UPLOAD_DATA}" | jq -er '.name')"
FILE_SIZE="$(printf '%s' "${UPLOAD_DATA}" | jq -er '.size')"
LOGICAL_PATH="$(printf '%s' "${UPLOAD_DATA}" | jq -er '.logicalPath')"
ASSET_ID="$(printf '%s' "${UPLOAD_DATA}" | jq -er '.assetId')"

# 2) Open SSE before newTask. Production code should wait for state.ready;
#    this compact example uses a short timeout
SSE_LOG="${TMPDIR:-/tmp}/infinisynapse-${TASK_ID}.sse"
curl -NsS \
  "https://app.infinisynapse.cn/api/ai/events?connId=${CONN_ID}" \
  -H "Authorization: Bearer ${API_KEY}" \
  -H "Accept: text/event-stream" >"${SSE_LOG}" &
SSE_PID=$!
sleep 1

# 3) type is the original MIME; reference is for documents, data for structured data
NEW_TASK_BODY="$(
  jq -n \
    --arg taskId "${TASK_ID}" \
    --arg connId "${CONN_ID}" \
    --arg name "${FILE_NAME}" \
    --argjson size "${FILE_SIZE}" \
    --arg mimeType "${MIME_TYPE}" \
    --arg logicalPath "${LOGICAL_PATH}" \
    --arg assetId "${ASSET_ID}" \
    '{
      type: "newTask",
      taskId: $taskId,
      connId: $connId,
      text: "Read the attached PDF and summarize its key findings",
      images: [],
      files: [{
        name: $name,
        size: $size,
        type: $mimeType,
        logicalPath: $logicalPath,
        fileType: "reference",
        assetId: $assetId
      }],
      chatSettings: { mode: "act" }
    }'
)"
curl -fsS -X POST "https://app.infinisynapse.cn/api/ai/message" \
  -H "Authorization: Bearer ${API_KEY}" \
  -H "Content-Type: application/json" \
  -d "${NEW_TASK_BODY}"

# Follow SSE live. After completion press Ctrl-C, then run kill "${SSE_PID}" if still connected
tail -f "${SSE_LOG}"

This proactive path happens before newTask: the application already knows which file the Agent needs, so it writes the file to the task workspace with taskUpload and declares the path in the first message's files[]; no separate askResponse is needed. upload_file_to_sandbox is the reactive, mid-run path: only after the Agent emits that Ask does the client call /api/ai/upload?taskId=..., then send askResponse with the same task and connection to release the wait. Even if a reactive implementation uses taskUpload to place the bytes, it must still send askResponse; uploading alone does not resume the waiting Agent.

2.3 Other Conversation Helper Endpoints

These endpoints sync state, update settings, probe connectivity, and confirm whether the browser extension is online. Overview:

EndpointMethodDescription
/api/ai/state?taskId=GETGet the complete frontend state for the specified task (or globally)
/api/ai/settingsPOSTUpdate API configuration, custom instructions, and auto-approval settings; when taskId is provided, also update that task's model
/api/ai/configurationGETGet the apiConfiguration saved by the current user
/api/ai/modelsGETRequest the OpenAI-compatible /models using the current API configuration; returns an array of available model IDs
/api/ai/pingGETLightweight heartbeat that returns { ok: true }
/api/ai_browser/sessionGETGet the current user's connected browser extension session

Get frontend state

  • GET /api/ai/state
  • Returns the full state for a task under the current user (or the global state when taskId is omitted), for full sync by the frontend/SDK.

Query parameters

ParameterRequiredDescription
taskIdNoTask ID; omit to return global state unrelated to the current task

Response fields (common)

FieldDescription
apiConfigurationCurrent API configuration (provider, Base URL, model, etc.)
customInstructionsCustom instructions / system prompt
currentTaskItemCurrent task item (id, status, mode, task, etc.)
infiniMessagesMessage list (ask / say)
autoApprovalSettingsAuto-approval and capability switches
chatSettingsConversation mode (plan / act)
todoItemsTodo items
curl -X GET "https://app.infinisynapse.cn/api/ai/state?taskId=task-001" \
  -H "Authorization: Bearer <your API Key>"

Update settings (focus)

  • POST /api/ai/settings
  • Updates the user-level API configuration, custom instructions, and auto-approval settings. All body fields are optional—send only what you need. When taskId is provided and apiConfiguration contains a valid apiProvider + model ID, the task's model selection is updated as well.

Request body fields

FieldTypeRequiredDescription
apiConfigurationobjectNoAPI configuration (provider, keys, Base URL, model, etc.); see table below
customInstructionsSettingstringNoCustom instructions / system prompt; written to the user settings
autoApprovalSettingsobjectNoAuto-approval and capability switches; see table below
taskIdstringNoWhen set, updates that task's provider/model from apiConfiguration while also updating the user's default configuration

Common apiConfiguration fields

FieldTypeDescription
apiProviderstringProvider: infinisynapse / openai / anthropic
infinisynapseApiKeystringInfiniSynapse provider API Key
infinisynapseModelIdstringInfiniSynapse model ID
openAiBaseUrlstringOpenAI-compatible Base URL (used by /api/ai/models to list models)
openAiApiKeystringOpenAI-compatible API Key
openAiModelIdstringOpenAI-compatible model ID
openAiModelInfoobjectOptional model metadata (context window, temperature, etc.)
openAiCustomParamsobjectOptional extra custom parameters
anthropicApiKeystringAnthropic API Key
anthropicBaseUrlstringAnthropic Base URL
anthropicModelIdstringAnthropic model ID
anthropicModelInfoobjectOptional Anthropic model metadata
anthropicCustomParamsobjectOptional extra custom parameters

Task-level model updates depend on extractModelId: for apiProvider=openai use openAiModelId, for anthropic use anthropicModelId, for infinisynapse use infinisynapseModelId. Both provider and modelId must be present before the task is updated.

autoApprovalSettings fields

FieldTypeDescriptionDefault (reference)
maxRequestsnumberMax requests1000
maxSubAgentRequestsnumberMax sub-agent requests500
databaseReturnLimitnumberMax database return rows (hard-capped by the server)200
delegateMaxConcurrencynumberMax delegate concurrency5
enableNotificationsbooleanEnable notificationstrue
debugModebooleanDebug modefalse
enableWebSearchbooleanEnable web searchtrue
enableReadImagebooleanEnable image readingtrue
enableBrowserbooleanEnable browser capabilityfalse
enableNativeToolCallingbooleanEnable native tool callingtrue

Response

On success, returns { success: true, notification }. The notification.title / message text follows the user's language preference (i18n); the structure is fixed:

{
  "success": true,
  "notification": {
    "type": "success",
    "title": "...",
    "message": "...",
    "duration": 3000
  }
}

Usage examples

# 1) Update the user's default model and custom instructions (no taskId)
curl -X POST "https://app.infinisynapse.cn/api/ai/settings" \
  -H "Authorization: Bearer <your API Key>" \
  -H "Content-Type: application/json" \
  -d '{
    "apiConfiguration": {
      "apiProvider": "openai",
      "openAiBaseUrl": "https://api.openai.com/v1",
      "openAiApiKey": "<your-openai-key>",
      "openAiModelId": "gpt-4o"
    },
    "customInstructionsSetting": "You are a data analysis assistant. Keep answers concise and actionable."
  }'

# 2) Switch the model for a specific task (also updates the user's default apiConfiguration)
curl -X POST "https://app.infinisynapse.cn/api/ai/settings" \
  -H "Authorization: Bearer <your API Key>" \
  -H "Content-Type: application/json" \
  -d '{
    "taskId": "task-001",
    "apiConfiguration": {
      "apiProvider": "infinisynapse",
      "infinisynapseModelId": "infini-analyst"
    }
  }'

# 3) Update auto-approval / capability switches only
curl -X POST "https://app.infinisynapse.cn/api/ai/settings" \
  -H "Authorization: Bearer <your API Key>" \
  -H "Content-Type: application/json" \
  -d '{
    "autoApprovalSettings": {
      "maxRequests": 1000,
      "enableWebSearch": true,
      "enableBrowser": false,
      "databaseReturnLimit": 200
    }
  }'

Recommended call order

  1. Call GET /api/ai/configuration or GET /api/ai/state to inspect the current settings.
  2. To switch an OpenAI-compatible model, optionally call GET /api/ai/models first to list available model IDs.
  3. Call POST /api/ai/settings to write the new settings; include taskId if you only want to affect a running task.
  4. Call GET /api/ai/state?taskId= again to confirm the state has synced.

Get API configuration

  • GET /api/ai/configuration
  • Returns the apiConfiguration saved for the current user (provider, Base URL, API key, model, etc.). No query or body.
curl -X GET "https://app.infinisynapse.cn/api/ai/configuration" \
  -H "Authorization: Bearer <your API Key>"

Example response:

{
  "apiConfiguration": {
    "apiProvider": "openai",
    "openAiBaseUrl": "https://api.openai.com/v1",
    "openAiModelId": "gpt-4o"
  }
}

List available models

  • GET /api/ai/models
  • Uses openAiBaseUrl / openAiApiKey from the current user's apiConfiguration to call the OpenAI-compatible /models endpoint, and returns an array of model ID strings. Returns [] when the Base URL is invalid or the request fails.
curl -X GET "https://app.infinisynapse.cn/api/ai/models" \
  -H "Authorization: Bearer <your API Key>"

Example response: ["gpt-4o", "gpt-4o-mini"]

Heartbeat probe

  • GET /api/ai/ping
  • Lightweight probe for connection/auth liveness. Does not fetch any business state.
curl -X GET "https://app.infinisynapse.cn/api/ai/ping" \
  -H "Authorization: Bearer <your API Key>"

Response: { "ok": true }

Browser extension session

  • GET /api/ai_browser/session
  • Returns the current user's connected Chrome / browser extension session, or null if not connected. Shopping comparison and web-research apps can use this to verify the extension is online.

Response fields

FieldTypeDescription
uidstringUser ID
clientIdstring | nullExtension client ID
statusstringSession status (e.g. connected)
connectedAtnumber | nullConnected timestamp (ms)
lastActivityAtnumber | nullLast activity timestamp (ms)
browserNamestringBrowser name
versionstringExtension version
activeSessionCountnumberNumber of active automation sessions
activeSessionIdsstring[]Active automation session ID list
curl -X GET "https://app.infinisynapse.cn/api/ai_browser/session" \
  -H "Authorization: Bearer <your API Key>"

3. Task Management

Controller prefix: /api/ai_task.

3.1 Task Queries

EndpointMethodParametersDescription
/api/ai_task/listGETPagination parameters + task_name, category_name, category_id, is_in_rag, virtual_echart_category (all optional, fuzzy match)Get the task list with pagination
/api/ai_task/tasks?taskId=GETtaskId (required)Get the full task data (taskInfo + messages + isRunning)
/api/ai_task/getTaskInfo/:idGETPath idGet task metadata (without creating a running instance)
/api/ai_task/showTaskWithId/:idGETPath idGet task details
/api/ai_task/getUiMessageById?id=GETid (task ID)Get the task's UI message list (slimmed down)
/api/ai_task/messagePayload?taskId=&messageTs=GETtaskId, messageTsGet the full text of a single message (not slimmed down)
/api/ai_task/getTaskWorkspace/:idGETPath idGet the task working directory and file list { cwd, files }

3.2 Task Operations

Delete Tasks

  • POST /api/ai_task/deleteTaskWithId
{ "ids": ["task-001", "task-002"] }

Cancel a Task

  • GET /api/ai_task/cancelTask?taskId=task-001 (taskId as a Query parameter; some older clients may also use POST /api/ai/message with type=cancelTask)

Rerun a SQL Task

  • POST /api/ai_task/rerunSqlTask
{ "id": "task-001", "chat_index": 0 }

Run Extracted SQL

  • POST /api/ai_task/runExtractSql
{
  "variables": { "startDate": "2024-01-01", "endDate": "2024-12-31" },
  "register_tables": "orders,users",
  "databases": "main_db",
  "sqls": "SELECT * FROM orders WHERE created_at BETWEEN :startDate AND :endDate"
}

3.3 Tasks and RAG

EndpointMethodBody/ParametersDescription
/api/ai_task/saveToRagPOST{ taskId, action }, where action is save/removeSave or remove a task to/from RAG
/api/ai_task/isSavedToRag?taskId=GETtaskIdReturns a boolean indicating whether the task has been saved to RAG

3.4 Task Categories

EndpointMethodBody/ParametersDescription
/api/ai_task/category/addPOST{ category_name }Add a category
/api/ai_task/category/updatePOST{ id, category_name }Update a category
/api/ai_task/category/deletePOST{ ids: [] }Delete categories
/api/ai_task/category/listGETPagination parameters + category_nameGet categories with pagination
/api/ai_task/category/getAllCategoriesGET-Get all categories
/api/ai_task/getCatetoryById/:idGETPath idCategory details
/api/ai_task/getCatetoryByTaskId/:idGETPath id (task ID)Get the categories associated with a task
/api/ai_task/updateCategoryByTaskIdPOST{ id, category_ids: [] }Update the categories associated with a task

3.5 Task Files

EndpointMethodBody/ParametersDescription
/api/ai_task/previewFilePOST{ taskId, fileName }Preview the file content, returning { content, fileType }
/api/ai_task/getTaskWorkspace/:idGETPath idGet the task working directory and flat file list { cwd, files }; usually call this first to discover generated .md, .pdf, .docx, and chart files
/api/ai_task/downloadZip?taskId=GETtaskIdDownload the entire task directory as a ZIP (returns a binary stream)

3.6 Task Sharing (public read-only, no authentication required)

EndpointMethodDescription
/api/ai_task/setSharePOST{ taskId, isPublic } sets the task as public/private (requires owner authentication)
/api/ai_task/shareStatus?taskId=GETQuery the sharing status (requires owner authentication)
/api/ai_task/publicTask?taskId=GETPublic read-only retrieval of task data
/api/ai_task/publicMessagePayload?taskId=&messageTs=GETPublic read-only retrieval of the full content of a single message
/api/ai_task/publicTaskFileTree/:taskIdGETPublic read-only retrieval of the file tree
/api/ai_task/publicPreviewFilePOSTPublic read-only file preview
/api/ai_task/publicDownloadTaskFile/:taskId?path=GETPublic read-only file download
/api/ai_task/publicDownloadZip?taskId=GETPublic read-only download of the task ZIP

4. Data Source Management

Controller prefix: /api/ai_database. Supported database types: mysql, postgres, sqlite, sqlserver, clickhouse, snowflake, doris, starrocks, gbase, kingbase, dm, supabase, deltalake, file (connection testing also supports mongodb, elasticsearch).

4.1 List Query

  • GET /api/ai_database/list

Query parameters: pagination parameters + the following optional items

ParameterDescription
nameDatabase name (fuzzy)
typeDatabase type
enabledWhether enabled: 1 / 0
sourceSource: local / remote / subscribed / all (default all)
subscribeSourceSubscription source: created / subscribed / all (default created)

4.2 Create, Update, Delete

EndpointMethodBodyDescription
/api/ai_database/addPOSTDatabaseAddDtoCreate a database connection
/api/ai_database/updatePOSTDatabaseEditDto (includes id)Update the database configuration
/api/ai_database/deletePOST{ ids: [] }Batch delete
/api/ai_database/enabledPOST{ ids: number[], enabled }Batch enable/disable

Example add request body:

{
  "name": "production_db",
  "type": "mysql",
  "config": "{\"mysql_host\":\"127.0.0.1\",\"mysql_port\":3306,\"mysql_username\":\"root\",\"mysql_password\":\"***\",\"mysql_database\":\"sales\"}",
  "enabled": 1,
  "description": "生产环境数据库",
  "nickname": "销售数据源"
}

Note: the database name must not start with remote_ or subscribe_.

4.3 Connection Testing and Queries

EndpointMethodBody/ParametersDescription
/api/ai_database/testConnectionPOST{ type, config }Test the connection, returning { success, message, latencyMs }
/api/ai_database/getDatabaseById/:idGETPath idQuery details by ID
/api/ai_database/getDatabaseByName/:nameGETPath nameQuery details by name

4.4 File and Knowledge Base Binding

EndpointMethodBody/ParametersDescription
/api/ai_database/upload/:databaseIdPOSTmultipart/form-data, field file (≤1GB)Upload a data file to the specified database
/api/ai_database/bindRagsPOST{ databaseId, ragIds: [] }Set the knowledge bases associated with the database
/api/ai_database/getBindRags/:databaseIdGETPath databaseIdGet the list of knowledge bases bound to the database

5. RAG Knowledge Base Management

Controller prefix: /api/ai_rag_sdk.

5.1 Queries

EndpointMethodParametersDescription
/api/ai_rag_sdkGETPagination parameters + keyword, enabled, source, subscribeSourceGet the knowledge base list with pagination
/api/ai_rag_sdk/allGET-Get all knowledge bases (no pagination)
/api/ai_rag_sdk/:idGETPath idKnowledge base details

5.2 Create, Update, Delete

EndpointMethodBodyDescription
/api/ai_rag_sdk/createPOSTRagSdkCreateDtoCreate a knowledge base
/api/ai_rag_sdk/update/:idPOSTRagSdkUpdateDtoUpdate a knowledge base
/api/ai_rag_sdk/deletePOST{ ids: [] }Batch delete
/api/ai_rag_sdk/enabledPOST{ ids: [], enabled }Batch enable/disable

Example create request body:

{
  "name": "sales_kb",
  "nickname": "销售知识库",
  "description": "销售相关文档",
  "ragDocFilterRelevance": "0.5",
  "requiredExts": [".pdf", ".docx", ".txt"],
  "docDir": "/path/to/docs",
  "enabled": 1,
  "database_ids": ["uuid-1", "uuid-2"]
}

5.3 Database Binding

EndpointMethodBody/ParametersDescription
/api/ai_rag_sdk/bindDatabasesPOST{ ragId, databaseIds: [] }Set the databases associated with the knowledge base
/api/ai_rag_sdk/getBindDatabases/:ragIdGETPath ragIdGet the list of databases bound to the knowledge base

5.4 File Operations (supports file / oss / s3)

EndpointMethodBodyDescription
/api/ai_rag_sdk/fileTreePOSTListDirectoryDtoList the directory file tree
/api/ai_rag_sdk/downloadPOSTDownloadFileDtoDownload a file (returns a binary stream)
/api/ai_rag_sdk/deleteRemoteFilePOSTDeleteRemoteFileDtoDelete a remote file (OSS/S3 only)

Example fileTree request body (remote OSS):

{
  "file_system": "oss",
  "directory": "/docs",
  "endpoint": "https://oss-cn-hangzhou.aliyuncs.com",
  "access_key_id": "***",
  "access_key_secret": "***",
  "filter": "both"
}

6. File Upload

The upload-related endpoints are registered under the root path (i.e. /api/...). Except for task uploads, ordinary uploads are organized by "directory".

EndpointMethodParametersDescription
/api/upload/:directoryPOSTmultipart/form-data field file (≤1GB)Upload a file to the specified directory, returning { filename }
/api/ai/upload?taskId=POSTmultipart/form-data field file + Query taskIdUpload a local file to the specified task sandbox, commonly used to respond to the Agent's upload_file_to_sandbox request
/api/tools/taskUpload/:taskIdPOSTfile + Query subdir, naming (original/hash)Upload a file to the task working directory, returning { filename, assetId, logicalPath, name, size }; report-writing apps can use subdir=upload_documents to archive user documents
/api/createDirectoryPOSTCreateDirectoryDtoCreate a directory
/api/deleteDirectoryDELETEDeleteDirectoryDtoDelete a directory
/api/directoriesGET-Get the directory list
/api/fileTree?keyword=GETkeyword (optional)Get the file tree structure
/api/taskFileTree/:taskIdGETPath taskIdGet the task working directory file tree
/api/uploadConfigGET-Get the upload limit configuration { maxFileSizeMB, maxFileSizeBytes, chat }
curl -X POST "https://app.infinisynapse.cn/api/upload/my-folder" \
  -H "Authorization: Bearer <your API Key>" \
  -F "file=@./data.csv"
# Upload to a task sandbox so the Agent can continue reading it
curl -X POST "https://app.infinisynapse.cn/api/ai/upload?taskId=task-001" \
  -H "Authorization: Bearer <your API Key>" \
  -F "file=@./attachment.pdf"

# Upload to a specific subdirectory in the task workspace
curl -X POST "https://app.infinisynapse.cn/api/tools/taskUpload/task-001?subdir=upload_documents&naming=original" \
  -H "Authorization: Bearer <your API Key>" \
  -F "file=@./report-source.docx"

7. File Storage and Download

Generic file storage uses the /api/storage prefix; task workspace downloads use /api/tools/storage in the current Server API.

EndpointMethodParametersDescription
/api/storage/deletePOST{ ids: [] }Delete files
/api/storage/download/:idGETPath id (format directory/filename, URL-encoded)Download a file (returns a binary stream)
/api/tools/storage/downloadTaskFile/:taskId?path=GETPath taskId + Query path (file relative path, URL-encoded)Download a file from the task working directory
/api/tools/storage/downloadTaskFile/:taskId?path=&inline=1GETOptional inline=1Return previewable files such as images, SVGs, and PDFs inline; useful for rendering charts or images in report preview pages
curl "https://app.infinisynapse.cn/api/tools/storage/downloadTaskFile/task-001?path=data%2Fresult.csv" \
  -H "Authorization: Bearer <your API Key>" \
  -o result.csv

8. Error Handling

SymptomRecommended handling
code of 1101 / 1105The Token has expired or is invalid; replace the API Key and retry
HTTP 422Request parameter validation failed; message is the specific reason
HTTP 400Business validation failed (e.g. file too large, illegal naming, no file uploaded, etc.)
HTTP 404The resource/file does not exist or you do not have access
No SSE dataCheck the Authorization header and the network, and make sure you established the /api/ai/events connection before sending messages

9. Typical Call Flow

  1. Pre-generate taskId and connId, and persist them with your business task record.
  2. Prepare resources: GET /api/ai_database/list, GET /api/ai_rag_sdk, and enable as needed via POST /api/ai_database/enabled, POST /api/ai_rag_sdk/enabled.
  3. If the first message has attachments, call POST /api/tools/taskUpload/:taskId with the same taskId and assemble each response data into files[].
  4. Establish an SSE connection: GET /api/ai/events?connId=<uuid>.
  5. Create a new task: POST /api/ai/message (type=newTask) with the same taskId / connId and optional files[], and receive real-time replies from SSE.
  6. If the running Agent requests upload_file_to_sandbox, call POST /api/ai/upload?taskId=, then send the upload result back with POST /api/ai/message (type=askResponse).
  7. Multi-turn follow-up: POST /api/ai/message (type=askResponse).
  8. Cancel a task: GET /api/ai_task/cancelTask?taskId=.
  9. View results: GET /api/ai_task/getTaskWorkspace/:id to list the artifacts, POST /api/ai_task/previewFile to preview, and GET /api/tools/storage/downloadTaskFile/:taskId?path= to download.

10. API Scenarios and Compositions from Production mini-apps

Real mini-apps should not expose the API Key in the browser. The recommended pattern is to implement your own server-side business route: keep the API Key on the server, assemble prompts there, proxy uploads, and read task artifacts. The frontend only talks to your own business route.

10.1 Common Agent Task Skeleton

Use this for any long-running Agent application, including Gaokao assistants, shopping comparison, and report writing.

  1. The frontend calls your server route; the server pre-generates and persists both a connId and a taskId.
  2. When the first message has attachments, the server calls POST /api/tools/taskUpload/:taskId with the same taskId and maps each response data object into files[].
  3. The server opens GET /api/ai/events?connId=<uuid> and starts consuming SSE.
  4. The server calls POST /api/ai/message with type=newTask, the same connId, the same taskId, task text, optional files[], autoApprovalSettings, and chatSettings: { "mode": "act" }.
  5. Use SSE message.partial / message.add to advance state; transform message.text into progress, conclusions, or structured frontend results.
  6. When message.ask=upload_file_to_sandbox, use the reactive upload path, then send the upload result back to the Agent with POST /api/ai/message (type=askResponse).
  7. After message.ask=completion_result or message.say=completion_result, read messages, workspace files, or downloads according to the task type.
  8. When the user stops the run, call GET /api/ai_task/cancelTask?taskId= and mark the business task state in your own database.

10.2 Gaokao Assistants: Form Input + Optional Files + PDF Result

Gaokao school/major consulting apps are centered on "one form submission generates a structured report." These apps usually do not need the browser extension.

StageAPI compositionUsage
First-message attachmentsPOST /api/tools/taskUpload/:taskId + newTask.files[]If the user already selected a score sheet or school list when submitting the form, pre-upload it and declare it in newTask.files[]; do not wait for the Agent to ask
Create taskGET /api/ai/events + POST /api/ai/messagePut score, province, subject choices, preferences, and constraints into text, then create newTask with the same taskId / connId and optional files[]
Mid-run supplementPOST /api/ai/upload?taskId= + POST /api/ai/messageOnly when the Agent asks for upload_file_to_sandbox, upload a subsequently added file to the task sandbox and send the result back with askResponse
Progress recoveryGET /api/ai_task/getUiMessageById?id=After page refresh or polling, retrieve slim UI messages and check whether completion_result has appeared
Read resultGET /api/ai_task/getTaskWorkspace/:id + POST /api/ai_task/previewFileDiscover generated Markdown, PDF, or data files; preview before displaying them
Download resultGET /api/tools/storage/downloadTaskFile/:taskId?path=Download PDFs, images, or other final files
Share resultPOST /api/ai_task/setShareWhen a public read-only result page is needed, make the task public and then read through public task endpoints

10.3 Shopping Comparison Assistant: Chrome Extension + Realtime Agent + Message Result

Shopping apps need the Agent to see the product page, search page, or multiple e-commerce pages the user is browsing. Usually check whether the Chrome extension is online before starting the task.

StageAPI compositionUsage
Extension checkGET /api/ai_browser/sessionShow whether the Chrome extension is connected; if not, guide the user to install or open it
Create comparison taskGET /api/ai/events + POST /api/ai/messageIn text, include budget, product links, preferences, price sensitivity, and comparison dimensions; use chatSettings.mode=act
Web/file supplementmessage.ask=upload_file_to_sandbox + POST /api/ai/upload?taskId=If the user adds screenshots, order pages, or product material, upload them when the Agent asks and send the result back
Realtime displaySSE message.partial / message.addShow comparison progress, candidate products, risk warnings, and purchase recommendations in real time
Resume and pollingGET /api/ai_task/getUiMessageById?id=When the user returns to the page, restore recent messages by task ID
Stop taskGET /api/ai_task/cancelTask?taskId=Cancel the running Agent when the user changes product, budget, or no longer wants to continue

10.4 Report Writer: Batch Document Upload + Knowledge/Data Resources + Workspace Artifacts

Report-writing apps do not just need a text answer. They let the Agent continuously create Markdown, charts, PDFs, Word files, and other artifacts in the task workspace.

StageAPI compositionUsage
Upload user materialPOST /api/tools/taskUpload/:taskId?subdir=upload_documents&naming=originalArchive Word, PDF, Markdown, spreadsheets, and other source files into a fixed task workspace directory, and retain each response data object for newTask.files[]
Enable resourcesGET /api/ai_database/list, POST /api/ai_database/enabled, GET /api/ai_rag_sdk, POST /api/ai_rag_sdk/enabledIf the report needs databases or knowledge bases, list and enable the relevant resources before creating the task
Create writing taskGET /api/ai/events + POST /api/ai/messageIn text, specify the report goal, audience, structure, and citation requirements, and send pre-uploaded source material in newTask.files[]; use autoApprovalSettings to reduce tool-call confirmations
Supplement materialPOST /api/ai/upload?taskId= + POST /api/ai/messageFor temporary files requested by the Agent during the conversation, upload to sandbox and continue with askResponse
Inspect workspaceGET /api/ai_task/getTaskWorkspace/:idEnumerate task artifacts and discover the latest .md, .pdf, .docx, chart, and image files
Preview contentPOST /api/ai_task/previewFilePreview Markdown, text, and readable files; the frontend can render them as a report preview
Download/inline renderGET /api/tools/storage/downloadTaskFile/:taskId?path=Download final files; add inline=1 for images, SVGs, and PDFs embedded in report preview pages
Multi-turn revisionPOST /api/ai/message (type=askResponse)When the user asks for revisions, continue the same task instead of creating a new one and losing context

10.5 Composition Principles

  • Connect SSE before sending the task: the most reliable long-task order is to establish /api/ai/events first, then call /api/ai/message, so early state is not missed.
  • Keep credentials and state server-side: API Key, taskId, file paths, share state, and business user ID should stay on your server. The frontend should only receive business results.
  • Separate the two upload modes: /api/tools/taskUpload/:taskId is for proactive pre-upload before the first message, with its response mapped into newTask.files[]; /api/ai/upload?taskId= responds to a mid-run upload_file_to_sandbox, and must be followed by askResponse.
  • Prefer the workspace for deliverables: SSE messages are enough for text-only display; use getTaskWorkspace, previewFile, and downloadTaskFile when you need download, preview, versioning, or export.
  • Enable resources before the task: databases and knowledge bases should be listed and enabled before newTask, otherwise the Agent may not see the expected resources.
  • Design recovery from the beginning: mini-apps should persist taskId, connId, user input, uploaded file mappings, and last status; after refresh, recover with getUiMessageById and getTaskWorkspace.