Skip to main content

Crate llm_content_blocks

Crate llm_content_blocks 

Source
Expand description

§llm-content-blocks

Typed fluent builder for Anthropic Messages-API content blocks.

The Anthropic Messages API takes a list of content blocks per message: text, image, tool_use, tool_result, document. The shapes are simple but fiddly, especially when you stitch them together programmatically. Blocks is a fluent builder that emits the exact JSON shape the API expects, with no SDK dependency.

§Serialization approach

Variants of ContentBlock derive serde::Serialize with #[serde(tag = "type", rename_all = "snake_case")]. This puts the "type": "..." discriminator alongside the variant fields, which is exactly the dict shape Anthropic expects. cache_control and is_error are skipped when absent / false so the produced JSON is byte-equivalent to the Python reference library’s output.

§Quick example

use llm_content_blocks::Blocks;

let mut b = Blocks::new();
b.text("Look at this:")
    .image_b64(b"\x89PNG", "image/png").unwrap()
    .text("What is it?");
let content = b.build();

assert_eq!(content.len(), 3);

§Wrap as a full message

use llm_content_blocks::Blocks;

let mut b = Blocks::new();
b.text("Hi");
let msg = b.build_message("user");
assert_eq!(msg.role, "user");
assert_eq!(msg.content.len(), 1);

§One-shot tool result

use llm_content_blocks::Blocks;
use serde_json::json;

let block = Blocks::tool_result_block("toolu_1", json!("the answer"), false);

Structs§

Blocks
Fluent builder for a list of Anthropic content blocks.
Message
A full {role, content} message envelope.

Enums§

BlockError
Errors returned by builder methods that validate input up front.
CacheControl
Cache-control marker for a single content block.
ContentBlock
One entry in the content array of an Anthropic message.
DocumentSource
Source for a document content block.
ImageSource
Source for an image content block.

Constants§

VALID_DOCUMENT_MEDIA_TYPES
Document media types accepted by the Anthropic Messages API.
VALID_IMAGE_MEDIA_TYPES
Image media types accepted by the Anthropic Messages API.