reagent-rs 0.2.11

A Rust library for building AI agents with MCP, custom tools and skills
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
use std::{collections::HashMap, marker::PhantomData};

use rmcp::schemars::JsonSchema;
use serde_json::Value;
use tokio::sync::mpsc::Sender;

use crate::{
    services::llm::{
        message::Message,
        models::embedding::{EmbeddingsRequest, EmbeddingsResponse},
        BaseRequest, ClientBuilder, InferenceOptions, ResponseFormatConfig, SchemaSpec,
    },
    Agent, ChatRequest, ChatResponse, ClientConfig, InvocationError, InvocationRequest,
    Notification, Provider, Tool,
};

#[derive(Debug, Clone, Default)]
pub struct ChatMode;

#[derive(Debug, Clone, Default)]
pub struct EmbeddingMode;

pub type InvocationBuilder = TypedInvocationBuilder<ChatMode>;
pub type EmbeddingInvocationBuilder = TypedInvocationBuilder<EmbeddingMode>;

#[derive(Debug, Clone)]
pub struct TypedInvocationBuilder<M = ChatMode> {
    mode: PhantomData<M>,
    model: Option<String>,
    format: Option<Value>,
    stream: Option<bool>,
    keep_alive: Option<String>,
    name: Option<String>,
    messages: Option<Vec<Message>>,
    tools: Option<Vec<Tool>>,
    embedding_input: Option<Vec<String>>,
    opts: InferenceOptions,
    strip_thinking: Option<bool>,
    use_tools: Option<bool>,
    client_config: ClientConfig,
    notification_channel: Option<Sender<Notification>>,
    response_format: ResponseFormatConfig,
}

impl Default for TypedInvocationBuilder<ChatMode> {
    fn default() -> Self {
        Self::new()
    }
}

impl<M> TypedInvocationBuilder<M> {
    fn new() -> Self {
        Self {
            mode: PhantomData,
            model: None,
            format: None,
            stream: None,
            keep_alive: None,
            name: None,
            messages: None,
            tools: None,
            embedding_input: None,
            opts: InferenceOptions::default(),
            strip_thinking: None,
            use_tools: None,
            client_config: ClientConfig::default(),
            notification_channel: None,
            response_format: ResponseFormatConfig::default(),
        }
    }

    pub fn model(mut self, v: impl Into<String>) -> Self {
        self.model = Some(v.into());
        self
    }

    pub fn keep_alive(mut self, v: impl Into<String>) -> Self {
        self.keep_alive = Some(v.into());
        self
    }

    pub fn set_name<T>(mut self, name: T) -> Self
    where
        T: Into<String>,
    {
        self.name = Some(name.into());
        self
    }

    pub fn set_provider(mut self, provider: Provider) -> Self {
        self.client_config = self.client_config.provider(Some(provider));
        self
    }

    pub fn set_base_url(mut self, base_url: impl Into<String>) -> Self {
        self.client_config = self.client_config.base_url(Some(base_url));
        self
    }

    pub fn set_api_key(mut self, api_key: impl Into<String>) -> Self {
        self.client_config = self.client_config.api_key(Some(api_key));
        self
    }

    pub fn set_organization(mut self, organization: impl Into<String>) -> Self {
        self.client_config = self.client_config.organization(Some(organization));
        self
    }

    pub fn set_extra_headers(mut self, extra_headers: HashMap<String, String>) -> Self {
        self.client_config = self.client_config.extra_headers(Some(extra_headers));
        self
    }

    pub fn notification_channel(
        mut self,
        notification_channel: Option<Sender<Notification>>,
    ) -> Self {
        self.notification_channel = notification_channel;
        self
    }
}

impl TypedInvocationBuilder<ChatMode> {
    pub fn chat() -> Self {
        Self::default()
    }

    pub fn generate() -> Self {
        Self::default()
    }

    pub fn embedding() -> EmbeddingInvocationBuilder {
        TypedInvocationBuilder::<EmbeddingMode>::new()
    }

    pub fn response_format_some(mut self, v: Value) -> Self {
        self.format = Some(v);
        self
    }

    pub fn stream(mut self, v: bool) -> Self {
        self.stream = Some(v);
        self
    }

    pub fn messages(mut self, msgs: Vec<Message>) -> Self {
        self.messages = Some(msgs);
        self
    }

    pub fn history(mut self, msg: Vec<Message>) -> Self {
        self.messages = Some(msg);
        self
    }

    pub fn add_message(mut self, msg: Message) -> Self {
        self.messages.get_or_insert_with(Vec::new).push(msg);
        self
    }

    pub fn set_message(mut self, msg: Message) -> Self {
        self.messages = Some(vec![msg]);
        self
    }

    pub fn tools(mut self, tools: Vec<Tool>) -> Self {
        self.tools = Some(tools);
        self
    }

    pub fn add_tool(mut self, tools: Vec<Tool>) -> Self {
        self.tools = Some(tools);
        self
    }

    pub fn num_ctx(mut self, v: u32) -> Self {
        self.opts.num_ctx = Some(v);
        self
    }

    pub fn repeat_last_n(mut self, v: i32) -> Self {
        self.opts.repeat_last_n = Some(v);
        self
    }

    pub fn repeat_penalty(mut self, v: f32) -> Self {
        self.opts.repeat_penalty = Some(v);
        self
    }

    pub fn temperature(mut self, v: f32) -> Self {
        self.opts.temperature = Some(v);
        self
    }

    pub fn seed(mut self, v: i32) -> Self {
        self.opts.seed = Some(v);
        self
    }

    pub fn stop(mut self, v: String) -> Self {
        self.opts.stop = Some(v);
        self
    }

    pub fn num_predict(mut self, v: i32) -> Self {
        self.opts.num_predict = Some(v);
        self
    }

    pub fn top_k(mut self, v: u32) -> Self {
        self.opts.top_k = Some(v);
        self
    }

    pub fn top_p(mut self, v: f32) -> Self {
        self.opts.top_p = Some(v);
        self
    }

    pub fn min_p(mut self, v: f32) -> Self {
        self.opts.min_p = Some(v);
        self
    }

    pub fn presence_penalty(mut self, v: f32) -> Self {
        self.opts.presence_penalty = Some(v);
        self
    }

    pub fn frequency_penalty(mut self, v: f32) -> Self {
        self.opts.frequency_penalty = Some(v);
        self
    }

    pub fn max_tokens(mut self, v: i32) -> Self {
        self.opts.max_tokens = Some(v);
        self
    }

    pub fn strip_thinking(mut self, strip_thinking: bool) -> Self {
        self.strip_thinking = Some(strip_thinking);
        self
    }

    pub fn use_tools(mut self, use_tools: bool) -> Self {
        self.use_tools = Some(use_tools);
        self
    }

    pub fn set_response_format_str(mut self, schema_json: &str) -> Self {
        self.response_format.set_raw(schema_json);
        self
    }

    pub fn set_response_format_value(mut self, schema: serde_json::Value) -> Self {
        self.response_format.set_value(schema);
        self
    }

    pub fn set_response_format_from<T: JsonSchema>(mut self) -> Self {
        self.response_format.set_type::<T>();
        self
    }

    pub fn set_response_format_spec(mut self, schema: SchemaSpec) -> Self {
        self.response_format.set_spec(schema);
        self
    }

    pub fn set_schema_name(mut self, name: impl Into<String>) -> Self {
        self.response_format.set_name(name);
        self
    }

    pub fn set_schema_strict(mut self, strict: bool) -> Self {
        self.response_format.set_strict(strict);
        self
    }

    pub async fn invoke_with(self, agent: &mut Agent) -> Result<ChatResponse, InvocationError> {
        let model = self.model.or(Some(agent.model.clone()));
        let format = match self.format {
            Some(format) => Some(format),
            None => match self
                .response_format
                .resolve()
                .map_err(InvocationError::InvalidJsonSchema)?
            {
                Some(spec) => Some(agent.inference_client.structured_output_format(&spec)?),
                None => agent.response_format.clone(),
            },
        };
        let stream = self.stream.or(Some(agent.stream));
        let keep_alive = self.keep_alive.or(agent.keep_alive.clone());
        let messages = self
            .messages
            .or(Some(agent.history.clone()))
            .unwrap_or_default();
        let tools = match self.use_tools {
            Some(false) => None,
            Some(true) | None => self.tools.or(agent.tools.clone()),
        };

        let name = self
            .name
            .or(Some(agent.name.clone()))
            .unwrap_or("Invocation".into());

        let options = self
            .opts
            .merge_over(agent.inference_options())
            .into_option();

        let Some(model) = model else {
            return Err(InvocationError::ModelNotDefined);
        };

        let request = ChatRequest {
            base: BaseRequest {
                model,
                format,
                options,
                stream,
                keep_alive,
            },
            messages,
            tools,
        };

        let invocation_request = InvocationRequest::new(
            self.strip_thinking.unwrap_or(agent.strip_thinking),
            request,
            agent.inference_client.clone(),
            agent.notification_channel.clone(),
            name,
        );

        let response = match &invocation_request.request.base.stream {
            Some(true) => super::invocations::invoke_streaming(invocation_request).await?,
            _ => super::invocations::invoke_nonstreaming(invocation_request).await?,
        };

        agent.history.push(response.message.clone());

        Ok(response)
    }

    pub async fn invoke(mut self) -> Result<ChatResponse, InvocationError> {
        let name = self.name.take().unwrap_or("Invocation".into());
        let options = self.opts.into_option();

        let Some(model) = self.model.take() else {
            return Err(InvocationError::ModelNotDefined);
        };

        let tools = match self.use_tools {
            Some(false) => None,
            Some(true) => self.tools.take(),
            None => self.tools.take(),
        };

        let client = self.client_config.build()?;

        let response_format = self
            .response_format
            .resolve()
            .map_err(InvocationError::InvalidJsonSchema)?;

        let format = response_format
            .map(|f| client.structured_output_format(&f))
            .transpose()?;
        let format = self.format.take().or(format);

        let request = ChatRequest {
            base: BaseRequest {
                model,
                format,
                options,
                stream: Some(self.stream.unwrap_or(false)),
                keep_alive: self.keep_alive.take(),
            },
            messages: self.messages.unwrap_or_default(),
            tools,
        };

        let invocation_request = InvocationRequest::new(
            self.strip_thinking.unwrap_or(false),
            request,
            client,
            self.notification_channel.take(),
            name,
        );

        let response = match &invocation_request.request.base.stream {
            Some(true) => super::invocations::invoke_streaming(invocation_request).await?,
            _ => super::invocations::invoke_nonstreaming(invocation_request).await?,
        };

        Ok(response)
    }
}

impl TypedInvocationBuilder<EmbeddingMode> {
    pub fn input(mut self, input: impl Into<String>) -> Self {
        self.embedding_input = Some(vec![input.into()]);
        self
    }

    pub fn inputs<T, I>(mut self, inputs: I) -> Self
    where
        T: Into<String>,
        I: IntoIterator<Item = T>,
    {
        self.embedding_input = Some(inputs.into_iter().map(Into::into).collect());
        self
    }

    pub async fn invoke_with(self, agent: &Agent) -> Result<EmbeddingsResponse, InvocationError> {
        let Some(model) = self.model.or(Some(agent.model.clone())) else {
            return Err(InvocationError::ModelNotDefined);
        };

        let Some(input) = self.embedding_input.filter(|input| !input.is_empty()) else {
            return Err(InvocationError::InputNotDefined);
        };

        let request = EmbeddingsRequest {
            model,
            input,
            options: None,
            keep_alive: self.keep_alive.or(agent.keep_alive.clone()),
        };

        Ok(agent.inference_client.embeddings(request).await?)
    }

    pub async fn invoke(mut self) -> Result<EmbeddingsResponse, InvocationError> {
        let Some(model) = self.model.take() else {
            return Err(InvocationError::ModelNotDefined);
        };

        let Some(input) = self
            .embedding_input
            .take()
            .filter(|input| !input.is_empty())
        else {
            return Err(InvocationError::InputNotDefined);
        };

        let client = self.client_config.build()?;

        let request = EmbeddingsRequest {
            model,
            input,
            options: None,
            keep_alive: self.keep_alive.take(),
        };

        Ok(client.embeddings(request).await?)
    }
}