Skip to content

Latest commit

 

History

History
257 lines (192 loc) · 16.3 KB

README.md

File metadata and controls

257 lines (192 loc) · 16.3 KB

TokenCraft Rust SDK

Start with the synthetic image quickstart to submit and reopen a request and download a verified PNG.

Use tokencraft_sdk in a Craft backend or another trusted Rust process. For a local checkout, add the SDK as a path dependency.

[dependencies]
tokencraft_sdk = { path = "/path/to/tokencraft/sdk/rust" }

Build a TokenCraftClient with the gateway base URL and a project key from your secret configuration. The client selects a scoped quote when a key is configured. catalog() and quote_public() are available for public comparison.

use tokencraft_sdk::{QuoteInput, SubmitOptions, TokenCraftClient, WaitOptions, Workload};

let client = TokenCraftClient::new(&base_url, Some(&api_key))?;
let quote = client.quote(&QuoteInput {
    model: "example_image".into(),
    workload: Workload::Image {
        count: 1,
        aspect_ratio: "4:3".into(),
        max_relative_error_bps: None,
    },
    provider: None,
    max_total_usd_nanos: None,
}).await?;
let receipt = client.submit(&quote, SubmitOptions::new(job_key)).await?;
let trace = client.wait(&receipt.id, WaitOptions::default()).await?;

Persist the quote, submission options, and stable job key before submitting. Replay them to recover the receipt after an interrupted submission. wait returns when the request reaches a terminal status or needs reconciliation. A timeout carries the durable request ID when available. Dropping a polling future stops local polling. Use cancel(id) to request gateway cancellation explicitly.

Native submissions and published workflow invocations make one attempt by default. Add .with_submit_max_attempts(3)? when creating the client to enable retries after a connection error, an interrupted success response, or a 429 or 503 with a valid Retry-After in seconds or as an HTTP date. The limit includes the first attempt. Every retry uses the same serialized body and idempotency key within the original client timeout. During polling, wait follows the same HTTP hints. If a connection drops, a response body is interrupted, or a single read times out, polling resumes at the configured interval with the last valid validator. The overall wait deadline still applies.

Native submissions verify that the receipt's request ID agrees with its status URL and any TokenCraft-Request-Id header. An inconsistent receipt returns invalid_response. Recover the receipt by explicitly replaying the saved submission.

Artifact and workflow-output downloads also make one attempt by default. Add .with_download_max_attempts(3)? to retry an interrupted transfer or a 429 or 503 with a valid Retry-After. Each attempt starts the download again and verifies the final file. A response that fails integrity validation returns an error. The same timeout covers the full operation.

The SDK gives an HTTP error body up to one second and 64 KiB within the operation deadline. If it cannot decode the error details, Error::Gateway reports http_error with the HTTP status and any available request ID.

To link a caller span, use client.clone().with_submit_traceparent(traceparent)? for that span's submissions. Pass the trace header generated by your application's tracer. Call trace(&receipt.id) to read the stored correlation, or use list_filtered with RequestFilters::trace_id to find the request by the caller's trace ID. Trace correlation

For automatic model selection, set QuoteInput::model to "auto" and use a project key. Use quote_with_options to combine provider preferences, community thresholds, and client attribution. submit preserves the request-level preferences and thresholds in the quote. Each automatic candidate names the model it represents. Routing policy precedence

For a shared project key, set the client reference with quote_scoped_for_client or QuoteOptions::client_ref. Use the same reference in SubmitOptions::client_ref.

Set QuoteOptions::data_requirements to limit provider processing regions or upstream retention. Persist the returned Quote before submitting. Its input holds the normalized request and retains those limits across serialization and replay. The effective requirements appear under routing.data_requirements. Use quote.input.base when you need ownership of the basic QuoteInput, or input.into() when constructing a quote from basic fixture input. Data handling requirements

Use get(id) and events(id) to inspect the request, result(id) for a stored chat result, and list and usage for client filters and cursor pagination. The usage report preserves aggregated nano-USD amounts as decimal strings.

For a quote that selects an image offer, set SubmitOptions::image_prompt and call image_result(id) after success. When an image includes artifact, pass the saved reference to download_artifact with ArtifactLocation::Warm to verify the downloaded bytes. The trace's upstream.accepted_at and upstream.queue_state show acknowledgment and queue progress. Example connector walkthrough

The audio, video, and mesh verification examples require TOKENCRAFT_MODEL to name a compatible model in the deployment’s catalog. Set TOKENCRAFT_API_KEY to a scoped project key and TOKENCRAFT_BASE_URL to your gateway when it differs from http://localhost:4000.

Filter and page through Usage

Use a project key with usage:read. Group by UsageGrouping::ApiKey to see stable key identities and their labels. An api_key_ref keeps usage from all rotations of a service principal together. Add credential_id to restrict the report to one issued key. Amounts remain decimal strings in nano-USD.

use tokencraft_sdk::{UsageFilters, UsageGrouping};

let filters = UsageFilters {
    client_ref: Some("example-client"),
    group_by: Some(UsageGrouping::ApiKey),
    limit: Some(20),
    ..Default::default()
};
let first = client.usage_filtered(filters.clone()).await?;
if let Some(cursor) = first.next_after.as_deref() {
    let next = client.usage_filtered(UsageFilters {
        after: Some(cursor),
        ..filters
    }).await?;
    // Read next.groups here.
}

Reuse the same filters and pass the cursor unchanged. Each page's totals cover the entire filtered window. Usage API

Usage reads make one attempt by default. Set with_usage_max_attempts(3)? on the client to retry HTTP 429 or 503 responses with a valid Retry-After header. Each retry uses the same filters and cursor, and all attempts share the original timeout. A usage_report_timeout response calls for a shorter date window.

Trace requests behind a Usage report

Use a key with requests:read to call list_attributed. Pass the Usage group's stable key reference as api_key_ref. Use credential_id for a single credential or api_key_unattributed: Some(true) for requests without key attribution. Reuse the same filters when passing next_after.

use tokencraft_sdk::{AttributedRequestFilters, RequestFilters};

let page = client.list_attributed(AttributedRequestFilters {
    filters: RequestFilters {
        client_ref: Some("example-client"),
        ..Default::default()
    },
    api_key_ref: Some(stable_key_ref),
    ..Default::default()
}).await?;
if let Some(row) = page.requests.first() {
    let detail = client.get_attributed(&row.request.id).await?;
    let trace = client.trace(&detail.request.id).await?;
}

A historical request can have a stable key reference with no recorded credential ID. Key attribution

Chain generation with existing assets

Read CatalogModel::operation_workloads from client.models().await? for presets specific to an operation. Use OperationKind::ImageEdit for edit ratios and OperationKind::ImageToVideo for animation. Each OperationWorkload::Video keeps its ratios, durations, and resolution together. The map is empty on older gateways. Use a scoped quote to confirm that an offer can serve the selected workload. Model workload presets

Call quote_operation with typed input references and output requirements. Use an AssetSource::Artifact containing the source request ID and artifact slot to reuse an output directly. The SDK preserves the operation from the normalized quote when it submits or retries.

The asset_chain_verification example exercises an image edit followed by animation of the edited artifact. On a disposable gateway with both offers configured, set TOKENCRAFT_SOURCE_PNG to a local PNG to upload, or set TOKENCRAFT_SOURCE_REQUEST_ID to an available image request in the same project with an image in slot zero. Set TOKENCRAFT_IMAGE_MODEL, TOKENCRAFT_VIDEO_MODEL, and TOKENCRAFT_VERIFICATION_KEY alongside the gateway URL and project key. Run cargo run --locked -p tokencraft_sdk --example asset_chain_verification. The example checks that replay returns the original image edit receipt and verifies the final MP4 download.

Reference scoped media in chat

Use quote_operation with a text workload and a chat operation that requires OperationFeature::TextOutput. List the upload or prior artifact references in their message order. Pass them to submit_chat in a user message as ChatContentPart::Asset, alongside any ChatContentPart::Text. Use the same project and client scope for the quote and submission. Read the completed chat response with result.

Transcribe a prior speech artifact

Call infer with InferenceInput::SpeechSynthesis to create speech. Wait on the returned request ID and read the verified WAV reference with inference_result. Use its request ID, slot, and byte length to submit transcription within the same project and client scope.

use tokencraft_sdk::{AssetSource, InferenceInput, InferenceOptions, InferenceOutput, InferenceRequest};

let speech = client.inference_result(speech_request_id).await?;
if let InferenceOutput::Speech { audio } = speech.result {
    let request = InferenceRequest::new(
        "studio-transcription",
        InferenceInput::Transcription {
            audio: AssetSource::Artifact {
                request_id: speech_request_id.to_owned(),
                slot: audio.artifact.slot,
            },
            byte_length: audio.artifact.byte_length,
            language: Some("en"),
        },
    );
    let receipt = client.infer(&request, InferenceOptions::new("studio-transcription-01")).await?;
    // Wait for the receipt, then use inference_result to read the transcript.
}

Use InferenceOutput::Structured to read the transcript, embedding vectors, or reranking scores. A submission uses one attempt by default. Reuse the same key and operation to recover an interrupted admission.

Reopen a request from a second process

Set TOKENCRAFT_API_KEY to a project key with requests:submit and requests:read. Set TOKENCRAFT_BASE_URL to your local fixture gateway if it differs from http://localhost:4000.

cargo run --quiet --locked -p tokencraft_sdk --example restart -- quote > quote.json
cargo run --quiet --locked -p tokencraft_sdk --example restart -- submit quote.json craft-job-42 > receipt.json
request_id=$(python3 -c 'import json, sys; print(json.load(sys.stdin)["id"])' < receipt.json)
cargo run --quiet --locked -p tokencraft_sdk --example restart -- wait "$request_id"

Run a published workflow

Create a client with the published workflow's application key. Use the active OpenAPI document to find the input names, supported file types, and named outputs. This example uses an endpoint with video and narration inputs and a master output.

use tokencraft_sdk::{TokenCraftClient, WaitOptions, WorkflowInvokeOptions, WorkflowRunStatus};

let client = TokenCraftClient::new(&base_url, Some(&workflow_app_key))?;
let endpoint = client.workflow(&project_id, &workflow_id)?;
let contract = endpoint.contract().await?;
let video = endpoint.upload("video/mp4", video_bytes).await?;
let narration = endpoint.upload("audio/wav", narration_bytes).await?;
let inputs = [("video".into(), video.input()), ("narration".into(), narration.input())].into();
let mut options = WorkflowInvokeOptions::new(job_key);
options.client_ref = Some(customer_ref);
let receipt = endpoint.invoke(&inputs, options).await?;
let run = endpoint.wait(&receipt.id, WaitOptions::default()).await?;
if run.status == WorkflowRunStatus::Succeeded {
    let output = endpoint.download_output(&run.id, "master").await?;
    std::fs::write("master.mp4", output.bytes)?;
}

Supply WorkflowInput::WorkflowOutput { run_id, output } for a media input to reuse a compatible named output from a successful run of the same workflow, application, and client. The output must still be retained, and the application key needs both runs:read and outputs:read in addition to runs:submit.

Save the invocation inputs and job key to replay admission after an interruption. Once you have the run ID, use get or wait to reopen it. Pass reuse_run_id for a new invocation that can reuse eligible steps from a prior run. A polling timeout stops the local wait. Call cancel with a key that has runs:cancel to stop further admission. The download method builds a scoped gateway route from the run ID and output name and verifies the SHA-256 returned with the bytes. Workflow permissions and lifecycle

Verify a terminal webhook

Give verify_webhook the actual HTTP header map and original body bytes. The verifier accepts the current key or overlapping keys during rotation. It verifies the HMAC, replay window, and event envelope. Deduplicate the verified event ID in durable storage before applying downstream side effects.

use tokencraft_sdk::{verify_webhook, WebhookOptions};

let event = verify_webhook(&headers, &raw_body, &[&signing_secret], WebhookOptions::default())?;
handle_event_once(&event.id, &event)?;

Native request verification checks the project ID, terminal status, and request fetch path in event.data.attributes. Use event.data.client_ref() for the optional client reference.

For workflow terminal events, use verify_workflow_webhook with the same arguments. Its verified data contains the workflow run ID, terminal state, relative status URL, and the optional data.client_ref supplied at invocation.

cargo test --locked -p tokencraft_sdk runs the loopback HTTP and webhook tests from a source checkout. The restart example uses the disposable gateway described in the setup guide.

Inspect a request

After submission, retain the request ID. Use a key with requests:read.

let trace = client.trace(request_id).await?;
let baseline = client.trace_baseline(request_id).await?;
let otlp_json = serde_json::to_string(&client.trace_otlp(request_id).await?)?;

The catalog's custom provider IDs are available through Provider::as_str(). Use Provider::Custom when passing a custom provider to a quote. See the diagnostics endpoints.

Read retained history

Use content_metadata to check dates, phase, and any restore progress without fetching input or output. Read warm input and results with warm_content. Use retrieve_content to read an available archive. Each operation uses the project's requests:read scope and the API key's client restriction.

use tokencraft_sdk::{ArtifactLocation, ContentPhase, RetainedResult};

let metadata = client.content_metadata(&request_id).await?;
if metadata.phase == ContentPhase::Archived {
    let retained = client.retrieve_content(&request_id).await?;
    if let Some(RetainedResult::Images(output)) = retained.result {
        if let Some(artifact) = output.images.first().and_then(|image| image.artifact.as_ref()) {
            let file = client.download_artifact(&request_id, artifact, ArtifactLocation::Archived).await?;
            std::fs::write("output.png", file.bytes)?;
        }
    }
}

A cold object can return HTTP 409 with archive_retrieval_required. A project administrator can start a restore in Requests. Call content_metadata again to check its progress. Artifact downloads read from the configured gateway and verify the saved byte length and SHA-256. Retention and restore guide