cencori 1.4.0

Official Rust SDK for Cencori - AI Infrastructure for Production
Documentation

Cencori Rust SDK

Official Rust SDK for Cencori - AI Infrastructure for Production.

One SDK for AI Gateway, Compute, Workflow, and Storage. Every operation is secured, logged, and tracked.

Installation

Add to your Cargo.toml:

[dependencies]
cencori = "1.2"

Quick Start

use cencori::{Cencori, types::Message};

let cencori = Cencori::new(Some("your-api-key"), None, None).unwrap();

// Chat
let response = cencori.ai.chat(
    vec![Message::user("Hello!")],
    None, None, None, None,
).unwrap();
println!("{}", response.content);

// Embeddings
use cencori::types::EmbeddingInput;
let embedding = cencori.ai.embeddings(
    EmbeddingInput::Single("Hello world".into()),
    Some("text-embedding-3-small"),
).unwrap();
println!("Dimension: {}", embedding.embeddings[0].len());

Async Support

All methods have async counterparts:

use cencori::{Cencori, types::Message};

#[tokio::main]
async fn main() {
    let cencori = Cencori::new(Some("your-api-key"), None, None).unwrap();

    // Async chat
    let response = cencori.ai.async_chat(
        vec![Message::user("Hello!")],
        None, None, None, None,
    ).await.unwrap();
    println!("{}", response.content);
}

Streaming

use cencori::{Cencori, types::Message};

let cencori = Cencori::new(Some("your-api-key"), None, None).unwrap();

for chunk in cencori.ai.chat_stream(
    vec![Message::user("Tell me a story")],
    Some("gpt-4o"), None, None, None,
).unwrap() {
    let chunk = chunk.unwrap();
    print!("{}", chunk.delta);
}

Structured Output (Object Generation)

use cencori::Cencori;
use serde_json::json;

let cencori = Cencori::new(Some("your-api-key"), None, None).unwrap();

let schema = json!({
    "type": "object",
    "properties": {
        "name": { "type": "string" },
        "age": { "type": "number" }
    },
    "required": ["name", "age"]
});

let response = cencori.ai.generate_object::<serde_json::Value>(
    "gpt-4o",
    Some("Generate a fictional user profile"),
    schema,
    None, None, None, None,
).unwrap();
println!("{:?}", response.object);

Vision (Image Understanding)

Analyze, describe, OCR, and classify images. Routes across OpenAI, Anthropic, and Google vision-capable models.

use cencori::Cencori;
use cencori::vision::VisionParams;

let cencori = Cencori::new(Some("your-api-key"), None, None).unwrap();

// General analysis with a custom prompt
let params = VisionParams::from_url("https://example.com/photo.jpg")
    .with_prompt("What breed of dog is this?");
let result = cencori.vision.analyze(&params).unwrap();
println!("{}", result.analysis);

// OCR from a local file
use std::fs;
use base64::{engine::general_purpose, Engine};
let bytes = fs::read("receipt.png").unwrap();
let b64 = general_purpose::STANDARD.encode(&bytes);

let ocr = cencori
    .vision
    .ocr(&VisionParams::from_base64(b64, "image/png"))
    .unwrap();
println!("{}", ocr.text);

Async variants: cencori.vision.async_analyze(&params).await, async_describe, async_ocr, async_classify.

See docs for the full API.

Documents (PDF & Image Extraction)

Extract text from PDFs and images, summarize, and answer questions. Text-based PDFs use native parsing — no LLM tokens.

use cencori::documents::DocumentParams;
use cencori::Cencori;

let cencori = Cencori::new(None, None, None)?;

// Extract text (native PDF parse — free)
let result = cencori
    .documents
    .extract(&DocumentParams::from_url("https://example.com/contract.pdf"))?;
println!("method: {}", result.method); // 'pdf_text' — no LLM cost

// Summarize
let summary = cencori
    .documents
    .summarize(&DocumentParams::from_url("https://example.com/report.pdf"))?;
println!("{}", summary.summary);

// Q&A — strict "Not found" if answer isn't present
let answer = cencori.documents.query(
    &DocumentParams::from_url("https://example.com/contract.pdf")
        .with_question("What is the termination clause?"),
)?;
println!("{}", answer.answer);

Async variants: cencori.documents.async_extract(&params).await, async_summarize, async_query.

See docs for the full API.

Image Generation

use cencori::Cencori;

let cencori = Cencori::new(Some("your-api-key"), None, None).unwrap();

let response = cencori.ai.generate_image(
    "A futuristic city at sunset",
    Some("dall-e-3"), None,
    Some("1024x1024"), Some("hd"),
    None, None,
).unwrap();
println!("{:?}", response.images[0].url);

RAG (Retrieval-Augmented Generation)

use cencori::{Cencori, types::Message};

let cencori = Cencori::new(Some("your-api-key"), None, None).unwrap();

let response = cencori.ai.rag(
    "gpt-4o",
    vec![Message::user("What are our company policies?")],
    "company-docs",
    None, None, Some(5), None, None,
).unwrap();
println!("{}", response.message.content);

Responses API

use cencori::Cencori;
use serde_json::json;

let cencori = Cencori::new(Some("your-api-key"), None, None).unwrap();

let response = cencori.ai.responses(
    "gpt-4o",
    json!("What is the weather in San Francisco?"),
    None, None, None, None, None, None,
    None, None, None, None, None, None, None, None,
).unwrap();
println!("{}", response.id);

Agent Management

use cencori::{Cencori, types::CreateAgentParams};

let cencori = Cencori::new(Some("your-api-key"), None, None).unwrap();

// Create an agent
let agent = cencori.agents.create(&CreateAgentParams {
    name: "my-agent".into(),
    description: Some("A helpful assistant".into()),
    config: None,
}).unwrap();

// List agents
let agents = cencori.agents.list().unwrap();

// Create an agent key
use cencori::types::CreateAgentKeyParams;
let key = cencori.agents.create_key(&agent.id, &CreateAgentKeyParams {
    name: Some("prod-key".into()),
    environment: Some("production".into()),
    key_type: Some("secret".into()),
    allowed_domains: None,
}).unwrap();

Memory (Vector Storage)

use cencori::{Cencori, types::CreateNamespaceOptions};

let cencori = Cencori::new(Some("your-api-key"), None, None).unwrap();

// Create a namespace
let ns = cencori.memory.create_namespace(&CreateNamespaceOptions {
    name: "conversations".into(),
    description: Some("User conversations".into()),
    embedding_model: None,
    dimensions: None,
    metadata: None,
}).unwrap();

// Store a memory
use cencori::types::StoreMemoryOptions;
let memory = cencori.memory.store(&StoreMemoryOptions {
    namespace: "conversations".into(),
    content: "User asked about pricing".into(),
    embedding: None,
    metadata: None,
    expires_at: None,
}).unwrap();

// Search memories
use cencori::types::SearchMemoryOptions;
let results = cencori.memory.search(&SearchMemoryOptions {
    namespace: "conversations".into(),
    query: "pricing plans".into(),
    limit: Some(5),
    threshold: None,
    filter: None,
}).unwrap();

Sessions (Durable Execution)

Durable execution sessions for AI agents — pause/resume, event sourcing, and human-in-the-loop approvals.

use cencori::{Cencori, types::CreateSessionParams};

let cencori = Cencori::new(Some("your-api-key"), None, None).unwrap();

// Create a session
let session = cencori.sessions.create(&CreateSessionParams {
    agent_id: Some("ag_...".into()),
    metadata: None,
}).unwrap();
println!("Session: {}", session.id);

// List sessions
use cencori::types::SessionListParams;
let sessions = cencori.sessions.list(&SessionListParams {
    page: None,
    limit: None,
    status: Some("active".into()),
    agent_id: None,
}).unwrap();
println!("Total: {}", sessions.pagination.total);

// Get a session
let session = cencori.sessions.get("sess_123").unwrap();
println!("Status: {}, Turns: {}", session.status, session.turn_count);

// Submit a turn (returns raw SSE stream)
use cencori::types::TurnParams;
use serde_json::json;
let stream = cencori.sessions.submit_turn("sess_123", &TurnParams {
    input: json!("What is the weather in San Francisco?"),
    tools: None,
    instructions: None,
    agent_id: None,
    model: None,
    temperature: None,
    max_output_tokens: None,
    tool_choice: None,
    response_format: None,
    user: None,
    pause_on_tool_calls: None,
    stream: None,
}).unwrap();
// Read SSE events from stream.bytes() or stream.text()

// Get events
use cencori::types::PaginatedSessionEventsResponse;
let events: PaginatedSessionEventsResponse = cencori.sessions.get_events(
    "sess_123", None, None, None,
).unwrap();
println!("Events: {}", events.data.len());

// Approve a pending action (returns raw SSE stream)
use cencori::types::ApproveRejectParams;
let stream = cencori.sessions.approve("sess_123", &ApproveRejectParams {
    action_id: "act_...".into(),
    tool_results: None,
}).unwrap();

// Reject a pending action
let result = cencori.sessions.reject("sess_123", &ApproveRejectParams {
    action_id: "act_...".into(),
    tool_results: None,
}).unwrap();
println!("Resolution: {}", result.resolution);

// Delete a session
cencori.sessions.delete("sess_123").unwrap();

Telemetry

use cencori::Cencori;
use cencori::types::WebTelemetryPayload;

let cencori = Cencori::new(Some("your-api-key"), None, None).unwrap();

cencori.telemetry.report_web_request(WebTelemetryPayload {
    host: "my-app.example.com".into(),
    method: "GET".into(),
    path: "/api/chat".into(),
    status_code: 200,
    request_id: None,
    query_string: None,
    message: None,
    user_agent: None,
    referer: None,
    ip_address: None,
    country_code: None,
    latency_ms: None,
});

Client Configuration

use cencori::Cencori;
use std::collections::HashMap;

// Full configuration with custom headers
let mut headers = HashMap::new();
headers.insert("X-Custom-Header".into(), "value".into());

let cencori = Cencori::new_with_config(
    Some("your-api-key"),
    Some("https://api.cencori.com"),
    Some(headers),
    Some(60.0),
).unwrap();

Project Management

use cencori::{Cencori, types::CreateProjectParams};

let cencori = Cencori::new(Some("your-api-key"), None, None).unwrap();

// List projects
let projects = cencori.projects.list("my-org").unwrap();

// Create project
let project = cencori.projects.create(
    "my-org",
    &CreateProjectParams::new("New Project")
        .with_visibility("private"),
).unwrap();

API Key Management

use cencori::{Cencori, types::CreateAPIKeyParams};

let cencori = Cencori::new(Some("your-api-key"), None, None).unwrap();

// Create API key
let key = cencori.api_keys.create(
    "proj_123",
    &CreateAPIKeyParams {
        name: "Dev Key".into(),
        environment: "dev".into(),
    },
).unwrap();
println!("Secret Key: {:?}", key.key); // Only shown once!

// Get key stats
let stats = cencori.api_keys.get_stats("proj_123", &key.id).unwrap();

Metrics & Analytics

use cencori::Cencori;

let cencori = Cencori::new(Some("your-api-key"), None, None).unwrap();

// Get usage metrics for last 24 hours
let metrics = cencori.metrics.get("24h").unwrap();

println!("Total Requests: {}", metrics.requests.total);
println!("Total Cost: ${}", metrics.cost.total_usd);

Error Handling

use cencori::{Cencori, CencoriError, types::Message};

let cencori = Cencori::new(Some("your-api-key"), None, None).unwrap();

match cencori.ai.chat(
    vec![Message::user("Hello!")],
    None, None, None, None,
) {
    Ok(response) => println!("{}", response.content),
    Err(CencoriError::Authentication) => println!("Invalid API key"),
    Err(CencoriError::RateLimit) => println!("Too many requests"),
    Err(CencoriError::Safety { reasons }) => println!("Content blocked: {:?}", reasons),
    Err(e) => println!("Error: {}", e),
}

Supported Models

Provider Models
OpenAI gpt-4o, gpt-4-turbo, gpt-3.5-turbo
Anthropic claude-3-opus, claude-3-sonnet, claude-3-haiku
Google gemini-2.5-flash, gemini-2.0-flash

Contributing

See CONTRIBUTING.md for development setup, workflow, and guidelines.

License

MIT © FohnAI