克拉瓦塔 Java 脚本 SDK
此目录包含 克拉瓦塔语Name JavaScript SDK 有类型定义.
开始
电子邮件 翻译: 如果您还没有 API 密钥/托肯 .
初始化 SDK 开始向 Clavata API 提出请求.
import Clavata from "@clavata/sdk";
// API key can be provided directly or via environment variable
const client = new Clavata({ apiKey: "<YOUR_CLAVATA_API_KEY>" } as Options);
配置
客户端构建器接受以下选项:
interface Options {
// Your API key. If not provided you _must_ then set CLAVATA_API_KEY as an environment variable
apiKey?: string;
// Optional
server?: string; // Server endpoint (default: "gateway.app.clavata.ai:443")
insecure?: boolean; // Use insecure connection. (default: false)
keepalive?: {
// Connection keepalive settings
timeout: number; // How long to wait for a response to a keepalive ping before considering the connection dead (in ms). (default: 10000)
permitWithoutCalls: boolean; // Allows keepalive pings to maintain idle connections. (default: true)
time: number; // How frequently to send keepalive pings to check if the connection is alive (in ms). (default: 10000)
};
maxMessageLength?: number; // Max message size (default: 100MB)
retryConfig:
| {
// Configuration for automatic retries. Will retry by default. Set to `false` to disable this. See https://grpc.io/docs/guides/retry for more info.
maxAttempts?: number; // Maximum number of retry attempts (default: 5)
initialBackoff?: string; // Initial backoff time in milliseconds (default: "1s")
maxBackoff?: string; // Maximum backoff time (default: "30s")
backoffMultiplier?: number; // Multiplier for backoff time after each retry (default: 2.0)
jitter?: number; // Jitter factor between 0 and 1 (default: 0.2, 0 = no jitter, 1 = full jitter)
}
| false;
}
如果没有向构造者提供 API 密钥, 也不是一种 process.env.CLAVATA_API_KEY 环境变量设置后, 构造器将丢出一个错误 .
RPC 方法
getJob(jobId: string): Promise<Job | undefined>
- 由UUID获取一份工作.
listJobs(request: ListJobsRequest): Promise<ListJobsResponse>
- 列出带有过滤参数的工作.
createJob(request: CreateJobRequest): Promise<CreateJobResponse[]>
- 以提供的内容数据创建新任务,并返回稍后可以请求的任务的ID和状态. 如果您需要等待结果使用
evaluate换句话说.
evaluate(request: EvaluateRequest): Promise<AsyncIterable<EvaluateMessage | StreamError>>
- 评估每个输入并返回一系列的回复或错误。 秩序得不到保证,因此在发送多块进行单调评价时,会建议使用元数据或内容Hash.
- 示例
const stream = client.evaluate({
contentData: [
{
metadata: { id: "1" },
content: { value: "Hello, world!", $case: "text" },
contentType: "text",
},
{
metadata: { id: "2" },
content: { value: Buffer.from("<BASE64_DATA>", "base64"), $case: "image" },
contentType: "image/png",
},
{
metadata: { id: "3" },
content: { value: "<IMAGE_URL>", $case: "imageUrl" },
contentType: "image/jpeg",
},
],
policyId: "00000000-0000-0000-0000-000000000000",
});
for await (const item of stream) {
if (item instanceof StreamError) throw item;
const { metadata, report } = item;
console.log({ id: metadata?.id, matches: report?.matches });
}
beta.evaluateLabels(request: EvaluateLabelsRequest): Promise<EvaluateLabelsResponse>
- 标签 v2 评价目前为β并暴露于
client.beta.evaluateLabels。 。 。 . - 对照1-10 明确的标签 v2 标签版本ID 来评价一个内容项 .
- 需要为您的客户账户启用标签 v2 .
- 结果以请求的标签版本ID顺序返回.
- 标准对策包括:
contentHash而且,对于每一项结果,labelId, (中文(简体) ),labelVersionId, (中文(简体) ),jobUuid,或者说evaluation(单位:千美元)outcome, (中文(简体) ),score, (中文(简体) ),threshold)或(或)error,没有巢状报告。 这通常足以用于大多数SDK用途. - 每个标签失败在响应中因结果错误被返回;运输,认证,以及平台错误仍然拒绝调用.
- 设定
includeEvaluationReport: true仅当您需要关于每个标签评价成功的可选嵌入式报告数据时,例如report.matches。 。 。 . - 示例
const response = await client.beta.evaluateLabels({
content: {
metadata: { id: "1" },
content: { value: "Hello, world!", $case: "text" },
contentType: "text",
},
labelVersionIds: ["00000000-0000-0000-0000-000000000000", "11111111-1111-1111-1111-111111111111"],
threshold: 0.5,
});
for (const result of response.results) {
if (result.error) {
console.log({
labelId: result.labelId,
labelVersionId: result.labelVersionId,
jobUuid: result.jobUuid,
error: result.error.message,
});
continue;
}
console.log({
labelId: result.labelId,
labelVersionId: result.labelVersionId,
jobUuid: result.jobUuid,
outcome: result.evaluation?.outcome,
score: result.evaluation?.score,
threshold: result.evaluation?.threshold,
});
}
何时 includeEvaluationReport: true 设置,后端返回报告数据, result.evaluation?.report 与政策评价报告相同,包括: matches。 。 。 .
所生成的LabelsService CRUD,版本,草稿,标记,批量,和数据集API都是私有的,不是公共SDK表面的一部分.
拒绝
在某些情况下,Clavata API会拒绝按要求评价内容. 仅有几个可能的原因:
- 内容( 图像) 符合 CSAM 数据库中已知的散列 。 这可以是精确匹配,也可以是感知的散列匹配.
- 内容(图像)采用不支持的格式. 目前, Clavata 支持
webp, (中文(简体) ),png财务报告和审定财务报表jpg图像. - 内容是腐败的。 通常因为内容不完整或编码(对于图像)不正确.
当出现拒绝时,a StreamError 将返回 evaluate)或抛出(用于: createJob) (中文(简体) ). 您可以使用 : getRefusalReason() 方法 StreamError 类型。 如果错误是 没有 由于拒绝,此方法将返回 undefined。如果错误 是因为拒绝页:1 RefusalReason 将返回.
这个 RefusalReason 类型是带有符合下列条件之一的字符串的圆柱:
"CSAM""UNSUPPORTED_IMAGE_FORMAT""INVALID_IMAGE"
还有一个 "UNKNOWN" 选项,但这个案例显示,在答复中,对“理由”信息进行解码出错.
import { RefusalReason } from "@clavata/sdk";
const stream = client.evaluate(...)
for await (const item of stream) {
if (item instanceof StreamError) {
const reason = item.getRefusalReason();
if (!reason) {
// Not a refusal, you can check the other possible identification methods like
if (item.isTransient()) {
// Transient error so we can retry
}
}
// It was a refusal, so we can use a switch statement to figure out why
switch (reason) {
case RefusalReason.CSAM:
// Handle CSAM appropriately
break;
case RefusalReason.UNSUPPORTED_IMAGE_FORMAT:
// Convert image and try again
break;
case RefusalReason.INVALID_IMAGE:
// data corruption, maybe try to re-download from CDN and try again?
break;
default:
// unknown reason for refusal
}
}
}
获取拒绝错误
如果你喜欢,你可以转换一个 StreamError 改为 a RefusalError 与 toRefusalError() 方法。 如果错误是 没有 由于拒绝,此方法将返回 undefined然而,如果拒绝 对 发生 RefusalError 返回的类型有以下界面,您可以用来理解原因:
interface RefusalError {
isCSAM(): boolean;
isUnsupportedImageFormat(): boolean;
isInvalidImage(): boolean;
isUnknown(): boolean;
getReason(): RefusalReason;
}
// So you can do this:
if (item instanceof StreamError) {
const refusalErr = item.toRefusalError();
if (refusalErr.isCSAM()) {
// Take action based on the content having been CSAM
}
}
你用来确定原因的接口由你决定,在功能上是等同的.
拒绝和 createJob
打电话时 createJob承诺得到回报 如果发生错误,则该错误将自动转换为 StreamError 由SDK重新推出. 你就可以抓住那个 StreamError 并检查拒绝的方式相同.
Monorepo发展
在奥林匹斯独行侠队工作时 SDK 工作流程 用于单位测试的活烟examples/sdk),和出版(下).
捐款
更新版本为 npm version <new_version> 然后运行 npm publish。 。 。 .