sombrax_agentic_core 0.1.1

SombraX Agentic Core (SAC) — a provider-agnostic Rust library for building LLM agents: content-modifying hooks, tool/MCP integration, and context optimization.
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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
//! Agent factory functions for building agents from configuration.
//!
//! This module provides generic factory functions that can build agents from any
//! configuration implementing [`LlmConfigLike`]. This allows applications to use
//! their own configuration structs while leveraging sac's agent infrastructure.
//!
//! # Example
//!
//! ```rust,ignore
//! use sombrax_agentic_core::providers::{build_agent, build_agent_with_options, AgentBuildOptions};
//!
//! // Simple agent
//! let agent = build_agent(&config, "You are helpful", 8192, vec![]).await?;
//!
//! // Agent with options
//! let options = AgentBuildOptions {
//!     max_turns: Some(25),
//!     hook: Some(my_hook),
//!     response_validation: Some(validation),
//! };
//! let agent = build_agent_with_options(&config, "You are helpful", 8192, vec![], options).await?;
//! ```

use crate::agent::wrapper::AgentWrapper;
use crate::context::{ContextOptimizer, OptimizationConfig};
use crate::hook::Hook;
use crate::provider::CompletionModelExt;
use crate::providers::{
    config::LlmConfigLike,
    provider_type::{ProviderType, ProviderTypeError},
    AnthropicClientBuilder, AnthropicClientExt, CerebrasClientBuilder, CerebrasClientExt,
    ChatTemplate, LmStudioClientBuilder, LmStudioClientExt, MinimaxClientBuilder, MinimaxClientExt,
    MlxLmClientBuilder, MlxLmClientExt, OllamaClientBuilder, OllamaClientExt, OpenAIClientBuilder,
    OpenAIClientExt, OpenRouterClientBuilder, OpenRouterClientExt, ZaiClientBuilder, ZaiClientExt,
};
use crate::retry::ResponseValidation;
use crate::tool::ToolDyn;
use crate::AgentBuilder;
use std::sync::Arc;
use thiserror::Error;
use tracing::{debug, info};

/// Error type for agent building operations.
#[derive(Error, Debug)]
pub enum AgentBuildError {
    /// Provider type error (unknown provider)
    #[error("Provider error: {0}")]
    ProviderType(#[from] ProviderTypeError),

    /// Invalid configuration
    #[error("Invalid configuration: {0}")]
    InvalidConfig(String),
}

/// Options for building an agent with hooks and execution limits.
///
/// This is a generic version that accepts any [`Hook`] implementation.
/// All fields are optional and have sensible defaults.
pub struct AgentBuildOptions<H: Hook + Clone = ()> {
    /// Maximum number of turns for the tool execution loop.
    /// When set, the agent will stop executing tools after this many turns.
    pub max_turns: Option<usize>,

    /// Optional hook for tracking, display, and notifications.
    /// Hooks can intercept and modify messages, tool calls, and responses.
    pub hook: Option<H>,

    /// Optional response validation for retrying on empty/low-quality responses.
    pub response_validation: Option<ResponseValidation>,

    /// Optional context optimizer for managing conversation context.
    /// Useful for reducing context size during long conversations.
    pub optimizer: Option<Arc<dyn ContextOptimizer>>,

    /// Optional optimization configuration for the context optimizer.
    pub optimization_config: Option<OptimizationConfig>,
}

impl<H: Hook + Clone> Default for AgentBuildOptions<H> {
    fn default() -> Self {
        Self {
            max_turns: None,
            hook: None,
            response_validation: None,
            optimizer: None,
            optimization_config: None,
        }
    }
}

/// Build an agent from any configuration implementing [`LlmConfigLike`].
///
/// This is the primary factory function for creating agents with the correct
/// provider client based on the `provider()` method of the configuration.
///
/// # Arguments
///
/// * `config` - Configuration implementing [`LlmConfigLike`]
/// * `system_prompt` - System prompt/preamble for the agent
/// * `max_tokens` - Maximum tokens for completion
/// * `tools` - Vector of tools to register with the agent
///
/// # Supported Providers
///
/// - `openrouter` - OpenRouter API (default)
/// - `openai` - Direct OpenAI API
/// - `anthropic` / `claude` - Anthropic Claude API
/// - `minimax` - MiniMax Anthropic-compatible API
/// - `cerebras` - Cerebras with custom tool content serialization
/// - `ollama` - Local Ollama (via OpenAI-compatible API)
/// - `zai` - ZAI with GLM-4.6 thinking mode support
/// - `mlx` / `mlxlm` - Local MLX-LM for Apple Silicon
///
/// # Example
///
/// ```rust,ignore
/// let agent = build_agent(&config, "You are a helpful assistant.", 8192, vec![]).await?;
/// let (response, stats) = agent.execute("Hello!", &[]).await?;
/// ```
pub async fn build_agent<C: LlmConfigLike>(
    config: &C,
    system_prompt: &str,
    max_tokens: u64,
    tools: Vec<Arc<dyn ToolDyn>>,
) -> Result<AgentWrapper, AgentBuildError> {
    build_agent_with_options(
        config,
        system_prompt,
        max_tokens,
        tools,
        AgentBuildOptions::<()>::default(),
    )
    .await
}

/// Build an agent with additional options (hooks, max_turns, validation).
///
/// This function extends [`build_agent`] with support for:
/// - Hooks (for tracking, display, ACP notifications)
/// - Maximum turns limit (to prevent infinite tool loops)
/// - Response validation (retry on empty responses)
///
/// # Arguments
///
/// * `config` - Configuration implementing [`LlmConfigLike`]
/// * `system_prompt` - System prompt/preamble for the agent
/// * `max_tokens` - Maximum tokens for completion
/// * `tools` - Vector of tools to register with the agent
/// * `options` - Additional options (hooks, max_turns, validation)
///
/// # Example
///
/// ```rust,ignore
/// let options = AgentBuildOptions {
///     max_turns: Some(25),
///     hook: Some(my_tracking_hook),
///     response_validation: Some(ResponseValidation::min_length(100)),
/// };
///
/// let agent = build_agent_with_options(&config, &prompt, 8192, tools, options).await?;
/// let (response, stats) = agent.execute(&prompt, &history).await?;
/// ```
pub async fn build_agent_with_options<C: LlmConfigLike, H: Hook + Clone>(
    config: &C,
    system_prompt: &str,
    max_tokens: u64,
    tools: Vec<Arc<dyn ToolDyn>>,
    options: AgentBuildOptions<H>,
) -> Result<AgentWrapper, AgentBuildError> {
    let provider_type = ProviderType::from_str(config.provider())?;
    let api_key = config.api_key().unwrap_or("none");

    info!(
        "Building agent: provider={}, model={}, think={:?} url={} temp={:?} top_k={:?} top_p={:?}",
        provider_type,
        config.model(),
        config.thinking(),
        config.url(),
        config.temperature(),
        config.top_k(),
        config.top_p()
    );

    match provider_type {
        ProviderType::OpenRouter => {
            debug!("Creating OpenRouter client");
            let mut builder = OpenRouterClientBuilder::new(api_key).base_url(config.url());

            // Apply sampling parameters from config if set
            if let Some(temp) = config.temperature() {
                builder = builder.temperature(temp);
            }
            if let Some(top_p) = config.top_p() {
                builder = builder.top_p(top_p);
            }
            if let Some(top_k) = config.top_k() {
                builder = builder.top_k(top_k);
            }

            // Apply provider routing configuration if set
            if let Some(blacklist) = config.blacklist() {
                debug!("OpenRouter blacklist: {:?}", blacklist);
                builder = builder.blacklist(blacklist.to_vec());
            }
            if let Some(whitelist) = config.whitelist() {
                debug!("OpenRouter whitelist: {:?}", whitelist);
                builder = builder.whitelist(whitelist.to_vec());
            }
            if let Some(allow_fallbacks) = config.allow_fallbacks() {
                debug!("OpenRouter allow_fallbacks: {}", allow_fallbacks);
                builder = builder.allow_fallbacks(allow_fallbacks);
            }

            builder = builder.max_tokens(max_tokens);
            let client = builder.build();
            let model = client
                .completion_model_adapter(config.model())
                .with_metrics();
            let mut agent_builder = AgentBuilder::new(model)
                .preamble(system_prompt)
                .tools(tools);

            if let Some(max) = options.max_turns {
                agent_builder = agent_builder.max_turns(max);
            }
            if let Some(hook) = options.hook.clone() {
                agent_builder = agent_builder.hook(hook);
            }
            if let Some(ref validation) = options.response_validation {
                agent_builder = agent_builder.response_validation(validation.clone());
            }
            if let Some(ref optimizer) = options.optimizer {
                agent_builder = agent_builder.context_optimizer_arc(optimizer.clone());
            }
            if let Some(ref opt_config) = options.optimization_config {
                agent_builder = agent_builder.optimization_config(opt_config.clone());
            }

            Ok(AgentWrapper::OpenRouter(agent_builder.build()))
        }
        ProviderType::OpenAI => {
            debug!("Creating OpenAI client");
            let mut builder = OpenAIClientBuilder::new(api_key)
                .base_url(config.url())
                .max_tokens(max_tokens);

            // Apply sampling parameters from config if set
            if let Some(temp) = config.temperature() {
                builder = builder.temperature(temp);
            }
            if let Some(top_p) = config.top_p() {
                builder = builder.top_p(top_p);
            }
            // top_k and repetition_penalty are not part of the canonical
            // OpenAI Chat Completions schema, but every OpenAI-compatible
            // local server we target (mlx-lm forks, vllm, sglang,
            // llama.cpp `--jinja`) accepts them as extension fields.
            // Forward when configured; upstream OpenAI silently ignores
            // unknown fields, so this is safe even against api.openai.com.
            if let Some(top_k) = config.top_k() {
                builder = builder.top_k(top_k);
            }
            if let Some(rep) = config.repetition_penalty() {
                builder = builder.repetition_penalty(rep);
            }

            // Forward explicit thinking-mode toggle so OpenAI-compatible
            // servers fronting thinking-by-default models (mlx_fun
            // serving GLM-5.1, Qwen-thinking, …) emit `content` instead
            // of reasoning-only output. Skip when unset — preserves
            // upstream OpenAI behaviour where the field is meaningless.
            if let Some(enabled) = config.thinking() {
                debug!("OpenAI client enable_thinking={}", enabled);
                builder = builder.enable_thinking(enabled);
            }

            let client = builder.build();
            let model = client
                .completion_model_adapter(config.model())
                .with_metrics();
            let mut agent_builder = AgentBuilder::new(model)
                .preamble(system_prompt)
                .tools(tools);

            if let Some(max) = options.max_turns {
                agent_builder = agent_builder.max_turns(max);
            }
            if let Some(hook) = options.hook.clone() {
                agent_builder = agent_builder.hook(hook);
            }
            if let Some(ref validation) = options.response_validation {
                agent_builder = agent_builder.response_validation(validation.clone());
            }
            if let Some(ref optimizer) = options.optimizer {
                agent_builder = agent_builder.context_optimizer_arc(optimizer.clone());
            }
            if let Some(ref opt_config) = options.optimization_config {
                agent_builder = agent_builder.optimization_config(opt_config.clone());
            }

            Ok(AgentWrapper::OpenAI(agent_builder.build()))
        }
        ProviderType::Anthropic => {
            let enable_thinking = config.thinking().unwrap_or(false);
            debug!(
                "Creating Anthropic client, thinking mode: {}",
                enable_thinking
            );
            let mut builder = AnthropicClientBuilder::new(api_key)
                .base_url(config.url())
                .enable_thinking(enable_thinking);

            if let Some(budget) = config.thinking_budget_tokens() {
                builder = builder.thinking_budget_tokens(budget);
            }

            // Apply sampling parameters from config if set
            if let Some(temp) = config.temperature() {
                builder = builder.temperature(temp);
            }
            if let Some(top_p) = config.top_p() {
                builder = builder.top_p(top_p);
            }
            if let Some(top_k) = config.top_k() {
                builder = builder.top_k(top_k);
            }

            builder = builder.max_tokens(max_tokens);
            let client = builder.build();
            let model = client
                .completion_model_adapter(config.model())
                .with_metrics();
            let mut agent_builder = AgentBuilder::new(model)
                .preamble(system_prompt)
                .tools(tools);

            if let Some(max) = options.max_turns {
                agent_builder = agent_builder.max_turns(max);
            }
            if let Some(hook) = options.hook.clone() {
                agent_builder = agent_builder.hook(hook);
            }
            if let Some(ref validation) = options.response_validation {
                agent_builder = agent_builder.response_validation(validation.clone());
            }
            if let Some(ref optimizer) = options.optimizer {
                agent_builder = agent_builder.context_optimizer_arc(optimizer.clone());
            }
            if let Some(ref opt_config) = options.optimization_config {
                agent_builder = agent_builder.optimization_config(opt_config.clone());
            }

            Ok(AgentWrapper::Anthropic(agent_builder.build()))
        }
        ProviderType::Minimax => {
            let enable_thinking = config.thinking().unwrap_or(false);
            debug!(
                "Creating MiniMax client, thinking mode: {}",
                enable_thinking
            );
            let mut builder = MinimaxClientBuilder::new(api_key)
                .base_url(config.url())
                .enable_thinking(enable_thinking);

            if let Some(budget) = config.thinking_budget_tokens() {
                builder = builder.thinking_budget_tokens(budget);
            }

            // Apply sampling parameters from config if set
            if let Some(temp) = config.temperature() {
                builder = builder.temperature(temp);
            }
            if let Some(top_p) = config.top_p() {
                builder = builder.top_p(top_p);
            }
            if let Some(top_k) = config.top_k() {
                builder = builder.top_k(top_k);
            }

            builder = builder.max_tokens(max_tokens);
            let client = builder.build();
            let model = client
                .completion_model_adapter(config.model())
                .with_metrics();
            let mut agent_builder = AgentBuilder::new(model)
                .preamble(system_prompt)
                .tools(tools);

            if let Some(max) = options.max_turns {
                agent_builder = agent_builder.max_turns(max);
            }
            if let Some(hook) = options.hook.clone() {
                agent_builder = agent_builder.hook(hook);
            }
            if let Some(ref validation) = options.response_validation {
                agent_builder = agent_builder.response_validation(validation.clone());
            }
            if let Some(ref optimizer) = options.optimizer {
                agent_builder = agent_builder.context_optimizer_arc(optimizer.clone());
            }
            if let Some(ref opt_config) = options.optimization_config {
                agent_builder = agent_builder.optimization_config(opt_config.clone());
            }

            Ok(AgentWrapper::Minimax(agent_builder.build()))
        }
        ProviderType::Cerebras => {
            debug!("Creating Cerebras client");
            let mut builder = CerebrasClientBuilder::new(api_key).base_url(config.url());

            // Apply sampling parameters from config if set
            if let Some(temp) = config.temperature() {
                builder = builder.temperature(temp);
            }
            if let Some(top_p) = config.top_p() {
                builder = builder.top_p(top_p);
            }
            if let Some(top_k) = config.top_k() {
                builder = builder.top_k(top_k);
            }

            builder = builder.max_tokens(max_tokens);
            let client = builder.build();
            let model = client
                .completion_model_adapter(config.model())
                .with_metrics();
            let mut agent_builder = AgentBuilder::new(model)
                .preamble(system_prompt)
                .tools(tools);

            if let Some(max) = options.max_turns {
                agent_builder = agent_builder.max_turns(max);
            }
            if let Some(hook) = options.hook.clone() {
                agent_builder = agent_builder.hook(hook);
            }
            if let Some(ref validation) = options.response_validation {
                agent_builder = agent_builder.response_validation(validation.clone());
            }
            if let Some(ref optimizer) = options.optimizer {
                agent_builder = agent_builder.context_optimizer_arc(optimizer.clone());
            }
            if let Some(ref opt_config) = options.optimization_config {
                agent_builder = agent_builder.optimization_config(opt_config.clone());
            }

            Ok(AgentWrapper::Cerebras(agent_builder.build()))
        }
        ProviderType::Ollama => {
            // Native Ollama /api/chat — one provider for local + cloud.
            // Cloud (https://ollama.com) needs a Bearer key but configs
            // shouldn't embed the secret; fall back to OLLAMA_API_KEY when
            // the config supplies no key (or the "none" sentinel). Local
            // use stays keyless.
            debug!("Creating native Ollama client");
            let ollama_key = if api_key.is_empty() || api_key == "none" {
                std::env::var("OLLAMA_API_KEY").unwrap_or_else(|_| "none".to_string())
            } else {
                api_key.to_string()
            };
            let mut builder = OllamaClientBuilder::new()
                .base_url(config.url())
                .api_key(&ollama_key)
                .max_tokens(max_tokens);

            // Apply sampling parameters from config if set
            if let Some(temp) = config.temperature() {
                builder = builder.temperature(temp);
            }
            if let Some(top_p) = config.top_p() {
                builder = builder.top_p(top_p);
            }
            if let Some(top_k) = config.top_k() {
                builder = builder.top_k(top_k);
            }
            if let Some(mp) = config.min_p() {
                builder = builder.min_p(mp);
            }

            // Native thinking traces when requested by config.
            if let Some(enabled) = config.thinking() {
                debug!("Ollama client enable_thinking={}", enabled);
                builder = builder.enable_thinking(enabled);
            }

            let client = builder.build();
            let model = client
                .completion_model_adapter(config.model())
                .with_metrics();
            let mut agent_builder = AgentBuilder::new(model)
                .preamble(system_prompt)
                .tools(tools);

            if let Some(max) = options.max_turns {
                agent_builder = agent_builder.max_turns(max);
            }
            if let Some(hook) = options.hook.clone() {
                agent_builder = agent_builder.hook(hook);
            }
            if let Some(ref validation) = options.response_validation {
                agent_builder = agent_builder.response_validation(validation.clone());
            }
            if let Some(ref optimizer) = options.optimizer {
                agent_builder = agent_builder.context_optimizer_arc(optimizer.clone());
            }
            if let Some(ref opt_config) = options.optimization_config {
                agent_builder = agent_builder.optimization_config(opt_config.clone());
            }

            Ok(AgentWrapper::Ollama(agent_builder.build()))
        }
        ProviderType::Zai => {
            // Determine thinking mode: config override, or default to enabled for ZAI
            let enable_thinking = config.thinking().unwrap_or(true);
            debug!("Creating ZAI client, thinking mode: {}", enable_thinking);

            let mut builder = ZaiClientBuilder::new(api_key)
                .base_url(config.url())
                .enable_thinking(enable_thinking);

            if let Some(budget) = config.thinking_budget_tokens() {
                builder = builder.thinking_budget_tokens(budget);
            }

            // Apply sampling parameters from config if set
            if let Some(temp) = config.temperature() {
                builder = builder.temperature(temp);
            }
            if let Some(top_p) = config.top_p() {
                builder = builder.top_p(top_p);
            }
            if let Some(top_k) = config.top_k() {
                builder = builder.top_k(top_k);
            }

            builder = builder.max_tokens(max_tokens);
            let client = builder.build();
            let model = client
                .completion_model_adapter(config.model())
                .with_metrics();
            let mut agent_builder = AgentBuilder::new(model)
                .preamble(system_prompt)
                .tools(tools);

            if let Some(max) = options.max_turns {
                agent_builder = agent_builder.max_turns(max);
            }
            if let Some(hook) = options.hook.clone() {
                agent_builder = agent_builder.hook(hook);
            }
            if let Some(ref validation) = options.response_validation {
                agent_builder = agent_builder.response_validation(validation.clone());
            }
            if let Some(ref optimizer) = options.optimizer {
                agent_builder = agent_builder.context_optimizer_arc(optimizer.clone());
            }
            if let Some(ref opt_config) = options.optimization_config {
                agent_builder = agent_builder.optimization_config(opt_config.clone());
            }

            Ok(AgentWrapper::Zai(agent_builder.build()))
        }
        ProviderType::MlxLm => {
            let mut builder = MlxLmClientBuilder::new().base_url(config.url());

            // Detect if this is an iquest model family (uses ChatML with specific stop sequences)
            let is_iquest = config.chat_template() == Some("iquest")
                || config.model().to_lowercase().contains("iquest");

            // Apply chat template: explicit config takes precedence, otherwise auto-detect from model name
            builder = match config.chat_template() {
                Some("minimax") => builder.chat_template(ChatTemplate::Minimax),
                Some("minimax25") | Some("minimax2.5") => {
                    builder.chat_template(ChatTemplate::Minimax25)
                }
                Some("chatml") | Some("iquest") | Some("qwen") => {
                    builder.chat_template(ChatTemplate::ChatML)
                }
                Some("qwen35") | Some("qwen3.5") => builder.chat_template(ChatTemplate::Qwen35),
                Some("glm") => builder.chat_template(ChatTemplate::GLM),
                Some("openai") => builder.chat_template(ChatTemplate::OpenAI),
                None => builder.auto_chat_template(config.model()), // Auto-detect from model name
                Some(other) => {
                    debug!(
                        "Unknown chat_template '{}', auto-detecting from model name",
                        other
                    );
                    builder.auto_chat_template(config.model())
                }
            };

            // Apply iquest-specific stop sequences for ChatML template and anti-repetition
            if is_iquest {
                debug!("Applying iquest model stop sequences (ChatML + anti-repetition)");
                builder = builder
                    .with_chatml_stop_sequences()
                    .with_anti_repetition_stops();
            }

            debug!("Creating MLX-LM client");

            // Apply sampling parameters from config if set
            if let Some(temp) = config.temperature() {
                builder = builder.temperature(temp);
            }
            if let Some(top_p) = config.top_p() {
                builder = builder.top_p(top_p);
            }
            if let Some(top_k) = config.top_k() {
                builder = builder.top_k(top_k);
            }

            // Apply repetition penalty only if explicitly configured
            if let Some(repetition_penalty) = config.repetition_penalty() {
                builder = builder.repetition_penalty(repetition_penalty);
            }

            if let Some(ctx_size) = config.repetition_context_size() {
                builder = builder.repetition_context_size(ctx_size);
            }
            if let Some(freq) = config.frequency_penalty() {
                builder = builder.frequency_penalty(freq);
            }
            if let Some(pres) = config.presence_penalty() {
                builder = builder.presence_penalty(pres);
            }
            if let Some(mp) = config.min_p() {
                builder = builder.min_p(mp);
            }

            builder = builder.max_tokens(max_tokens);
            let client = builder.build();
            let model = client
                .completion_model_adapter(config.model())
                .with_metrics();
            let mut agent_builder = AgentBuilder::new(model)
                .preamble(system_prompt)
                .tools(tools);

            if let Some(max) = options.max_turns {
                agent_builder = agent_builder.max_turns(max);
            }
            if let Some(hook) = options.hook.clone() {
                agent_builder = agent_builder.hook(hook);
            }
            if let Some(ref validation) = options.response_validation {
                agent_builder = agent_builder.response_validation(validation.clone());
            }
            if let Some(ref optimizer) = options.optimizer {
                agent_builder = agent_builder.context_optimizer_arc(optimizer.clone());
            }
            if let Some(ref opt_config) = options.optimization_config {
                agent_builder = agent_builder.optimization_config(opt_config.clone());
            }

            Ok(AgentWrapper::MlxLm(agent_builder.build()))
        }
        ProviderType::LmStudio => {
            let mut builder = LmStudioClientBuilder::new().base_url(config.url());

            debug!("Creating LMStudio client");

            // Apply sampling parameters from config if set
            if let Some(temp) = config.temperature() {
                builder = builder.temperature(temp);
            }
            if let Some(top_p) = config.top_p() {
                builder = builder.top_p(top_p);
            }
            if let Some(top_k) = config.top_k() {
                builder = builder.top_k(top_k);
            }

            // Apply repeat penalty only if explicitly configured
            if let Some(repeat_penalty) = config.repeat_penalty() {
                builder = builder.repeat_penalty(repeat_penalty);
            }

            if let Some(ctx_size) = config.repetition_context_size() {
                builder = builder.repetition_context_size(ctx_size);
            }
            if let Some(freq) = config.frequency_penalty() {
                builder = builder.frequency_penalty(freq);
            }
            if let Some(pres) = config.presence_penalty() {
                builder = builder.presence_penalty(pres);
            }
            if let Some(mp) = config.min_p() {
                builder = builder.min_p(mp);
            }

            builder = builder.max_tokens(max_tokens);
            let client = builder.build();
            let model = client
                .completion_model_adapter(config.model())
                .with_metrics();
            let mut agent_builder = AgentBuilder::new(model)
                .preamble(system_prompt)
                .tools(tools);

            if let Some(max) = options.max_turns {
                agent_builder = agent_builder.max_turns(max);
            }
            if let Some(hook) = options.hook.clone() {
                agent_builder = agent_builder.hook(hook);
            }
            if let Some(ref validation) = options.response_validation {
                agent_builder = agent_builder.response_validation(validation.clone());
            }
            if let Some(ref optimizer) = options.optimizer {
                agent_builder = agent_builder.context_optimizer_arc(optimizer.clone());
            }
            if let Some(ref opt_config) = options.optimization_config {
                agent_builder = agent_builder.optimization_config(opt_config.clone());
            }

            Ok(AgentWrapper::LmStudio(agent_builder.build()))
        }
    }
}