vv-agent 0.8.0

VectorVein agent runtime, SDK, CLI, tools, and workspace backends
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
use std::borrow::Borrow;
use std::collections::BTreeMap;
use std::sync::Arc;

use serde::de::DeserializeOwned;

use crate::guardrails::{InputGuardrail, OutputGuardrail};
use crate::handoffs::Handoff;
use crate::model::ModelRef;
use crate::model_settings::ModelSettings;
use crate::output_validation::{
    HostOutputValidator, OutputRepair, OutputRepairRequest, OutputValidationContext,
    OutputValidationResult,
};
use crate::runtime::RuntimeHook;
use crate::tools::common::trim_portable_whitespace;
use crate::tools::{AgentToolBuilder, BackgroundAgentTaskBuilder};
use crate::tools::{Tool, ToolPolicy};
use crate::types::{Metadata, NoToolPolicy, SubAgentConfig};

pub type InstructionProvider =
    Arc<dyn Fn(&crate::context::RunContext, &Agent) -> String + Send + Sync>;
pub type OutputValidator = Arc<dyn Fn(&str) -> Result<(), String> + Send + Sync>;

#[derive(Clone)]
pub struct Agent {
    name: String,
    instructions: String,
    instruction_provider: Option<InstructionProvider>,
    model: Option<ModelRef>,
    model_settings: ModelSettings,
    tools: Vec<Arc<dyn Tool>>,
    handoffs: Vec<Handoff>,
    input_guardrails: Vec<Arc<dyn InputGuardrail>>,
    output_guardrails: Vec<Arc<dyn OutputGuardrail>>,
    output_type_name: Option<&'static str>,
    output_validator: Option<OutputValidator>,
    output_validation_enabled: bool,
    host_output_validator: Option<HostOutputValidator>,
    output_repair: Option<OutputRepair>,
    output_validation_max_repairs: u8,
    output_repair_model: Option<ModelRef>,
    output_repair_model_settings: Option<ModelSettings>,
    hooks: Vec<Arc<dyn RuntimeHook>>,
    max_cycles: Option<u32>,
    no_tool_policy: Option<NoToolPolicy>,
    tool_use_behavior: ToolUseBehavior,
    tool_policy: ToolPolicy,
    sub_agents: BTreeMap<String, SubAgentConfig>,
    metadata: Metadata,
}

impl Agent {
    pub fn builder(name: impl Into<String>) -> AgentBuilder {
        AgentBuilder {
            agent: Self {
                name: name.into(),
                instructions: String::new(),
                instruction_provider: None,
                model: None,
                model_settings: ModelSettings::default(),
                tools: Vec::new(),
                handoffs: Vec::new(),
                input_guardrails: Vec::new(),
                output_guardrails: Vec::new(),
                output_type_name: None,
                output_validator: None,
                output_validation_enabled: false,
                host_output_validator: None,
                output_repair: None,
                output_validation_max_repairs: 1,
                output_repair_model: None,
                output_repair_model_settings: None,
                hooks: Vec::new(),
                max_cycles: None,
                no_tool_policy: None,
                tool_use_behavior: ToolUseBehavior::default(),
                tool_policy: ToolPolicy::default(),
                sub_agents: BTreeMap::new(),
                metadata: Metadata::new(),
            },
            sub_agent_error: None,
            output_validation_error: None,
        }
    }

    pub fn name(&self) -> &str {
        &self.name
    }

    pub fn instructions(&self) -> &str {
        &self.instructions
    }

    pub(crate) fn has_dynamic_instructions(&self) -> bool {
        self.instruction_provider.is_some()
    }

    pub fn resolve_instructions(&self, context: &crate::context::RunContext) -> String {
        self.instruction_provider
            .as_ref()
            .map(|provider| provider(context, self))
            .unwrap_or_else(|| self.instructions.clone())
    }

    pub fn model(&self) -> Option<&ModelRef> {
        self.model.as_ref()
    }

    pub fn model_settings(&self) -> &ModelSettings {
        &self.model_settings
    }

    pub fn tools(&self) -> &[Arc<dyn Tool>] {
        &self.tools
    }

    pub fn handoffs(&self) -> &[Handoff] {
        &self.handoffs
    }

    pub(crate) fn input_guardrails(&self) -> &[Arc<dyn InputGuardrail>] {
        &self.input_guardrails
    }

    pub(crate) fn output_guardrails(&self) -> &[Arc<dyn OutputGuardrail>] {
        &self.output_guardrails
    }

    pub fn output_type_name(&self) -> Option<&'static str> {
        self.output_type_name
    }

    pub fn validate_output(&self, output: &str) -> Result<(), String> {
        match self.output_validator.as_ref() {
            Some(validator) => validator(output),
            None => Ok(()),
        }
    }

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

    pub fn host_output_validator(&self) -> Option<&HostOutputValidator> {
        self.host_output_validator.as_ref()
    }

    pub fn output_repair(&self) -> Option<&OutputRepair> {
        self.output_repair.as_ref()
    }

    pub fn output_validation_max_repairs(&self) -> u8 {
        self.output_validation_max_repairs
    }

    pub fn output_repair_model(&self) -> Option<&ModelRef> {
        self.output_repair_model.as_ref()
    }

    pub fn output_repair_model_settings(&self) -> Option<&ModelSettings> {
        self.output_repair_model_settings.as_ref()
    }

    pub fn hooks(&self) -> &[Arc<dyn RuntimeHook>] {
        &self.hooks
    }

    pub fn max_cycles(&self) -> Option<u32> {
        self.max_cycles
    }

    pub fn no_tool_policy(&self) -> Option<NoToolPolicy> {
        self.no_tool_policy
    }

    pub fn tool_use_behavior(&self) -> &ToolUseBehavior {
        &self.tool_use_behavior
    }

    pub fn tool_policy(&self) -> &ToolPolicy {
        &self.tool_policy
    }

    pub fn sub_agents(&self) -> &BTreeMap<String, SubAgentConfig> {
        &self.sub_agents
    }

    pub fn metadata(&self) -> &Metadata {
        &self.metadata
    }

    pub fn as_tool(&self) -> AgentToolBuilder {
        AgentToolBuilder::new(self.clone())
    }

    pub fn as_background_task(&self) -> BackgroundAgentTaskBuilder {
        BackgroundAgentTaskBuilder::new(self.clone())
    }
}

pub struct AgentBuilder {
    agent: Agent,
    sub_agent_error: Option<String>,
    output_validation_error: Option<String>,
}

impl AgentBuilder {
    pub fn instructions(mut self, instructions: impl Into<String>) -> Self {
        self.agent.instructions = instructions.into();
        self.agent.instruction_provider = None;
        self
    }

    pub fn dynamic_instructions(
        mut self,
        provider: impl Fn(&crate::context::RunContext, &Agent) -> String + Send + Sync + 'static,
    ) -> Self {
        self.agent.instructions.clear();
        self.agent.instruction_provider = Some(Arc::new(provider));
        self
    }

    pub fn model(mut self, model: ModelRef) -> Self {
        self.agent.model = Some(model);
        self
    }

    pub fn model_settings(mut self, settings: ModelSettings) -> Self {
        self.agent.model_settings = settings;
        self
    }

    pub fn tool(mut self, tool: impl Tool + 'static) -> Self {
        self.agent.tools.push(Arc::new(tool));
        self
    }

    pub fn tool_arc(mut self, tool: Arc<dyn Tool>) -> Self {
        self.agent.tools.push(tool);
        self
    }

    pub fn handoff(mut self, handoff: impl Into<Handoff>) -> Self {
        self.agent.handoffs.push(handoff.into());
        self
    }

    pub fn input_guardrail(mut self, guardrail: Arc<dyn InputGuardrail>) -> Self {
        self.agent.input_guardrails.push(guardrail);
        self
    }

    pub fn output_guardrail(mut self, guardrail: Arc<dyn OutputGuardrail>) -> Self {
        self.agent.output_guardrails.push(guardrail);
        self
    }

    pub fn output_type<T>(mut self) -> Self
    where
        T: DeserializeOwned + 'static,
    {
        self.agent.output_type_name = Some(std::any::type_name::<T>());
        self.agent.output_validator = Some(Arc::new(|output| {
            serde_json::from_str::<T>(output)
                .map(|_| ())
                .map_err(|error| error.to_string())
        }));
        self
    }

    pub fn output_validator(
        mut self,
        name: &'static str,
        validator: impl Fn(&str) -> Result<(), String> + Send + Sync + 'static,
    ) -> Self {
        self.agent.output_type_name = Some(name);
        self.agent.output_validator = Some(Arc::new(validator));
        self
    }

    pub fn output_validation_enabled(mut self, enabled: bool) -> Self {
        self.agent.output_validation_enabled = enabled;
        self
    }

    pub fn host_output_validator(
        mut self,
        validator: impl Fn(&str, &OutputValidationContext) -> OutputValidationResult
            + Send
            + Sync
            + 'static,
    ) -> Self {
        self.agent.host_output_validator = Some(Arc::new(validator));
        self
    }

    pub fn output_repair(
        mut self,
        repair: impl Fn(&OutputRepairRequest) -> Result<String, String> + Send + Sync + 'static,
    ) -> Self {
        self.agent.output_repair = Some(Arc::new(repair));
        self
    }

    pub fn output_validation_max_repairs(mut self, max_repairs: u8) -> Self {
        if max_repairs > 1 {
            self.output_validation_error =
                Some("output_validation_max_repairs must be 0 or 1".to_string());
        } else {
            self.agent.output_validation_max_repairs = max_repairs;
        }
        self
    }

    pub fn output_repair_model(mut self, model: ModelRef) -> Self {
        self.agent.output_repair_model = Some(model);
        self
    }

    pub fn output_repair_model_settings(mut self, settings: ModelSettings) -> Self {
        self.agent.output_repair_model_settings = Some(settings);
        self
    }

    pub fn hook(mut self, hook: Arc<dyn RuntimeHook>) -> Self {
        self.agent.hooks.push(hook);
        self
    }

    pub fn max_cycles(mut self, max_cycles: u32) -> Self {
        self.agent.max_cycles = Some(max_cycles);
        self
    }

    pub fn no_tool_policy(mut self, policy: NoToolPolicy) -> Self {
        self.agent.no_tool_policy = Some(policy);
        self
    }

    pub fn tool_use_behavior(mut self, behavior: ToolUseBehavior) -> Self {
        self.agent.tool_use_behavior = behavior;
        self
    }

    pub fn tool_policy(mut self, tool_policy: ToolPolicy) -> Self {
        self.agent.tool_policy = tool_policy;
        self
    }

    pub fn sub_agent(mut self, id: impl AsRef<str>, config: impl Borrow<SubAgentConfig>) -> Self {
        self.insert_sub_agent(id.as_ref(), config.borrow());
        self
    }

    pub fn sub_agents<I, K, C>(mut self, sub_agents: I) -> Self
    where
        I: IntoIterator<Item = (K, C)>,
        K: AsRef<str>,
        C: Borrow<SubAgentConfig>,
    {
        for (id, config) in sub_agents {
            self.insert_sub_agent(id.as_ref(), config.borrow());
        }
        self
    }

    pub fn metadata(mut self, key: impl Into<String>, value: serde_json::Value) -> Self {
        self.agent.metadata.insert(key.into(), value);
        self
    }

    pub fn build(self) -> Result<Agent, String> {
        if self.agent.name.trim().is_empty() {
            return Err("agent name cannot be empty".to_string());
        }
        if self.agent.instructions.trim().is_empty() && self.agent.instruction_provider.is_none() {
            return Err("agent instructions cannot be empty".to_string());
        }
        if let Some(error) = self.sub_agent_error {
            return Err(error);
        }
        if let Some(error) = self.output_validation_error {
            return Err(error);
        }
        if self.agent.output_validation_enabled && self.agent.host_output_validator.is_none() {
            return Err("enabled output validation requires a host_output_validator".to_string());
        }
        if self.agent.output_repair.is_some() && self.agent.host_output_validator.is_none() {
            return Err("output_repair requires a host_output_validator".to_string());
        }
        Ok(self.agent)
    }

    fn insert_sub_agent(&mut self, id: &str, config: &SubAgentConfig) {
        let normalized_id = trim_portable_whitespace(id);
        if normalized_id.is_empty() {
            self.sub_agent_error
                .get_or_insert_with(|| "sub-agent id cannot be empty".to_string());
            return;
        }
        if self.agent.sub_agents.contains_key(normalized_id) {
            self.sub_agent_error.get_or_insert_with(|| {
                format!("duplicate sub-agent id after normalization: {normalized_id}")
            });
            return;
        }
        self.agent
            .sub_agents
            .insert(normalized_id.to_string(), config.clone());
    }
}

#[derive(Clone, Default)]
pub enum ToolUseBehavior {
    #[default]
    RunLlmAgain,
    StopOnFirstTool,
    StopAtToolNames(Vec<String>),
}