dsir 0.1.1

DSPy-shaped library for programming language models in Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
use anyhow::Result;

use serde::{Deserialize, Serialize};
use serde_json::{Value, json};

use rig::OneOrMany;
use rig::message::{
    AssistantContent, Message as RigMessage, Reasoning, ToolCall, ToolResult, ToolResultContent,
    UserContent,
};

// ---------------------------------------------------------------------------
// ContentBlock — one piece of content within a message
// ---------------------------------------------------------------------------

#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum ContentBlock {
    Text { text: String },
    ToolCall { tool_call: ToolCall },
    ToolResult { tool_result: ToolResult },
    Reasoning { reasoning: Reasoning },
}

impl ContentBlock {
    pub fn text(t: impl Into<String>) -> Self {
        ContentBlock::Text { text: t.into() }
    }

    pub fn tool_call(tc: ToolCall) -> Self {
        ContentBlock::ToolCall { tool_call: tc }
    }

    pub fn tool_result(tr: ToolResult) -> Self {
        ContentBlock::ToolResult { tool_result: tr }
    }

    pub fn reasoning(r: Reasoning) -> Self {
        ContentBlock::Reasoning { reasoning: r }
    }
}

// ---------------------------------------------------------------------------
// Role
// ---------------------------------------------------------------------------

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Role {
    System,
    User,
    Assistant,
}

impl Role {
    pub fn as_str(&self) -> &'static str {
        match self {
            Role::System => "system",
            Role::User => "user",
            Role::Assistant => "assistant",
        }
    }
}

// ---------------------------------------------------------------------------
// Message — a single turn in a conversation
// ---------------------------------------------------------------------------

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Message {
    pub role: Role,
    pub content: Vec<ContentBlock>,
    /// Provider-assigned message ID (e.g. Anthropic thinking turn IDs).
    #[serde(skip_serializing_if = "Option::is_none", default)]
    pub id: Option<String>,
}

impl Message {
    /// Creates a text-only message from a role string.
    ///
    /// # Panics
    ///
    /// Panics if `role` is not one of `"system"`, `"user"`, or `"assistant"`.
    pub fn new(role: &str, content: &str) -> Self {
        let role = match role {
            "system" => Role::System,
            "user" => Role::User,
            "assistant" => Role::Assistant,
            _ => panic!("Invalid role: {role}"),
        };
        Self {
            role,
            content: vec![ContentBlock::text(content)],
            id: None,
        }
    }

    pub fn user(content: impl Into<String>) -> Self {
        Self {
            role: Role::User,
            content: vec![ContentBlock::text(content)],
            id: None,
        }
    }

    pub fn assistant(content: impl Into<String>) -> Self {
        Self {
            role: Role::Assistant,
            content: vec![ContentBlock::text(content)],
            id: None,
        }
    }

    pub fn system(content: impl Into<String>) -> Self {
        Self {
            role: Role::System,
            content: vec![ContentBlock::text(content)],
            id: None,
        }
    }

    /// Creates an assistant message containing a single tool call.
    pub fn tool_call(tool_call: ToolCall) -> Self {
        Self {
            role: Role::Assistant,
            content: vec![ContentBlock::tool_call(tool_call)],
            id: None,
        }
    }

    /// Creates a user message containing a single tool result.
    pub fn tool_result(tool_result: ToolResult) -> Self {
        Self {
            role: Role::User,
            content: vec![ContentBlock::tool_result(tool_result)],
            id: None,
        }
    }

    /// Creates an assistant message containing a single reasoning block.
    pub fn reasoning(reasoning: Reasoning) -> Self {
        Self {
            role: Role::Assistant,
            content: vec![ContentBlock::reasoning(reasoning)],
            id: None,
        }
    }

    /// Creates a message with arbitrary content blocks.
    pub fn with_content(role: Role, content: Vec<ContentBlock>) -> Self {
        Self {
            role,
            content,
            id: None,
        }
    }

    // -- Accessors -----------------------------------------------------------

    /// Returns a string representation of the message's content.
    ///
    /// For text-only messages, returns the text. For multi-content messages,
    /// returns all blocks formatted and joined with newlines.
    pub fn content(&self) -> String {
        let parts: Vec<String> = self
            .content
            .iter()
            .map(|block| match block {
                ContentBlock::Text { text } => text.clone(),
                ContentBlock::ToolCall { tool_call } => {
                    format!(
                        "{}({})",
                        tool_call.function.name, tool_call.function.arguments
                    )
                }
                ContentBlock::ToolResult { tool_result } => tool_result
                    .content
                    .iter()
                    .filter_map(|item| match item {
                        ToolResultContent::Text(text) => Some(text.text.as_str()),
                        ToolResultContent::Image(_) => None,
                    })
                    .collect::<Vec<_>>()
                    .join("\n"),
                ContentBlock::Reasoning { reasoning } => reasoning.display_text(),
            })
            .collect();
        parts.join("\n")
    }

    /// Returns only the text content, ignoring tool calls, tool results,
    /// and reasoning blocks. Used by the parser to extract structured output.
    pub fn text_content(&self) -> String {
        self.content
            .iter()
            .filter_map(|block| match block {
                ContentBlock::Text { text } => Some(text.as_str()),
                _ => None,
            })
            .collect::<Vec<_>>()
            .join("\n")
    }

    // -- Content query helpers -----------------------------------------------

    /// Returns `true` if this message contains at least one tool call.
    pub fn has_tool_calls(&self) -> bool {
        self.content
            .iter()
            .any(|b| matches!(b, ContentBlock::ToolCall { .. }))
    }

    /// Returns `true` if this message contains at least one tool result.
    pub fn has_tool_results(&self) -> bool {
        self.content
            .iter()
            .any(|b| matches!(b, ContentBlock::ToolResult { .. }))
    }

    /// Returns `true` if this message contains at least one reasoning block.
    pub fn has_reasoning(&self) -> bool {
        self.content
            .iter()
            .any(|b| matches!(b, ContentBlock::Reasoning { .. }))
    }

    /// Extracts all tool calls from this message.
    pub fn tool_calls(&self) -> Vec<&ToolCall> {
        self.content
            .iter()
            .filter_map(|b| match b {
                ContentBlock::ToolCall { tool_call } => Some(tool_call),
                _ => None,
            })
            .collect()
    }

    // -- Rig conversion ------------------------------------------------------

    /// Converts this message to a rig message for provider API calls.
    ///
    /// Returns `None` for system messages (rig handles them as preamble).
    pub fn to_rig_message(&self) -> Option<RigMessage> {
        match self.role {
            Role::System => None,
            Role::User => {
                let user_content: Vec<UserContent> = self
                    .content
                    .iter()
                    .filter_map(|block| match block {
                        ContentBlock::Text { text } => Some(UserContent::text(text.clone())),
                        ContentBlock::ToolResult { tool_result } => {
                            Some(UserContent::ToolResult(tool_result.clone()))
                        }
                        // ToolCall/Reasoning don't belong in user messages; skip gracefully
                        _ => None,
                    })
                    .collect();
                if user_content.is_empty() {
                    return Some(RigMessage::user(String::new()));
                }
                Some(RigMessage::User {
                    content: OneOrMany::many(user_content)
                        .unwrap_or_else(|_| OneOrMany::one(UserContent::text(String::new()))),
                })
            }
            Role::Assistant => {
                let asst_content: Vec<AssistantContent> = self
                    .content
                    .iter()
                    .filter_map(|block| match block {
                        ContentBlock::Text { text } => Some(AssistantContent::text(text.clone())),
                        ContentBlock::ToolCall { tool_call } => {
                            Some(AssistantContent::ToolCall(tool_call.clone()))
                        }
                        ContentBlock::Reasoning { reasoning } => {
                            Some(AssistantContent::Reasoning(reasoning.clone()))
                        }
                        // ToolResult doesn't belong in assistant messages; skip gracefully
                        _ => None,
                    })
                    .collect();
                if asst_content.is_empty() {
                    return Some(RigMessage::assistant(String::new()));
                }
                Some(RigMessage::Assistant {
                    id: self.id.clone(),
                    content: OneOrMany::many(asst_content)
                        .unwrap_or_else(|_| OneOrMany::one(AssistantContent::text(String::new()))),
                })
            }
        }
    }

    // -- JSON serialization --------------------------------------------------

    pub fn to_json(&self) -> Value {
        let content_json: Vec<Value> = self
            .content
            .iter()
            .map(|block| match block {
                ContentBlock::Text { text } => json!({ "type": "text", "text": text }),
                ContentBlock::ToolCall { tool_call } => {
                    json!({ "type": "tool_call", "tool_call": tool_call })
                }
                ContentBlock::ToolResult { tool_result } => {
                    json!({ "type": "tool_result", "tool_result": tool_result })
                }
                ContentBlock::Reasoning { reasoning } => {
                    json!({ "type": "reasoning", "reasoning": reasoning })
                }
            })
            .collect();

        let mut msg = json!({
            "role": self.role.as_str(),
            "content": content_json,
        });

        if let Some(id) = &self.id {
            msg.as_object_mut()
                .unwrap()
                .insert("id".to_string(), json!(id));
        }

        msg
    }

    fn from_json_value(message: &Value) -> Result<Self> {
        let role_str = message
            .get("role")
            .and_then(Value::as_str)
            .ok_or_else(|| anyhow::anyhow!("chat message missing string role"))?;

        let role = match role_str {
            "system" => Role::System,
            "user" => Role::User,
            "assistant" => Role::Assistant,
            other => return Err(anyhow::anyhow!("unsupported chat message role: {other}")),
        };

        let id = message.get("id").and_then(Value::as_str).map(String::from);

        let content_val = message.get("content");

        // Support both formats:
        //   New: "content": [{ "type": "text", "text": "..." }, ...]
        //   Legacy: "content": "plain string"
        let content = match content_val {
            Some(Value::Array(arr)) => arr
                .iter()
                .map(parse_content_block)
                .collect::<Result<Vec<_>>>()?,
            Some(Value::String(s)) => vec![ContentBlock::text(s.clone())],
            _ => {
                // Legacy type-tagged format: { "type": "tool_call", "tool_call": {...} }
                match message.get("type").and_then(Value::as_str) {
                    Some("tool_call") => {
                        let tc: ToolCall = serde_json::from_value(message["tool_call"].clone())?;
                        vec![ContentBlock::tool_call(tc)]
                    }
                    Some("tool_result") => {
                        let tr: ToolResult =
                            serde_json::from_value(message["tool_result"].clone())?;
                        vec![ContentBlock::tool_result(tr)]
                    }
                    Some("reasoning") => {
                        let r: Reasoning = serde_json::from_value(message["reasoning"].clone())?;
                        vec![ContentBlock::reasoning(r)]
                    }
                    Some(other) => {
                        return Err(anyhow::anyhow!("unsupported chat message type: {other}"));
                    }
                    None => return Err(anyhow::anyhow!("chat message missing content field")),
                }
            }
        };

        Ok(Self { role, content, id })
    }
}

fn parse_content_block(value: &Value) -> Result<ContentBlock> {
    let block_type = value
        .get("type")
        .and_then(Value::as_str)
        .ok_or_else(|| anyhow::anyhow!("content block missing type"))?;

    match block_type {
        "text" => {
            let text = value
                .get("text")
                .and_then(Value::as_str)
                .ok_or_else(|| anyhow::anyhow!("text block missing text field"))?;
            Ok(ContentBlock::text(text))
        }
        "tool_call" => {
            let tc: ToolCall = serde_json::from_value(value["tool_call"].clone())?;
            Ok(ContentBlock::tool_call(tc))
        }
        "tool_result" => {
            let tr: ToolResult = serde_json::from_value(value["tool_result"].clone())?;
            Ok(ContentBlock::tool_result(tr))
        }
        "reasoning" => {
            let r: Reasoning = serde_json::from_value(value["reasoning"].clone())?;
            Ok(ContentBlock::reasoning(r))
        }
        other => Err(anyhow::anyhow!("unsupported content block type: {other}")),
    }
}

// ---------------------------------------------------------------------------
// From<RigMessage> — lossless conversion, one rig message → one dsir message
// ---------------------------------------------------------------------------

impl From<RigMessage> for Message {
    fn from(message: RigMessage) -> Self {
        match message {
            RigMessage::User { content } => {
                let blocks: Vec<ContentBlock> = content
                    .into_iter()
                    .filter_map(|item| match item {
                        UserContent::Text(text) => Some(ContentBlock::text(text.text)),
                        UserContent::ToolResult(result) => Some(ContentBlock::tool_result(result)),
                        UserContent::Image(_)
                        | UserContent::Audio(_)
                        | UserContent::Video(_)
                        | UserContent::Document(_) => None,
                    })
                    .collect();
                Message {
                    role: Role::User,
                    content: if blocks.is_empty() {
                        vec![ContentBlock::text(String::new())]
                    } else {
                        blocks
                    },
                    id: None,
                }
            }
            RigMessage::Assistant { id, content } => {
                let blocks: Vec<ContentBlock> = content
                    .into_iter()
                    .filter_map(|item| match item {
                        AssistantContent::Text(text) => Some(ContentBlock::text(text.text)),
                        AssistantContent::ToolCall(tc) => Some(ContentBlock::tool_call(tc)),
                        AssistantContent::Reasoning(r) => Some(ContentBlock::reasoning(r)),
                        AssistantContent::Image(_) => None,
                    })
                    .collect();
                Message {
                    role: Role::Assistant,
                    content: if blocks.is_empty() {
                        vec![ContentBlock::text(String::new())]
                    } else {
                        blocks
                    },
                    id,
                }
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Chat — ordered sequence of messages
// ---------------------------------------------------------------------------

#[derive(Clone, Debug)]
pub struct Chat {
    pub messages: Vec<Message>,
}

impl Chat {
    pub fn new(messages: Vec<Message>) -> Self {
        Self { messages }
    }

    pub fn len(&self) -> usize {
        self.messages.len()
    }

    pub fn is_empty(&self) -> bool {
        self.messages.is_empty()
    }

    pub fn push(&mut self, role: &str, content: &str) {
        self.messages.push(Message::new(role, content));
    }

    pub fn push_message(&mut self, message: Message) {
        self.messages.push(message);
    }

    pub fn push_all(&mut self, chat: &Chat) {
        self.messages.extend(chat.messages.clone());
    }

    pub fn pop(&mut self) -> Option<Message> {
        self.messages.pop()
    }

    pub fn from_json(&self, json_dump: Value) -> Result<Self> {
        let messages = json_dump
            .as_array()
            .ok_or_else(|| anyhow::anyhow!("chat dump must be an array"))?;
        let messages = messages
            .iter()
            .map(Message::from_json_value)
            .collect::<Result<Vec<_>>>()?;
        Ok(Self { messages })
    }

    pub fn to_json(&self) -> Value {
        let messages = self
            .messages
            .iter()
            .map(|message| message.to_json())
            .collect::<Vec<Value>>();
        json!(messages)
    }

    // -- Rig interop ---------------------------------------------------------

    /// Extracts the system prompt text from the first system message.
    pub fn system_prompt(&self) -> String {
        self.messages
            .iter()
            .find_map(|message| {
                if message.role == Role::System {
                    Some(message.text_content())
                } else {
                    None
                }
            })
            .unwrap_or_default()
    }

    /// Converts all non-system messages to rig messages for provider API calls.
    pub fn to_rig_chat_history(&self) -> Vec<RigMessage> {
        self.messages
            .iter()
            .filter_map(Message::to_rig_message)
            .collect()
    }
}