AI 智能体与自动化
Lingivio 翻译整个文档文件,并返回相同类型的文件,保留版式、公式和数字。AI 智能体、脚本或工作流工具可通过 REST API 执行应用中的所有操作。本页提供快速入门指引。API 参考文档包含所有端点。
接入方式及当前开放情况
无代码连接器,让工作流无需编写代码就能翻译文档。这些连接器已列入计划,但尚未推出。在此之前,可通过工作流工具的 HTTP 步骤调用 REST API。
智能体能做什么
翻译文件并获得相同类型的文件。支持的格式:
- .txt
- .md
- .csv
- .html
- .srt
- .xlsx
- .docx
- .pptx
- .odt
- .ods
- .odp
- .png
- .jpg
- .webp
- 在扣费前从上传响应中读取确切的积分费用。若超过任务应花费的额度则停止。
- 在一次批量请求中发送最多 20 个文件。
- 跟踪真实进度:已完成片段数和总片段数。
- 根据稳定的错误类别进行分支处理。错误类别会说明重试是否有用,以及预留积分的处理情况。
不支持的功能
- 它翻译文件,而非零散文本。公共 API 不提供用于字符串的端点。请将文本作为 .txt 或 .md 文件发送。
- 上传文件及其译文会在上传后 24 小时内删除。请及时下载结果。
- 扫描 PDF 最多可有 100 页。各套餐还限制文件大小和单个文件可消耗的积分。价格页面列出了这两项限制。
- 并非每种语言都支持每种格式。PDF 和图片输出支持的文字系统少于 Office 和文本文件。语言页面列出了所有语言对。
获取密钥
Business 和 Enterprise 套餐包含 API 访问权限。在“设置 → API 密钥”中创建密钥。密钥仅显示一次。每次请求都需将其作为 bearer 令牌发送。
将密钥交给智能体的运行环境,而不是模型。将其保存在工具代码读取的环境变量中。切勿放入提示词、工具参数或模型可打开的文件中。
const res = await fetch('https://api.lingivio.com/v1/me', {
headers: { Authorization: `Bearer ${process.env.LINGIVIO_KEY}` },
});
console.log(res.status, await res.json()); const res: Response = await fetch('https://api.lingivio.com/v1/me', {
headers: { Authorization: `Bearer ${process.env.LINGIVIO_KEY}` },
});
console.log(res.status, await res.json()); import os
import httpx
res = httpx.get(
"https://api.lingivio.com/v1/me",
headers={"Authorization": f"Bearer {os.environ['LINGIVIO_KEY']}"},
)
print(res.status_code, res.json()) require "json"
require "net/http"
uri = URI("https://api.lingivio.com/v1/me")
req = Net::HTTP::Get.new(uri, "Authorization" => "Bearer #{ENV.fetch("LINGIVIO_KEY")}")
res = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https") { |http| http.request(req) }
puts res.code, JSON.parse(res.body) package main
import (
"fmt"
"io"
"net/http"
"os"
)
func main() {
req, _ := http.NewRequest("GET", "https://api.lingivio.com/v1/me", nil)
req.Header.Set("Authorization", "Bearer "+os.Getenv("LINGIVIO_KEY"))
res, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(res.StatusCode, string(body))
} curl https://api.lingivio.com/v1/me -H "Authorization: Bearer $LINGIVIO_KEY" 翻译文件
请原样复制此代码。它会上传一个 PDF,并读取已验证的类型、检测到的语言和积分费用。然后将 PDF 翻译为日语并生成双栏对照版本,轮询直至完成,再下载结果。
// Node 18+, Bun or Deno — save as translate.mjs and run `node translate.mjs`.
import { readFile, writeFile } from 'node:fs/promises';
const API = 'https://api.lingivio.com';
const auth = { Authorization: `Bearer ${process.env.LINGIVIO_KEY}` };
// 1. Upload. The answer carries the verified content type, the detected source language and the
// real credit count, so you can price the job before you start it.
const form = new FormData();
form.append('file', new Blob([await readFile('report.pdf')]), 'report.pdf');
const file = await fetch(`${API}/v1/files`, { method: 'POST', headers: auth, body: form })
.then((r) => r.json());
if (!file.id) throw new Error(JSON.stringify(file.error));
console.log(file.content_type, file.detected_source_language, file.credits);
// 2. Translate. The same Idempotency-Key and body return the SAME translation, billed once.
let job = await fetch(`${API}/v1/translations`, {
method: 'POST',
headers: { ...auth, 'content-type': 'application/json', 'Idempotency-Key': crypto.randomUUID() },
body: JSON.stringify({ file_id: file.id, target_language: 'ja', side_by_side: true }),
}).then((r) => r.json());
// 3. Poll while the job is IN PROGRESS, on REAL segment counts. Every other answer ends the loop:
// done, failed, canceled, needs_review — or no status at all (an error answer).
const IN_PROGRESS = ['pending', 'queued', 'dispatched', 'running', 'cancel_requested'];
while (IN_PROGRESS.includes(job.status)) {
await new Promise((resolve) => setTimeout(resolve, 3000));
job = await fetch(`${API}/v1/translations/${job.id}`, { headers: auth }).then((r) => r.json());
if (job.progress) console.log(job.progress.done, '/', job.progress.total);
}
// Only a finished job has an output; `error.class` is stable and machine-readable.
if (job.status !== 'done') throw new Error(`${job.status ?? 'no status'}: ${JSON.stringify(job.error)}`);
// 4. Download
const out = await fetch(`${API}/v1/translations/${job.id}/output`, { headers: auth });
await writeFile('report.ja.pdf', Buffer.from(await out.arrayBuffer())); // TypeScript on Node 18+ (tsx), Bun or Deno — save as translate.ts and run `npx tsx translate.ts`.
import { readFile, writeFile } from 'node:fs/promises';
const API = 'https://api.lingivio.com';
const auth = { Authorization: `Bearer ${process.env.LINGIVIO_KEY}` };
interface ApiError { class: string; retryable: boolean; credit_action: string }
interface PublicFile { id: string; content_type: string; detected_source_language: string | null; credits: number | null }
interface PublicTranslation {
id: string;
status: string;
progress: { done: number; total: number } | null;
error: ApiError | null;
}
// 1. Upload: the answer is the verified file, with its real credit count.
const form = new FormData();
form.append('file', new Blob([await readFile('report.pdf')]), 'report.pdf');
const upload = await fetch(`${API}/v1/files`, { method: 'POST', headers: auth, body: form });
const file = (await upload.json()) as PublicFile & { error?: ApiError };
if (!upload.ok) throw new Error(file.error?.class);
console.log(file.content_type, file.detected_source_language, file.credits);
// 2. Translate (idempotent: a retry with the same key and body is billed once)
let job = (await fetch(`${API}/v1/translations`, {
method: 'POST',
headers: { ...auth, 'content-type': 'application/json', 'Idempotency-Key': crypto.randomUUID() },
body: JSON.stringify({ file_id: file.id, target_language: 'ja', side_by_side: true }),
}).then((r) => r.json())) as Partial<PublicTranslation>;
// 3. Poll while the job is IN PROGRESS. Every other answer ends the loop: done, failed, canceled,
// needs_review — or no status at all (an error answer).
const IN_PROGRESS: string[] = ['pending', 'queued', 'dispatched', 'running', 'cancel_requested'];
while (job.status !== undefined && IN_PROGRESS.includes(job.status)) {
await new Promise((resolve) => setTimeout(resolve, 3000));
job = (await fetch(`${API}/v1/translations/${job.id}`, { headers: auth }).then((r) => r.json())) as PublicTranslation;
if (job.progress) console.log(job.progress.done, '/', job.progress.total);
}
if (job.status !== 'done') throw new Error(`${job.status ?? 'no status'}: ${JSON.stringify(job.error)}`);
// 4. Download
const out = await fetch(`${API}/v1/translations/${job.id}/output`, { headers: auth });
await writeFile('report.ja.pdf', new Uint8Array(await out.arrayBuffer())); # Python 3.9+ with httpx (pip install httpx).
import os
import time
import uuid
import httpx
API = "https://api.lingivio.com"
auth = {"Authorization": f"Bearer {os.environ['LINGIVIO_KEY']}"}
with httpx.Client(base_url=API, headers=auth, timeout=120) as http:
# 1. Upload: the answer carries the verified type, the source language and the real credits.
with open("report.pdf", "rb") as fh:
file = (
http.post("/v1/files", files={"file": ("report.pdf", fh)})
.raise_for_status()
.json()
)
print(file["content_type"], file["detected_source_language"], file["credits"])
# 2. Translate (idempotent: a retry with the same key and body is billed once)
job = (
http.post(
"/v1/translations",
headers={"Idempotency-Key": str(uuid.uuid4())},
json={"file_id": file["id"], "target_language": "ja", "side_by_side": True},
)
.raise_for_status()
.json()
)
# 3. Poll while the job is IN PROGRESS, on REAL segment counts. Every other answer ends the
# loop: done, failed, canceled, needs_review — or no status at all (an error answer).
IN_PROGRESS = {"pending", "queued", "dispatched", "running", "cancel_requested"}
while job.get("status") in IN_PROGRESS:
time.sleep(3)
job = http.get(f"/v1/translations/{job['id']}").json()
if job.get("progress"):
print(job["progress"]["done"], "/", job["progress"]["total"])
# Only a finished job has an output; error.class is stable and machine-readable.
if job.get("status") != "done":
raise RuntimeError(f"{job.get('status', 'no status')}: {job.get('error')}")
# 4. Download
out = http.get(f"/v1/translations/{job['id']}/output").raise_for_status()
with open("report.ja.pdf", "wb") as fh:
fh.write(out.content) # Ruby 3+, standard library only.
require "json"
require "net/http"
require "securerandom"
API = URI("https://api.lingivio.com")
KEY = ENV.fetch("LINGIVIO_KEY")
def call(request)
request["Authorization"] = "Bearer #{KEY}"
Net::HTTP.start(API.host, API.port, use_ssl: API.scheme == "https") { |http| http.request(request) }
end
# 1. Upload: the answer carries the verified type, the source language and the real credits.
upload = Net::HTTP::Post.new("/v1/files")
upload.set_form([["file", File.open("report.pdf", "rb"), { filename: "report.pdf" }]], "multipart/form-data")
file = JSON.parse(call(upload).body)
raise file["error"].to_s unless file["id"]
puts [file["content_type"], file["detected_source_language"], file["credits"]].join(" ")
# 2. Translate (idempotent: a retry with the same key and body is billed once)
start = Net::HTTP::Post.new("/v1/translations", "content-type" => "application/json",
"Idempotency-Key" => SecureRandom.uuid)
start.body = JSON.generate(file_id: file["id"], target_language: "ja", side_by_side: true)
job = JSON.parse(call(start).body)
# 3. Poll while the job is IN PROGRESS. Every other answer ends the loop: done, failed, canceled,
# needs_review — or no status at all (an error answer).
IN_PROGRESS = ["pending", "queued", "dispatched", "running", "cancel_requested"]
while IN_PROGRESS.include?(job["status"])
sleep 3
job = JSON.parse(call(Net::HTTP::Get.new("/v1/translations/#{job["id"]}")).body)
puts "#{job["progress"]["done"]} / #{job["progress"]["total"]}" if job["progress"]
end
raise "#{job["status"] || "no status"}: #{job["error"]}" if job["status"] != "done"
# 4. Download
out = call(Net::HTTP::Get.new("/v1/translations/#{job["id"]}/output"))
File.binwrite("report.ja.pdf", out.body) // Go 1.21+, standard library only: go run translate.go
package main
import (
"bytes"
"crypto/rand"
"encoding/json"
"fmt"
"io"
"mime/multipart"
"net/http"
"os"
"slices"
"time"
)
const api = "https://api.lingivio.com"
var key = os.Getenv("LINGIVIO_KEY")
type translation struct {
ID string `json:"id"`
Status string `json:"status"`
Progress *struct{ Done, Total int } `json:"progress"`
Error json.RawMessage `json:"error"`
}
func call(method, path, contentType string, body io.Reader, headers map[string]string) *http.Response {
req, _ := http.NewRequest(method, api+path, body)
req.Header.Set("Authorization", "Bearer "+key)
if contentType != "" {
req.Header.Set("Content-Type", contentType)
}
for k, v := range headers {
req.Header.Set(k, v)
}
res, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
return res
}
func decode(res *http.Response, into any) {
defer res.Body.Close()
if err := json.NewDecoder(res.Body).Decode(into); err != nil {
panic(err)
}
}
func main() {
// 1. Upload: the answer carries the verified type, the source language and the real credits.
var form bytes.Buffer
mw := multipart.NewWriter(&form)
part, _ := mw.CreateFormFile("file", "report.pdf")
pdf, _ := os.ReadFile("report.pdf")
part.Write(pdf)
mw.Close()
var file struct {
ID string `json:"id"`
ContentType string `json:"content_type"`
DetectedSourceLanguage string `json:"detected_source_language"`
Credits int `json:"credits"`
Error json.RawMessage `json:"error"`
}
decode(call("POST", "/v1/files", mw.FormDataContentType(), &form, nil), &file)
if file.ID == "" {
panic(string(file.Error))
}
fmt.Println(file.ContentType, file.DetectedSourceLanguage, file.Credits)
// 2. Translate (idempotent: a retry with the same key and body is billed once)
idem := make([]byte, 16)
rand.Read(idem)
body, _ := json.Marshal(map[string]any{"file_id": file.ID, "target_language": "ja", "side_by_side": true})
var job translation
decode(call("POST", "/v1/translations", "application/json", bytes.NewReader(body),
map[string]string{"Idempotency-Key": fmt.Sprintf("%x", idem)}), &job)
// 3. Poll while the job is IN PROGRESS. Every other answer ends the loop: done, failed,
// canceled, needs_review — or no status at all (an error answer).
inProgress := []string{"pending", "queued", "dispatched", "running", "cancel_requested"}
for slices.Contains(inProgress, job.Status) {
time.Sleep(3 * time.Second)
id := job.ID
job = translation{}
decode(call("GET", "/v1/translations/"+id, "", nil, nil), &job)
if job.Progress != nil {
fmt.Println(job.Progress.Done, "/", job.Progress.Total)
}
}
if job.Status != "done" {
panic(fmt.Sprintf("%q: %s", job.Status, job.Error))
}
// 4. Download
res := call("GET", "/v1/translations/"+job.ID+"/output", "", nil, nil)
defer res.Body.Close()
out, _ := os.Create("report.ja.pdf")
defer out.Close()
io.Copy(out, res.Body)
} # 1. Create a key in Settings → API keys (Business and Enterprise plans), then:
export KEY="llk_your_key_here"
export API="https://api.lingivio.com"
# 2. Upload the file. The response carries the VERIFIED content type, the detected
# source language and the real credit count — so you can price the job first.
# (`page_count` is the same number under its old, misleading name; prefer `credits`.)
FILE=$(curl -s -X POST "$API/v1/files" \
-H "Authorization: Bearer $KEY" \
-F "file=@report.pdf")
echo "$FILE" | jq '{id, content_type, detected_source_language, credits}'
FILE_ID=$(echo "$FILE" | jq -r .id)
# 3. Start the translation. Idempotency-Key makes a retry safe: the same key with the
# same body returns the SAME translation and is billed once.
JOB=$(curl -s -X POST "$API/v1/translations" \
-H "Authorization: Bearer $KEY" \
-H "Idempotency-Key: $(uuidgen)" \
-H "content-type: application/json" \
-d '{"file_id":"'"$FILE_ID"'","target_language":"ja","side_by_side":true}')
JOB_ID=$(echo "$JOB" | jq -r .id) # null if refused: "$JOB" then names the error class
# 4. Poll while the job is IN PROGRESS. progress.done / progress.total are REAL segment counts.
# Every other answer ends the loop: done, failed, canceled, needs_review — or no status at all
# (an error answer: the job was refused, expired, or the key was revoked).
IN_PROGRESS=" pending queued dispatched running cancel_requested "
STATUS=$(echo "$JOB" | jq -r '.status // empty')
while [ -n "$STATUS" ] && [[ "$IN_PROGRESS" == *" $STATUS "* ]]; do
sleep 3
JOB=$(curl -s "$API/v1/translations/$JOB_ID" -H "Authorization: Bearer $KEY")
STATUS=$(echo "$JOB" | jq -r '.status // empty')
done
# 5. Download — only a finished job has an output. Anything else: the answer names the error class.
if [ "$STATUS" = done ]; then
curl -s "$API/v1/translations/$JOB_ID/output" -H "Authorization: Bearer $KEY" -o report.ja.pdf
else
echo "$JOB" | jq '{status, error}'
fi 将其作为工具交给智能体
一个可由智能体框架注册为工具的 Python 函数,附有供模型使用的 JSON Schema。它会拒绝费用超过所传入上限的文件。它根据文件和语言生成 Idempotency-Key,确保重试调用只计费一次。它返回错误而非抛出异常,让智能体决定下一步操作。
# A tool an AI agent can call: translate one local file and save the result beside it.
# Register `translate_document` with your agent framework and give the model TOOL_SCHEMA.
import os
import time
import httpx
API = "https://api.lingivio.com"
auth = {"Authorization": f"Bearer {os.environ['LINGIVIO_KEY']}"}
TOOL_SCHEMA = {
"name": "translate_document",
"description": "Translate a document file into another language and save a file of the "
"same type. Layout, formulas, numbers and codes are kept. Costs credits.",
"input_schema": {
"type": "object",
"properties": {
"path": {"type": "string", "description": "Path of the file to translate"},
"target_language": {
"type": "string",
"description": "Language code, e.g. de",
},
"max_credits": {"type": "integer", "description": "Refuse above this cost"},
},
"required": ["path", "target_language"],
},
}
# Every other answer ends the poll: done, failed, canceled, needs_review, or an error answer.
IN_PROGRESS = {"pending", "queued", "dispatched", "running", "cancel_requested"}
def translate_document(
path: str, target_language: str, max_credits: int | None = None
) -> dict:
"""{"output": path, "credits": n} on success; otherwise {"error": ...} to branch on."""
with httpx.Client(base_url=API, headers=auth, timeout=120) as http:
# 1. Upload. The answer carries the verified credit cost; nothing is charged yet.
with open(path, "rb") as fh:
r = http.post("/v1/files", files={"file": (os.path.basename(path), fh)})
file = r.json()
if r.is_error:
return {"error": file.get("error")}
if max_credits is not None and file["credits"] > max_credits:
return {"error": "over_budget", "credits": file["credits"]}
# 2. Translate. The key is derived from the file and the language, so an agent that
# retries this step gets the SAME translation back and is billed once.
r = http.post(
"/v1/translations",
headers={"Idempotency-Key": f"translate-{file['id']}-{target_language}"},
json={"file_id": file["id"], "target_language": target_language},
)
job = r.json()
# 3. Poll on real segment counts.
while job.get("status") in IN_PROGRESS:
time.sleep(3)
job = http.get(f"/v1/translations/{job['id']}").json()
if job.get("status") != "done":
return {"error": job.get("error"), "status": job.get("status")}
# 4. Download a file of the same type.
out = http.get(f"/v1/translations/{job['id']}/output").raise_for_status()
root, ext = os.path.splitext(path)
output = f"{root}.{target_language}{ext}"
with open(output, "wb") as fh:
fh.write(out.content)
return {"output": output, "credits": file["credits"]}
if __name__ == "__main__":
print(translate_document("report.docx", target_language="de")) 需要 Python 3.10 或更高版本及 httpx。它调用的端点与快速入门相同。不绑定于特定智能体框架。
智能体应遵循的规则
幂等性
在任何 POST 请求中发送 Idempotency-Key。相同密钥配合相同请求体会返回首次调用创建的资源,且仅计费一次。相同密钥配合不同请求体会被拒绝并返回 409。密钥记录保留 24 小时。
速率限制
限制按密钥计算,采用固定的 60 秒窗口。每个响应都包含 X-RateLimit-Limit 和 X-RateLimit-Remaining。429 响应包含 Retry-After。同一账号的两个密钥各有独立限额。
MCP 服务器
可用Lingivio MCP 服务器让 AI 助手或代码编辑器(ChatGPT或Claude,或任何支持远程 MCP 服务器的客户端)使用你自己的账号和积分,为文档估价、翻译并下载文档。
服务器地址
https://api.lingivio.com/mcp 连接并翻译
- 1. 将上方的服务器地址添加到客户端:在 Claude 或 ChatGPT 中将其添加为自定义连接器,在代码编辑器中则添加到 MCP 设置。设置指南提供了各客户端的具体步骤。
- 2. 首次连接时,会打开 Lingivio 登录窗口。登录后,选择“允许”。客户端无法看到你的密码,也无法通过你的账号购买任何东西。
- 3. 附加文档并指定语言。Lingivio 会计算积分费用,在你确认前不会扣费。
- 4. 查看进度,然后通过助手显示的链接下载译文文件。
登录采用带 PKCE 的 OAuth 2.1。服务器在标准 well-known 地址发布 OAuth 元数据,每个访问令牌都绑定到此服务器。
翻译流程包含四个工具,按以下顺序调用:
- prepare_translation
- start_translation
- get_translation_status
- get_download_link
只读工具可回答有关账号、支持的语言和近期翻译的问题。
Professional、Business和Enterprise 已包含此功能。使用其他套餐的客户端可以连接,但每个请求都会被拒绝,并返回 plan.mcp_access_required。
Claude、ChatGPT、Cursor 和其他客户端的设置指南适用于 Claude 的 Lingivio 技能
Claude 会自行读取你附加到聊天中的文件,不会将其传给连接器。Lingivio 技能会指示 Claude 通过一次性上传链接发送你要翻译的文档,让你获得保留版式的译文文件,而不是聊天中的翻译文本。
下载技能(ZIP)将技能添加到 Claude
- 1. 在 Claude 中打开“设置”,然后进入“功能”,开启代码执行和文件创建。技能需要这些功能。
- 2. 打开“自定义”,然后进入“技能”。选择“+”,再选择“创建技能”,然后选择“上传技能”。
- 3. 选择下载的 ZIP。该技能名为 lingivio-translate-documents。同时保持 Lingivio 连接器处于连接状态:此技能会使用它的工具。
使用 Team 或 Enterprise 套餐时,所有者可以为所有人添加技能:在“组织设置”中打开“插件和技能”,在“策略”选项卡中开启“技能”,然后选择“添加”和“上传技能”。此技能会为每位成员开启,每位成员都可以将其关闭。
列出 MCP 服务器提示词的应用也会提供 Lingivio 的提示词:“使用 Lingivio 翻译文档”。它会询问你想翻译成哪种语言,并启动相同的流程。
面向语言模型
llms.txt 以 llms.txt 格式为本站建立索引。llms-full.txt 还包含本指南及示例,让模型只需一次获取即可了解如何调用 Lingivio。OpenAPI 文档为客户端生成器描述了所有端点。