Skip to main content

Crate aither_core

Crate aither_core 

Source
Expand description

Β§aither

Write AI applications that work with any provider πŸš€

aither-core hosts the no-std trait APIs that power the rest of the workspace. Use it directly (or through the top-level aither crate) to describe portable language models, embeddings, moderation, image/audio generators, and more. Every provider crate simply implements these traits.

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   Your App      │───▢│    aither        │◀───│   Providers     β”‚
β”‚                 β”‚    β”‚   (this crate)   β”‚    β”‚                 β”‚
β”‚ - Chat bots     β”‚    β”‚                  β”‚    β”‚ - openai        β”‚
β”‚ - Search        β”‚    β”‚ - LanguageModel  β”‚    β”‚ - anthropic     β”‚
β”‚ - Content gen   β”‚    β”‚ - EmbeddingModel β”‚    β”‚ - llama.cpp     β”‚
β”‚ - Voice apps    β”‚    β”‚ - ImageGenerator β”‚    β”‚ - whisper       β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Β§Supported AI Capabilities

CapabilityTraitDescription
Language ModelsLanguageModelStreaming events (text, reasoning, tool calls)
EmbeddingsEmbeddingModelConvert text to vectors for semantic search
Image GenerationImageGeneratorCreate images with progressive quality improvement
Text-to-SpeechAudioGeneratorGenerate speech audio from text
Speech-to-TextAudioTranscriberTranscribe audio to text
Content ModerationModerationDetect policy violations with confidence scores

Β§Examples

Β§Streaming Responses with Events

β“˜
use aither_core::llm::{LanguageModel, Event, Message, LLMRequest, model::Parameters};
use futures_lite::StreamExt;

async fn event_demo(model: impl LanguageModel) -> aither_core::Result {
    let request = LLMRequest::new([
        Message::user("Explain how rainbows form like I'm five."),
    ])
    .with_parameters(Parameters::default().include_reasoning(true));

    let mut stream = model.respond(request);
    let mut answer = String::new();

    while let Some(event) = stream.next().await {
        match event? {
            Event::Text(text) => answer.push_str(&text),
            Event::Reasoning(thought) => println!("thinking: {}", thought),
            Event::ToolCall(call) => println!("tool requested: {}", call.name),
            _ => {}
        }
    }
    Ok(answer)
}

Β§Structured Output with Tools

use aither_core::llm::{LLMRequest, Message, Tool, ToolContext, ToolResult};
use schemars::JsonSchema;
use serde::Deserialize;
use std::borrow::Cow;

/// Get current weather for a location.
#[derive(JsonSchema, Deserialize)]
struct WeatherQuery {
    /// City to report on, e.g. "Tokyo".
    location: String,
}

struct WeatherTool;

impl Tool for WeatherTool {
    fn name(&self) -> Cow<'static, str> {
        Cow::Borrowed("get_weather")
    }

    type Arguments = WeatherQuery;
    type Res = ToolResult;

    async fn call(
        &self,
        args: Self::Arguments,
        _cx: ToolContext,
    ) -> aither_core::Result<Self::Res> {
        Ok(ToolResult::text(format!("Weather in {}: 22Β°C, sunny", args.location)))
    }
}

// Advertise the tool on a request. The model replies with a ToolCall event;
// executing it is up to the caller (see `aither-agent`).
let request = LLMRequest::new([Message::user("What is the weather in Tokyo?")])
    .with_tool(&WeatherTool);

See llm::tool for more details on using tools with language models.

Β§Semantic Search with Embeddings

use aither_core::EmbeddingModel;

async fn embed_query(
    model: impl EmbeddingModel,
    query: &str,
) -> aither_core::Result<Vec<f32>> {
    // Compare this against your stored document embeddings with cosine
    // similarity, or hand it to `aither-rag`.
    model.embed(query).await
}

Β§Progressive Image Generation

β“˜
use aither_core::{ImageGenerator, image::{Prompt, Size}};
use futures_lite::StreamExt;

async fn generate_image(generator: impl ImageGenerator) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
    let prompt = Prompt::new("A beautiful sunset over mountains");
    let size = Size::square(1024);
     
    let mut image_stream = generator.create(prompt, size);
    let mut final_image = Vec::new();
     
    // Each iteration gives us a complete image with progressively better quality
    while let Some(image_result) = image_stream.next().await {
        let current_image = image_result?;
        final_image = current_image; // Keep the latest (highest quality) version
         
        // Optional: Display preview of current quality level
        println!("Received image update, {} bytes", final_image.len());
    }
     
    Ok(final_image) // Return the final highest-quality image
}

Β§Modules

  • audio β€” text-to-speech and transcription traits.
  • embedding β€” turn text into dense vectors.
  • image β€” image generation + editing APIs.
  • llm β€” request builders, messages, provider traits, reasoning streams.
  • moderation β€” moderation scoring traits.

ModulesΒ§

audio
Audio generation and transcription.
embedding
Text embeddings.
ids
Model-facing ids: the words a model reads and types back to name what it can address, such as a background job, a stored output or a finished subagent.
image
Text-to-image generation.
llm
Language Models and Conversation Management
moderation
Content moderation utilities.

StructsΒ§

AnyIdAllocator
A shared IdAllocator.
Error
The Error type, a wrapper around a dynamic error type.
IdLease
A word leased from an AnyIdAllocator.
IdsExhausted
Every word an IdAllocator can hand out is leased.
WeakIdLease
A reference to an IdLease that does not keep its word leased, for what must still tell whether the word names the same thing later.
WordAllocator
An IdAllocator over a fixed list of words.

EnumsΒ§

TokenCounting
How a model can count the tokens a request costs, when it can.

TraitsΒ§

AudioGenerator
Generates audio from text prompts.
AudioTranscriber
Transcribes audio to text.
EmbeddingModel
Converts text to vector representations.
IdAllocator
Hands out the words that name what a model can address.
ImageGenerator
Trait for generating and editing images from prompts and masks.
LanguageModel
Language models for text generation and conversation.
Moderation
Trait for content moderation services.

Type AliasesΒ§

Result
Result type used throughout the crate.

Attribute MacrosΒ§

tool
Converts an async function into an AI tool that can be called by language models.