Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

10.8 KB
Raw Blame
use crate::tool_result_limit::ToolResultLimit;
/// Conversions between agent message types and `rig` message types.
use crate::types::{AssistantMessagePart, ChatMessage, ChatMessageContent, Role};
use attachment::image::ImageData;
use attachment::{AttachmentContent, AttachmentPart, Attachments};
use rig_core::OneOrMany;
use rig_core::message::{
    AssistantContent, ImageMediaType, Message, ToolCall, ToolFunction, ToolResultContent,
    UserContent,
};

/// Conversion of an attachment value into RIG user-content blocks.
///
/// Implemented for the attachment tree types so a user message's resolved
/// attachments can be flattened into the [`UserContent`] blocks RIG sends to
/// the model. Foreign-type orphan rules rule out a `From` impl, so this local
/// trait carries the conversions instead.
trait ToUserContent {
    /// Convert `self` into zero or more RIG user-content blocks.
    fn to_user_content(&self) -> Vec<UserContent>;
}

impl ToUserContent for Attachments<'_> {
    fn to_user_content(&self) -> Vec<UserContent> {
        // Failed resolutions carry no content useful to the model; skip them.
        self.parts()
            .iter()
            .filter_map(|resolved| resolved.as_ref().ok())
            .flat_map(ToUserContent::to_user_content)
            .collect()
    }
}

impl ToUserContent for AttachmentContent<'_> {
    fn to_user_content(&self) -> Vec<UserContent> {
        self.content
            .iter()
            .flat_map(ToUserContent::to_user_content)
            .collect()
    }
}

impl ToUserContent for AttachmentPart<'_> {
    fn to_user_content(&self) -> Vec<UserContent> {
        match self {
            Self::Content(text) => vec![UserContent::text(text.clone())],
            Self::Image(image) => image.to_user_content(),
            Self::Metadata { key, value } => vec![UserContent::text(format!("{key}: {value}"))],
            // Errors, child references, and resolved children are not
            // represented as inline model content here.
            Self::ImageError(_) | Self::Child(_) | Self::ChildReference(_) => vec![],
        }
    }
}

impl ToUserContent for ImageData {
    fn to_user_content(&self) -> Vec<UserContent> {
        let content = match self {
            // `Base64Image` is always a downscaled WebP by construction.
            Self::Base64(image) => UserContent::image_base64(
                image.base64_data().to_owned(),
                Some(ImageMediaType::WEBP),
                None,
            ),
            Self::StaticUrl(url) => UserContent::image_url(url.clone(), None, None),
        };
        vec![content]
    }
}

/// Convert a slice of [`ChatMessage`] into RIG [`Message`]s.
///
/// System messages are skipped (the system prompt is set on the agent).
///
/// A single persisted assistant message may contain a flattened multi-turn
/// tool loop: `[text, tool_calls, tool_results, text]`. This function
/// reconstructs the turn boundaries Anthropic expects:
/// `assistant(text + tool_calls)`, `user(tool_results)`, `assistant(text)`.
pub fn to_rig_messages(messages: &[ChatMessage]) -> Vec<Message> {
    messages
        .iter()
        .flat_map(|msg| convert_one(msg, None))
        .collect()
}

/// [`to_rig_messages`], with each tool result too long for the model cut as
/// `limit` cut it when it arrived, so it reads the same in every turn.
pub fn to_rig_messages_limited(messages: &[ChatMessage], limit: &ToolResultLimit) -> Vec<Message> {
    messages
        .iter()
        .flat_map(|msg| convert_one(msg, Some(limit)))
        .collect()
}

fn convert_one(msg: &ChatMessage, limit: Option<&ToolResultLimit>) -> Vec<Message> {
    match msg.role {
        Role::System => vec![],
        Role::User => convert_user(msg),
        Role::Assistant => convert_assistant(msg, limit),
    }
}

/// Convert a user message into a single RIG [`Message::User`].
///
/// The message text becomes a leading [`UserContent::Text`] block (when
/// non-empty) and any resolved [`attachments`](ChatMessage::attachments) are
/// appended as additional text and image content blocks. Without this, image
/// attachments would never reach the model.
fn convert_user(msg: &ChatMessage) -> Vec<Message> {
    let mut content: Vec<UserContent> = Vec::new();

    let text = msg.content.message_text();
    if !text.is_empty() {
        content.push(UserContent::text(text));
    }

    if let Some(attachments) = &msg.attachments {
        content.extend(attachments.to_user_content());
    }

    // A user turn must contain at least one content block.
    if content.is_empty() {
        content.push(UserContent::text(String::new()));
    }

    match OneOrMany::many(content) {
        Ok(content) => vec![Message::User { content }],
        Err(_) => vec![Message::user(msg.content.message_text())],
    }
}

fn convert_assistant(msg: &ChatMessage, limit: Option<&ToolResultLimit>) -> Vec<Message> {
    let parts = match &msg.content {
        ChatMessageContent::Text(text) => {
            return vec![Message::assistant(text)];
        }
        ChatMessageContent::AssistantMessageParts(parts) => parts,
    };

    let mut out: Vec<Message> = Vec::new();
    let mut assistant_parts: Vec<AssistantContent> = Vec::new();
    let mut tool_results: Vec<UserContent> = Vec::new();
    let mut saw_tool_call = false;

    for part in parts {
        match part {
            AssistantMessagePart::Text { text } => {
                if saw_tool_call {
                    flush(&mut out, &mut assistant_parts, &mut tool_results);
                    saw_tool_call = false;
                }
                if let Some(AssistantContent::Text(prev)) = assistant_parts.last_mut() {
                    prev.text.push_str(text);
                } else {
                    assistant_parts.push(AssistantContent::text(text));
                }
            }
            AssistantMessagePart::ToolCall { name, json, id }
            | AssistantMessagePart::McpToolCall { name, json, id, .. } => {
                saw_tool_call = true;
                // Anthropic requires tool_use.input to be an object; older persisted
                // messages may carry a non-object value from before this was enforced
                // at the source (see hook.rs on_tool_call), so coerce here too.
                let input = if json.is_object() {
                    json.clone()
                } else {
                    serde_json::json!({})
                };
                assistant_parts.push(AssistantContent::ToolCall(
                    ToolCall::new(replay_item_id(id), ToolFunction::new(name.clone(), input))
                        .with_call_id(replay_call_id(id)),
                ));
            }
            AssistantMessagePart::ToolCallResponseJson { id, json, .. } => {
                let content = if json.get("modelMedia").is_some() {
                    crate::tool_media::model_output(json.clone())
                        .map(|output| output.into_content())
                        .unwrap_or_else(|_| {
                            OneOrMany::one(ToolResultContent::text(
                                "Tool image could not be replayed. Render the canvas again.",
                            ))
                        })
                } else {
                    let text = serde_json::to_string(json).unwrap_or_default();
                    OneOrMany::one(ToolResultContent::text(model_view(limit, id, text)))
                };
                tool_results.push(UserContent::tool_result_with_call_id(
                    replay_item_id(id),
                    replay_call_id(id),
                    content,
                ));
            }
            AssistantMessagePart::ToolCallErr {
                id, description, ..
            } => {
                tool_results.push(UserContent::tool_result_with_call_id(
                    replay_item_id(id),
                    replay_call_id(id),
                    OneOrMany::one(ToolResultContent::text(model_view(
                        limit,
                        id,
                        description.clone(),
                    ))),
                ));
            }
            AssistantMessagePart::Thinking { .. } => {}
        }
    }

    flush(&mut out, &mut assistant_parts, &mut tool_results);
    out
}

/// What the model reads of a replayed tool result: `text` itself, unless
/// `limit` cuts it.
fn model_view(limit: Option<&ToolResultLimit>, id: &str, text: String) -> String {
    limit
        .and_then(|limit| limit.view(id, &text))
        .unwrap_or(text)
}

/// `call_id` replayed to the provider for a persisted tool call or result.
///
/// The persisted id is the provider call id (or a streamed item's `fc_…`
/// id), falling back to rig's correlation id when no provider id is available. OpenAI's Responses API pairs a
/// call to its result through `call_id` and rejects ids ending in a separator,
/// and a nanoid can end in `_` or `-` — so trim the trailing separator(s). A
/// call and its result both run through this with the same `id`, so trimming
/// keeps them paired. Anthropic ignores `call_id`.
fn replay_call_id(id: &str) -> String {
    id.trim_end_matches(['_', '-']).to_owned()
}

/// `function_call` item id replayed to the provider for a persisted tool call
/// or result.
///
/// OpenAI's Responses API rejects replayed item ids that don't begin with `fc`
/// (and, like `call_id`, ones ending in a separator — hence [`replay_call_id`]).
/// Anthropic ignores `call_id` and only requires a result's item id to match
/// its call's, which this uniform prefix-over-trimmed-id preserves.
fn replay_item_id(id: &str) -> String {
    format!("fc_{}", replay_call_id(id))
}

/// Merges consecutive `Text` and `Thinking` parts into single entries.
pub fn merge_consecutive_parts(parts: Vec<AssistantMessagePart>) -> Vec<AssistantMessagePart> {
    let mut out: Vec<AssistantMessagePart> = Vec::with_capacity(parts.len());
    for part in parts {
        match (&mut out.last_mut(), &part) {
            (
                Some(AssistantMessagePart::Text { text: acc }),
                AssistantMessagePart::Text { text },
            ) => {
                acc.push_str(text);
            }
            (
                Some(AssistantMessagePart::Thinking { thinking: acc }),
                AssistantMessagePart::Thinking { thinking },
            ) => {
                acc.push_str(thinking);
            }
            _ => out.push(part),
        }
    }
    out
}

fn flush(
    out: &mut Vec<Message>,
    assistant_parts: &mut Vec<AssistantContent>,
    tool_results: &mut Vec<UserContent>,
) {
    if !assistant_parts.is_empty() {
        let parts = std::mem::take(assistant_parts);
        if let Ok(content) = OneOrMany::many(parts) {
            out.push(Message::Assistant { id: None, content });
        }
    }
    if !tool_results.is_empty() {
        let results = std::mem::take(tool_results);
        if let Ok(content) = OneOrMany::many(results) {
            out.push(Message::User { content });
        }
    }
}