Fold-X Pro-1.2 · HTTPS API
语言 / Language
FOLD-X PRO-1.2

文字与图像决策服务Text and Image Decision Service

HTTPS 接入文档:请求格式、响应字段、用量与进度示例。HTTPS API guide: requests, responses, allowance and progress examples.

JSONSSEBearer Key共享额度Shared allowance

1. 接入信息1. Connection details

同一个 HTTPS 服务提供文字决策、图像条件判断和图像定位。三类请求使用同一 Key,额度共享。One HTTPS service provides text decisions, image-condition classification and image grounding. All three use the same key and shared allowance.

项目Item内容Value
服务地址Base URLhttps://foldx.krino.bio
服务名称Service nameFold-X Pro-1.2
请求正文Request bodyapplication/json
鉴权AuthenticationAuthorization: Bearer KEY
响应ResponsesJSON;进度接口使用 SSEJSON; progress endpoints use SSE

正文中的 Key 均为占位符。请使用服务提供方分配的有效 Key。KEY in the examples is a placeholder. Use a valid key supplied by your service provider.

2. 认证与用量2. Authentication and allowance

HTTP headers
Authorization: Bearer YOUR_API_KEY
Content-Type: application/json

Bearer 是认证方式的固定前缀,后面保留一个空格,再填写 Key。文字、图像识别和定位共用同一授权。Bearer is the authentication scheme. Add one space and then your key. The same authorization covers text, image classification and grounding.

Key 类型Key type返回的用量字段Returned allowance含义Meaning
count 点数额度count point allowanceremaining_points剩余可用点数,以非负整数返回。Available points as a nonnegative integer.
time 按时间授权time time-based accessremaining_days剩余有效天数,整数;不足一天按一天计。Whole remaining days, rounded up for a partial day.

文字扣点为问题数乘以每题点数。将 state 的 UTF-8 字节数除以 1,024,四舍五入到整数,每题最低 1 点。字符串按原文计,结构化正文按紧凑 JSON 计。问题和选项不计入正文大小。每条图像条件扣 1 点。例如 2,048 字节的正文问 3 题,扣 6 点。Text requests cost the question count times the points per question. Divide the UTF-8 byte length of state by 1,024 and round to the nearest integer, rounding ties up, with a minimum of one point per question. Text values use their original content and structured values use compact JSON. Questions and options are excluded. Each image condition costs one point. A 2,048-byte body with three questions costs six points.

图像定位按原图像素计费:每 512 × 512 像素扣 3 点,不足一份按一份计;成功返回空结果也计费。定位与文字、图像识别共用同一 Key 和额度,详见第 9 节。Image grounding costs 3 points per started block of 512 × 512 original-image pixels, including successful empty results. It shares the same key and allowance with text and image classification; see section 9.

使用计点 Key 时,文字、图像识别和定位均在处理前预扣本次费用,成功完成后结算;输入不合法、处理失败或服务中断未完成的请求不扣费,已预扣点数退回。余额不足时在开始处理前返回 HTTP 429,SSE 同样如此。客户端断开连接不会保证取消处理;若服务完成本次请求,仍会扣费。每次成功请求独立计费,重复提交也一样。计时 Key 在有效期内按授权使用,不逐次扣点。For count-based keys, text, image classification and grounding reserve the full charge before processing and settle it on success. Invalid, failed or interrupted unfinished requests are not charged; reserved points are refunded. Insufficient balance returns HTTP 429 before processing, including SSE. Disconnecting does not guarantee cancellation: a request completed by the service is still charged. Every successful request is charged independently, including repeated submissions. Time-based keys provide access during their validity period without per-request point charges.

程序可向 POST /v1/key/balance 发送 Authorization: Bearer YOUR_API_KEY 和 JSON 正文 {},例如返回 {"type":"count","remaining_points":401}。To query available points from code, send Authorization: Bearer YOUR_API_KEY and the JSON body {} to POST /v1/key/balance. Example response {"type":"count","remaining_points":401}.

key_usage · count
{
  "type": "count",
  "remaining_points": 98
}
key_usage · time
{
  "type": "time",
  "remaining_days": 60
}

3. 余额查询接口3. Balance API

打开余额查询页面Open the balance lookup page

发送 POST /v1/key/balance,请求头使用 Authorization: Bearer API_KEY,JSON 正文为 {}。查询不扣点;计点 Key 余额为零时仍可查询,计时 Key 返回剩余天数(向上取整)。无效 Key 返回 HTTP 401。Send POST /v1/key/balance with Authorization: Bearer API_KEY and a JSON body of {}. The lookup consumes no points. Point-based keys remain queryable at zero balance. Time-based keys return remaining days, rounded up. Invalid keys return HTTP 401.

JSON · count
{
  "type": "count",
  "remaining_points": 98
}
JSON · time
{
  "type": "time",
  "remaining_days": 28
}

需要查询消费额时,使用同一接口,将正文改为 {"include_usage":true}。计点 Key 会额外返回 used_points(已消费点数)和 reserved_points(处理中预扣点数)。预扣点数不计入已消费点数。省略此选项时保持原有余额响应。页面中的金额按你填写的每点单价折算,计时 Key 仍显示剩余天数。To include consumption, use the same endpoint with {"include_usage":true}. Count keys additionally return used_points (settled consumption) and reserved_points (active reservations). Reservations are excluded from consumed points. Omitting this option preserves the existing balance response. Displayed amounts are converted at the unit price you enter; time-based keys still show remaining days.

JSON · count · include_usage
{
  "type": "count",
  "remaining_points": 98,
  "used_points": 12,
  "reserved_points": 0
}

4. 接口列表4. Endpoints

方法Method路径Path用途Purpose需要 KeyKey required
GET/health服务状态Service status否No
GET/manual本接入文档This API guide否No
POST/v1/systemone文字决策,JSON 响应Text decisions, JSON response是Yes
POST/v1/systemone/stream文字决策,SSE 进度Text decisions, SSE progress是Yes
POST/v1/image/classify单图单条件或多条件,JSON 响应One image with one or more conditions, JSON response是Yes
POST/v1/image/classify/stream图像判断,SSE 进度Image classification, SSE progress是Yes
POST/v1/key/balance查询可用点数或天数,需密钥;查询不扣点。Available points or days; requires an API key and consumes no points.是Yes
POST/v1/image/grounding图像定位,返回单框或多框坐标与置信度Image grounding with single or multiple boxes and confidence是Yes

文字 JSON 入口也接受请求头 Accept: text/event-stream,用于选择 SSE 响应。The text JSON endpoint also accepts Accept: text/event-stream to select an SSE response.

GET /health
{
  "status": "ok",
  "loaded": true,
  "model": "Fold-X Pro-1.2"
}

5. 文字请求5. Text requests

通过 state 提供共享上下文,通过 questions 提交问题。一次请求可包含 1~256 道题,每题独立返回答案。Provide shared context in state and submit questions in questions. Each request supports 1–256 questions, with a separate answer for each.

字段Field类型Type说明Description
stateJSON 值JSON value必填。字符串或可序列化的结构化上下文。Required. A string or serializable structured context.
questionsobject必填。问题 ID 到问题对象的映射,1~256 项。Required. Map question IDs to question objects, 1–256 entries.
questions.ID.typestringchoice、noul 或 score;省略时为 choice。choice, noul or score; defaults to choice.
questions.ID.instructions字符串或 JSONstring or JSON问题或判断要求。The question or decision instruction.
questions.ID.criteria对象或数组object or array候选内容,格式由题型决定,最多 256 个选项。Candidate content, formatted according to the question type; at most 256 options.
review_modestring可选。仅支持 standard,省略时使用标准模式。Optional. The only supported value is standard, which is also the default.
题型Question typecriteria 格式criteria format返回值Answer
choice对象,键为选项 ID,至少两项。Object with option IDs as keys, at least two entries.choice 为选中的选项 ID。choice is the selected option ID.
noul对象,使用 true 和 false 描述成立与不成立条件。可省略,默认含义为是与否。Object with true and false descriptions. Optional; defaults to yes and no.noul 为成立概率,0~1。noul is the probability of the true condition, from 0 to 1.
score候选数组,至少两项,顺序即评分档位顺序。Array with at least two candidate levels, in score order.score 为从 0 开始的数组下标,以字符串返回。score is the zero-based array index, returned as a string.
POST /v1/systemone · JSON
{
  "state": "Order 1001 has been paid and is waiting for shipment.",
  "questions": {
    "paid": {
      "type": "noul",
      "instructions": "Has the order been paid?",
      "criteria": {
        "true": "The order has been paid.",
        "false": "The order has not been paid."
      }
    },
    "next_action": {
      "type": "choice",
      "instructions": "Choose the next action.",
      "criteria": {
        "ship": "Ship the order.",
        "refund": "Refund the order."
      }
    },
    "priority": {
      "type": "score",
      "instructions": "Choose the shipping priority.",
      "criteria": [
        "normal",
        "urgent"
      ]
    }
  },
  "review_mode": "standard"
}

6. 文字响应6. Text responses

以下为响应格式示例;答案、概率、耗时和用量以实际返回为准。响应中的问题 ID 与请求中的 ID 对应。The following examples illustrate the response format. Actual answers, probabilities, timing and allowance vary. Response question IDs correspond to request IDs.

200 OK · application/json
{
  "model": "Fold-X Pro-1.2",
  "answers": {
    "paid": {
      "type": "noul",
      "noul": 0.377541,
      "review_views": 1
    },
    "next_action": {
      "type": "choice",
      "choice": "ship",
      "probabilities": {
        "ship": 0.622459,
        "refund": 0.377541
      },
      "review_views": 1
    },
    "priority": {
      "type": "score",
      "score": "1",
      "probabilities": {
        "0": 0.377541,
        "1": 0.622459
      },
      "review_views": 1
    }
  },
  "usage": {
    "review_mode": "standard",
    "forward_passes": 3,
    "generated_tokens": 0
  },
  "key_usage": {
    "type": "count",
    "remaining_points": 97
  }
}
字段Field类型Type说明Description
modelstring服务名称。Service name.
answersobject按问题 ID 返回答案。Answers keyed by question ID.
answers.ID.typestring对应题型。Question type.
answers.ID.choicestring选择题的选项 ID。Selected option ID for a choice question.
answers.ID.noulnumber判断题中成立条件的概率,0~1。Probability of the true condition, from 0 to 1.
answers.ID.scorestring评分题所选档位的数组下标,从 0 开始。Selected zero-based level index for a score question.
answers.ID.probabilitiesobject选择题或评分题的各选项概率。Option probabilities for choice or score questions.
answers.ID.review_viewsinteger该题使用的判断轮次,标准模式为 1。Decision views used for this question, 1 in standard mode.
usage.review_modestring文字请求的模式,固定为 standard。Mode used for the text request, always standard.
usage.forward_passesinteger本次所有问题的判断轮次总数。Total decision views across questions.
usage.generated_tokensinteger生成文本 token 数,本服务为 0。Generated text tokens; this service returns 0.
key_usageobject当前 Key 的剩余用量或有效天数。Remaining allowance or validity days for the key.

7. 图像请求7. Image requests

通过 image_base64 提交一张图片。单条件使用 description;多条件使用 questions 数组,最多 64 项。两种形式选择其一。Submit one image in image_base64. Use description for one condition, or a questions array for up to 64 conditions. Provide exactly one of these forms.

字段Field类型Type说明Description
image_base64string必填。图片 Base64 字符串,也接受 data:image/...;base64, 前缀。Required. Base64 image data; a data:image/...;base64, prefix is also accepted.
descriptionstring单条件描述,1~2,000 字符;与 questions 二选一。Single condition, 1–2,000 characters; mutually exclusive with questions.
questionsarray多条件列表,1~64 项。List of 1–64 image conditions.
questions[].idstring条件 ID,1~128 字符,同一次请求中不能重复。Condition ID, 1–128 characters, unique within a request.
questions[].descriptionstring该条条件的描述,1~2,000 字符。Condition description, 1–2,000 characters.
thresholdnumber请求默认阈值,0~1,默认 0.65。Default request threshold, 0–1, default 0.65.
questions[].thresholdnumber可选。覆盖该条件的阈值;省略时使用请求默认阈值。Optional per-condition override; otherwise uses the request threshold.

单条件示例Single-condition example

POST /v1/image/classify · JSON
{
  "image_base64": "iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAIAAAAlC+aJAAAAfElEQVR4nNXOQREAMAjAsK7+PTMRPLhGQd7QJnESJ3ESJ3ESJ3ESJ3ESJ3ESJ3ESJ3ESJ3ESJ3ESJ3ESJ3ESJ3ESJ3ESJ3ESJ3ESJ3ESJ3ESJ3ESJ3ESJ3ESJ3ESJ3ESJ3ESJ3ESJ3ESJ3ESJ3ESJ3ESJ3ESJ3ES53Vg6wNShQF/fRSLfgAAAABJRU5ErkJggg==",
  "description": "A red surface is visible.",
  "threshold": 0.65
}

多条件示例Multiple-condition example

POST /v1/image/classify · JSON
{
  "image_base64": "iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAIAAAAlC+aJAAAAfElEQVR4nNXOQREAMAjAsK7+PTMRPLhGQd7QJnESJ3ESJ3ESJ3ESJ3ESJ3ESJ3ESJ3ESJ3ESJ3ESJ3ESJ3ESJ3ESJ3ESJ3ESJ3ESJ3ESJ3ESJ3ESJ3ESJ3ESJ3ESJ3ESJ3ESJ3ESJ3ESJ3ESJ3ESJ3ESJ3ESJ3ES53Vg6wNShQF/fRSLfgAAAABJRU5ErkJggg==",
  "questions": [
    {
      "id": "red",
      "description": "A red surface is visible."
    },
    {
      "id": "solid",
      "description": "A solid-colored surface is visible.",
      "threshold": 0.8
    }
  ],
  "threshold": 0.65
}

8. 图像响应8. Image responses

单条件直接返回判断字段;多条件在 answers 数组中返回各条件结果,并保留请求中的 id。A single condition returns classification fields directly. Multiple conditions return an answers array, preserving each request id.

200 OK · single condition
{
  "score": 0.9,
  "matches": true,
  "inference_seconds": 0.01,
  "threshold": 0.65,
  "threshold_match": true,
  "model": "Fold-X Pro-1.2",
  "elapsed_seconds": 0.0,
  "key_usage": {
    "type": "count",
    "remaining_points": 96
  }
}
200 OK · multiple conditions
{
  "model": "Fold-X Pro-1.2",
  "answers": [
    {
      "score": 0.9,
      "matches": true,
      "inference_seconds": 0.01,
      "threshold": 0.65,
      "threshold_match": true,
      "id": "red"
    },
    {
      "score": 0.9,
      "matches": true,
      "inference_seconds": 0.01,
      "threshold": 0.8,
      "threshold_match": true,
      "id": "solid"
    }
  ],
  "key_usage": {
    "type": "count",
    "remaining_points": 94
  },
  "elapsed_seconds": 0.0
}
字段Field类型Type说明Description
scorenumber条件成立的得分,0~1,越大表示越符合条件。Condition-match score, from 0 to 1; higher values indicate a stronger match.
matchesboolean模型给出的成立或不成立判断。The model’s yes/no classification.
thresholdnumber该条结果使用的阈值。Threshold used for this condition.
threshold_matchbooleanscore >= threshold 时为 true。True when score >= threshold.
inference_secondsnumber该条件的服务端推理耗时,单位为秒。Server inference time for this condition, in seconds.
elapsed_secondsnumber服务端条件判断阶段总耗时,单位为秒,不含图片上传和解码。Server classification-stage duration, in seconds, excluding upload and image decoding.
answers[].idstring多条件响应中的条件 ID。Condition ID in a multi-condition response.
key_usageobject共享 Key 的剩余额度或有效天数。Remaining shared-key allowance or validity days.

matches 与 threshold_match 含义不同。例如分数为 0.60、阈值为 0.80 时,模型可能判断成立,但未达到您设置的阈值。matches and threshold_match describe different decisions. With a score of 0.60 and a threshold of 0.80, the model may classify a match while the requested threshold is not met.

9. 图像定位9. Image grounding

POST /v1/image/grounding

提交一张图片和一条目标描述,接口返回坐标与置信度。使用同一个 Bearer Key,可在余额接口查询剩余点数。图片格式和输入限制与图像分类相同。Submit one image and one target description to receive coordinates and confidence scores. Use the same Bearer key and the balance endpoint. Image formats and limits match image classification.

请求字段Request field说明Description
image_base64必填,原图的 Base64 或带 Base64 的 data URL。Required. Original image as Base64 or a Base64 data URL.
description必填,描述要找的位置。多目标可在同一句中用分号列举。Required. Describe the targets. In multi mode, separate explicit targets with semicolons.
modesingle 默认,最多一个框。multi 最多八个框。single is the default and returns at most one box. multi returns at most eight.
JSON · Grounding request
{
  "image_base64": "REPLACE_WITH_IMAGE_BASE64",
  "description": "Find the red square",
  "mode": "single"
}

image_size 是 EXIF 方向校正后的 [宽, 高]。bbox 为 0 到 1 的归一化坐标,pixel_xyxy 为同一框的原图像素坐标,两者顺序都是左、上、右、下。confidence 估计该框与正确框的 IoU 达到 0.5 的概率。成功时可以返回空的 detections。image_size is [width, height] after EXIF orientation. bbox gives coordinates normalized to 0–1 and pixel_xyxy gives coordinates in original image pixels, both in left, top, right, bottom order. confidence estimates the probability of IoU at least 0.5 with the correct box. A successful result can contain an empty detections array.

JSON · Grounding result
{
  "model": "Fold-X Pro-1.2",
  "image_size": [
    513,
    512
  ],
  "detections": [
    {
      "bbox": [
        0.25,
        0.25,
        0.75,
        0.75
      ],
      "pixel_xyxy": [
        128.25,
        128,
        384.75,
        384
      ],
      "confidence": 0.84
    }
  ],
  "elapsed_seconds": 1.42,
  "key_usage": {
    "type": "count",
    "remaining_points": 94
  },
  "billing": {
    "input_pixels": 262656,
    "charged_points": 6
  }
}

计点 Key 按原图像素数除以 262,144 后向上取整,每档扣 3 点,不足一档也扣 3 点。512×512 扣 3 点,513×512 和 800×600 扣 6 点,1024×768 扣 9 点,1920×1080 扣 24 点。缩放和框数不影响扣点,成功的空结果也按原图结算。验图失败不扣点,推理失败退回预扣,余额不足返回 429。计时 Key 返回剩余天数,本次扣点为 0。Count keys pay 3 points per block of 262,144 original pixels, rounded up to the next whole block. 512×512 costs 3 points. 513×512 and 800×600 cost 6, 1024×768 costs 9, and 1920×1080 costs 24. Resizing and box count do not affect the charge. Successful empty results are billed. Invalid images are free, inference failures refund the reservation, and insufficient balance returns 429. Time keys report remaining days and have zero charged points.

每次成功调用独立计费,重复提交相同内容也会再次扣点。Each successful call is billed separately, including repeat submissions of the same request.

cURL · Grounding
curl https://foldx.krino.bio/v1/image/grounding \
  -H "Authorization: Bearer KEY" \
  -H "Content-Type: application/json" \
  --data-binary @grounding-request.json

10. SSE 进度流10. SSE progress streams

向对应的 /stream 路径发送同样的 JSON 与认证头。服务按事件返回进度和最终结果;进度表示实际已完成的问题或处理阶段。Send the same JSON and authorization header to the corresponding /stream endpoint. Events carry actual question or processing-stage completion and the final result.

事件Event内容Content
progress进度百分比和完成数量。Completion percentage and counts.
result完整 JSON 结果,结构与普通 JSON 响应一致,包含 key_usage。Complete JSON result, matching the regular response and including key_usage.
error错误信息 detail;该次请求未完成。A detail error message; the request did not complete.
接口Endpoint完成数量字段Completed count总数量字段Total count百分比Percentage
文字Textcompleted_questionstotal_questionspercent
图像Imagecompletedtotalpercent

SSE 每帧由空行分隔。客户端应持续读取:progress 更新显示,result 接收结果,error 处理失败。以冒号开头的保活注释可忽略。SSE frames are separated by a blank line. Read continuously: display progress, accept result, and handle error. Keep-alive comments beginning with a colon can be ignored.

POST /v1/systemone/stream · text/event-stream
event: progress
data: {"percent": 0, "completed_questions": 0, "total_questions": 1}

event: progress
data: {"percent": 100.0, "completed_questions": 1, "total_questions": 1}

event: result
data: {"model": "Fold-X Pro-1.2", "answers": {"paid": {"type": "noul", "noul": 0.5, "review_views": 1}}, "usage": {"review_mode": "standard", "forward_passes": 1, "generated_tokens": 0}, "key_usage": {"type": "count", "remaining_points": 93}}

POST /v1/image/classify/stream · text/event-stream
event: progress
data: {"completed":0,"total":2,"percent":0.0}

event: progress
data: {"completed":1,"total":2,"percent":50.0}

event: progress
data: {"completed":2,"total":2,"percent":100.0}

event: result
data: {"model":"Fold-X Pro-1.2","answers":[{"score":0.9,"matches":true,"inference_seconds":0.01,"threshold":0.65,"threshold_match":true,"id":"red"},{"score":0.9,"matches":true,"inference_seconds":0.01,"threshold":0.8,"threshold_match":true,"id":"solid"}],"key_usage":{"type":"count","remaining_points":91},"elapsed_seconds":0.0}

HTTP 连接建立前的鉴权与参数错误通过 HTTP 状态码返回;流开始后的处理错误使用 error 事件返回。Authentication and input failures before streaming use HTTP error statuses. Processing failures after streaming begins use an error event.

11. cURL 示例11. cURL examples

将文字请求示例保存为 text-request.json,并将环境变量 FOLDX_API_KEY 设为您的 Key。Save the text request example as text-request.json and set FOLDX_API_KEY to your key.

cURL · Bash · JSON
curl --request POST 'https://foldx.krino.bio/v1/systemone' \
  --header "Authorization: Bearer $FOLDX_API_KEY" \
  --header 'Content-Type: application/json' \
  --data-binary @text-request.json
cURL · Bash · SSE
curl --no-buffer --request POST 'https://foldx.krino.bio/v1/systemone/stream' \
  --header "Authorization: Bearer $FOLDX_API_KEY" \
  --header 'Content-Type: application/json' \
  --data-binary @text-request.json

12. Python 接入示例12. Python integration

以下示例只使用 Python 标准库。请先设置 FOLDX_API_KEY。These examples use only the Python standard library. Set FOLDX_API_KEY first.

Python · text JSON
import json
import os
from urllib.request import Request, urlopen

base = "https://foldx.krino.bio"
key = os.environ["FOLDX_API_KEY"]
payload = {
    "state": "Order 1001 has been paid and is waiting for shipment.",
    "questions": {
        "next_action": {
            "type": "choice",
            "instructions": "Choose the next action.",
            "criteria": {"ship": "Ship the order.", "refund": "Refund the order."}
        }
    },
    "review_mode": "standard"
}
request = Request(
    base + "/v1/systemone",
    data=json.dumps(payload).encode("utf-8"),
    headers={"Authorization": "Bearer " + key, "Content-Type": "application/json"},
    method="POST",
)
with urlopen(request, timeout=300) as response:
    result = json.load(response)
print(json.dumps(result, ensure_ascii=False, indent=2))
Python · multiple image conditions
import base64
import json
import os
from pathlib import Path
from urllib.request import Request, urlopen

raw = Path("frame.jpg").read_bytes()
if len(raw) > 1_048_576:
    raise ValueError("Image file exceeds 1 MiB")
payload = {
    "image_base64": base64.b64encode(raw).decode("ascii"),
    "questions": [
        {"id": "red", "description": "A red surface is visible."},
        {"id": "solid", "description": "A solid-colored surface is visible."}
    ],
    "threshold": 0.65
}
request = Request(
    "https://foldx.krino.bio/v1/image/classify",
    data=json.dumps(payload).encode("utf-8"),
    headers={"Authorization": "Bearer " + os.environ["FOLDX_API_KEY"],
             "Content-Type": "application/json"},
    method="POST",
)
with urlopen(request, timeout=300) as response:
    print(json.dumps(json.load(response), ensure_ascii=False, indent=2))
Python · SSE
import json
import os
from urllib.request import Request, urlopen

payload = {
    "state": "Order 1001 has been paid.",
    "questions": {"paid": {"type": "noul", "instructions": "Has the order been paid?"}},
    "review_mode": "standard"
}
request = Request(
    "https://foldx.krino.bio/v1/systemone/stream",
    data=json.dumps(payload).encode("utf-8"),
    headers={"Authorization": "Bearer " + os.environ["FOLDX_API_KEY"],
             "Content-Type": "application/json", "Accept": "text/event-stream"},
    method="POST",
)
with urlopen(request, timeout=300) as response:
    event, data = "message", []
    for raw in response:
        line = raw.decode("utf-8").rstrip("\r\n")
        if not line:
            if data:
                value = json.loads("\n".join(data))
                if event == "error":
                    raise RuntimeError(value.get("detail", "Request failed"))
                print(event, value)
            event, data = "message", []
        elif line.startswith("event:"):
            event = line[6:].strip()
        elif line.startswith("data:"):
            data.append(line[5:].lstrip())

13. JavaScript 接入示例13. JavaScript integration

以下示例用于 Node.js 18 及以上的服务端环境,请保存为 .mjs 文件运行。These examples target a server-side Node.js 18 or later environment. Save them as .mjs files.

JavaScript · JSON
// Node.js 18+
const key = process.env.FOLDX_API_KEY;
if (!key) throw new Error("Set FOLDX_API_KEY first");
const payload = {
  state: "Order 1001 has been paid.",
  questions: { paid: { type: "noul", instructions: "Has the order been paid?" } },
  review_mode: "standard"
};
const response = await fetch("https://foldx.krino.bio/v1/systemone", {
  method: "POST",
  headers: { "Authorization": `Bearer ${key}`, "Content-Type": "application/json" },
  body: JSON.stringify(payload)
});
if (!response.ok) throw new Error(`HTTP ${response.status}: ${await response.text()}`);
console.log(await response.json());
JavaScript · SSE
// Node.js 18+
const response = await fetch("https://foldx.krino.bio/v1/systemone/stream", {
  method: "POST",
  headers: {
    "Authorization": `Bearer ${process.env.FOLDX_API_KEY}`,
    "Content-Type": "application/json",
    "Accept": "text/event-stream"
  },
  body: JSON.stringify({
    state: "Order 1001 has been paid.",
    questions: { paid: { type: "noul", instructions: "Has the order been paid?" } },
    review_mode: "standard"
  })
});
if (!response.ok) throw new Error(`HTTP ${response.status}: ${await response.text()}`);
const decoder = new TextDecoder();
let buffer = "";
for await (const chunk of response.body) {
  buffer += decoder.decode(chunk, { stream: true });
  let end;
  while ((end = buffer.indexOf("\n\n")) !== -1) {
    const frame = buffer.slice(0, end);
    buffer = buffer.slice(end + 2);
    const lines = frame.split(/\r?\n/);
    const event = lines.find(line => line.startsWith("event:"))?.slice(6).trim();
    const data = lines.filter(line => line.startsWith("data:")).map(line => line.slice(5).trimStart()).join("\n");
    if (!data) continue;
    const value = JSON.parse(data);
    if (event === "error") throw new Error(value.detail || "Request failed");
    console.log(event, value);
  }
}

14. 输入限制与超时14. Input limits and timeouts

项目Item限制Limit
文字问题数Text questions per request256
每题候选数Options per question256
每题文字输入总长度Total text input per question最多 36,864 tokens,包含上下文、问题、候选和格式提示。At most 36,864 tokens, including context, question, candidates and prompt formatting.
图像条件数Image conditions per request64
图片原始文件大小Original image file size1 MiB = 1,048,576 bytes
图片格式Image formatsJPEG / PNG / WEBP
图片宽度与高度Image width and height每边 32~8,192 像素。Each side must be 32–8,192 pixels.
图片长宽比Image aspect ratio长边与短边的比值不超过 200:1。The longer side must be at most 200 times the shorter side (200:1).
图片总像素Total image pixels不超过 25,000,000。At most 25,000,000.
请求 JSON 正文Request JSON body12 MiB

文字超限会返回错误,不会自动截断。图片文件大小按 Base64 解码后的原始字节计算;JSON 正文大小包含 Base64 字符串和其他字段。Text exceeding the limit is rejected without truncation. The image file limit applies to decoded bytes; the JSON body limit includes Base64 text and other fields.

耗时随输入长度、题量和负载变化。长任务可使用 SSE 接收进度,并设置适合业务的读取超时。断开连接不能保证取消当前运算;网络超时后请核对结果再决定是否重新提交。Duration varies with input length, question count and service load. Use SSE for progress on longer requests and choose an appropriate read timeout. Disconnecting does not guarantee cancellation; check the outcome after a timeout before deciding to resubmit.

15. HTTP 状态码与错误15. HTTP statuses and errors

状态码Status含义Meaning处理建议Suggested action
200请求成功,或 SSE 流已建立。Successful request, or SSE stream established.读取 JSON 或继续处理事件。Read the JSON result or continue processing events.
400请求头或请求格式错误。Invalid request headers or format.检查请求头和正文。Check headers and body.
401Key 缺失、无效或已到期。Key missing, invalid or expired.检查 Bearer 格式与授权有效期。Check the Bearer header and key validity.
411图像请求缺少 Content-Length。Image request lacks Content-Length.使用正常发送 JSON 正文的 HTTP 客户端。Use an HTTP client that sends a JSON body with its content length.
413图像请求正文超过限制。Image JSON request body exceeds its limit.检查请求体大小。Reduce the request body size.
422参数、选项、图片格式、大小、尺寸或文字长度不符合要求。Invalid parameters, candidates, image format/size/dimensions, or text length.根据 detail 修正输入。Correct the input according to detail.
429剩余点数不足以覆盖整次请求。Insufficient points to cover the entire request.减少题量或联系服务提供方充值。Reduce the number of questions or contact your provider to recharge.
503服务繁忙,暂时无法接受本次请求。The service is busy and cannot accept this request temporarily.按 Retry-After 响应头等待后重试,并降低并发。未接受的请求不扣点。Wait as indicated by Retry-After, then retry with lower concurrency. Rejected requests are not charged.
500本次处理未完成。The request did not complete.保留错误信息并联系服务提供方。Retain the error information and contact your provider.
401 · application/json
{
  "detail": "Unauthorized"
}
429 · application/json
{
  "detail": "Quota exhausted"
}

参数错误的 detail 可能是字符串,也可能是包含字段位置与原因的数组。请先检查 HTTP 状态码,再读取正文。SSE 流建立后的失败按 error 事件处理。For invalid inputs, detail can be a string or an array identifying fields and reasons. Check the HTTP status before reading the body. Failures after an SSE stream starts are handled through error events.