Skip to main content

ClaudeOutput

Enum ClaudeOutput 

Source
pub enum ClaudeOutput {
    System(SystemMessage),
    User(UserMessage),
    Assistant(AssistantMessage),
    Result(ResultMessage),
    ControlRequest(ControlRequest),
    ControlResponse(ControlResponse),
    Error(AnthropicError),
    RateLimitEvent(RateLimitEvent),
}
Expand description

Top-level enum for all possible Claude output messages

Variants§

§

System(SystemMessage)

System initialization message

§

User(UserMessage)

User message echoed back

§

Assistant(AssistantMessage)

Assistant response

§

Result(ResultMessage)

Result message (completion of a query)

§

ControlRequest(ControlRequest)

Control request from CLI (tool permissions, hooks, etc.)

§

ControlResponse(ControlResponse)

Control response from CLI (ack for initialization, etc.)

§

Error(AnthropicError)

API error from Anthropic (500, 529 overloaded, etc.)

§

RateLimitEvent(RateLimitEvent)

Rate limit status event

Implementations§

Source§

impl ClaudeOutput

Source

pub fn message_type(&self) -> String

Get the message type as a string

Source

pub fn is_control_request(&self) -> bool

Check if this is a control request (tool permission request)

Source

pub fn is_control_response(&self) -> bool

Check if this is a control response

Source

pub fn is_api_error(&self) -> bool

Check if this is an Anthropic API error

Source

pub fn as_control_request(&self) -> Option<&ControlRequest>

Get the control request if this is one

Source

pub fn as_anthropic_error(&self) -> Option<&AnthropicError>

Get the Anthropic error if this is one

§Example
use claude_codes::ClaudeOutput;

let json = r#"{"type":"error","error":{"type":"overloaded_error","message":"Overloaded"}}"#;
let output: ClaudeOutput = serde_json::from_str(json).unwrap();

if let Some(err) = output.as_anthropic_error() {
    if err.is_overloaded() {
        println!("API is overloaded, retrying...");
    }
}
Source

pub fn is_rate_limit_event(&self) -> bool

Check if this is a rate limit event

Source

pub fn as_rate_limit_event(&self) -> Option<&RateLimitEvent>

Get the rate limit event if this is one

Source

pub fn is_error(&self) -> bool

Check if this is a result with error

Source

pub fn is_assistant_message(&self) -> bool

Check if this is an assistant message

Source

pub fn is_system_message(&self) -> bool

Check if this is a system message

Source

pub fn is_system_init(&self) -> bool

Check if this is a system init message

§Example
use claude_codes::ClaudeOutput;

let json = r#"{"type":"system","subtype":"init","session_id":"abc"}"#;
let output: ClaudeOutput = serde_json::from_str(json).unwrap();
assert!(output.is_system_init());
Source

pub fn session_id(&self) -> Option<&str>

Get the session ID from any message type that has one.

Returns the session ID from System, Assistant, or Result messages. Returns None for User, ControlRequest, and ControlResponse messages.

§Example
use claude_codes::ClaudeOutput;

let json = r#"{"type":"result","subtype":"success","is_error":false,
    "duration_ms":100,"duration_api_ms":200,"num_turns":1,
    "session_id":"my-session","total_cost_usd":0.01}"#;
let output: ClaudeOutput = serde_json::from_str(json).unwrap();
assert_eq!(output.session_id(), Some("my-session"));
Source

pub fn as_tool_use(&self, tool_name: &str) -> Option<&ToolUseBlock>

Get a specific tool use by name from an assistant message.

Returns the first ToolUseBlock with the given name, or None if this is not an assistant message or doesn’t contain the specified tool.

§Example
use claude_codes::ClaudeOutput;

let json = r#"{"type":"assistant","message":{"id":"msg_1","role":"assistant",
    "model":"claude-3","content":[{"type":"tool_use","id":"tu_1",
    "name":"Bash","input":{"command":"ls"}}]},"session_id":"abc"}"#;
let output: ClaudeOutput = serde_json::from_str(json).unwrap();

if let Some(bash) = output.as_tool_use("Bash") {
    assert_eq!(bash.name, "Bash");
}
Source

pub fn tool_uses(&self) -> impl Iterator<Item = &ToolUseBlock>

Get all tool uses from an assistant message.

Returns an iterator over all ToolUseBlocks in the message, or an empty iterator if this is not an assistant message.

§Example
use claude_codes::ClaudeOutput;

let json = r#"{"type":"assistant","message":{"id":"msg_1","role":"assistant",
    "model":"claude-3","content":[
        {"type":"tool_use","id":"tu_1","name":"Read","input":{"file_path":"/tmp/a"}},
        {"type":"tool_use","id":"tu_2","name":"Write","input":{"file_path":"/tmp/b","content":"x"}}
    ]},"session_id":"abc"}"#;
let output: ClaudeOutput = serde_json::from_str(json).unwrap();

let tools: Vec<_> = output.tool_uses().collect();
assert_eq!(tools.len(), 2);
Source

pub fn text_content(&self) -> Option<String>

Get text content from an assistant message.

Returns the concatenated text from all text blocks in the message, or None if this is not an assistant message or has no text content.

§Example
use claude_codes::ClaudeOutput;

let json = r#"{"type":"assistant","message":{"id":"msg_1","role":"assistant",
    "model":"claude-3","content":[{"type":"text","text":"Hello, world!"}]},
    "session_id":"abc"}"#;
let output: ClaudeOutput = serde_json::from_str(json).unwrap();
assert_eq!(output.text_content(), Some("Hello, world!".to_string()));
Source

pub fn as_assistant(&self) -> Option<&AssistantMessage>

Get the assistant message if this is one.

§Example
use claude_codes::ClaudeOutput;

let json = r#"{"type":"assistant","message":{"id":"msg_1","role":"assistant",
    "model":"claude-3","content":[]},"session_id":"abc"}"#;
let output: ClaudeOutput = serde_json::from_str(json).unwrap();

if let Some(assistant) = output.as_assistant() {
    assert_eq!(assistant.message.model, "claude-3");
}
Source

pub fn as_result(&self) -> Option<&ResultMessage>

Get the result message if this is one.

§Example
use claude_codes::ClaudeOutput;

let json = r#"{"type":"result","subtype":"success","is_error":false,
    "duration_ms":100,"duration_api_ms":200,"num_turns":1,
    "session_id":"abc","total_cost_usd":0.01}"#;
let output: ClaudeOutput = serde_json::from_str(json).unwrap();

if let Some(result) = output.as_result() {
    assert!(!result.is_error);
}
Source

pub fn as_system(&self) -> Option<&SystemMessage>

Get the system message if this is one.

Source

pub fn parse_json_tolerant(s: &str) -> Result<ClaudeOutput, ParseError>

Parse a JSON string, handling potential ANSI escape codes and other prefixes This method will:

  1. First try to parse as-is
  2. If that fails, trim until it finds a ‘{’ and try again
Source

pub fn parse_json(s: &str) -> Result<ClaudeOutput, ParseError>

Parse a JSON string, returning ParseError with raw JSON if it doesn’t match our types

Trait Implementations§

Source§

impl Clone for ClaudeOutput

Source§

fn clone(&self) -> ClaudeOutput

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for ClaudeOutput

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de> Deserialize<'de> for ClaudeOutput

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Serialize for ClaudeOutput

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,