Expand description
§LLM Integration Layer
This module provides a unified, modular interface for integrating multiple LLM providers with VT Code, supporting Gemini, OpenAI, Anthropic, Meta AI, xAI, and DeepSeek.
§Architecture Overview
The LLM layer is designed with several key principles:
- Unified Interface: Single
AnyClienttrait for all providers - Provider Agnostic: Easy switching between providers
- Configuration Driven: TOML-based provider configuration
- Error Handling: Comprehensive error types and recovery
- Async Support: Full async/await support for all operations
§Supported Providers
| Provider | Status | Models |
|---|---|---|
| Gemini | ✓ | gemini-3.1-pro-preview, gemini-3-flash-preview |
| OpenAI | ✓ | gpt-5, o3, o4-mini, gpt-5-mini, gpt-5-nano |
| Anthropic | ✓ | claude-4.1-opus, claude-4-sonnet |
| xAI | ✓ | grok-4.6, grok-4.5, grok-build-0.1, grok-4.3 |
| DeepSeek | ✓ | deepseek-chat, deepseek-reasoner |
| Meta AI | ✓ | muse-spark-1.1, muse-spark-1.2 |
| Z.AI | ✓ | glm-5 |
| Ollama | ✓ | gpt-oss:20b (local) |
§Basic Usage
ⓘ
use vtcode_core::llm::{AnyClient, make_client};
use vtcode_core::utils::dot_config::ProviderConfigs;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Configure providers
let providers = ProviderConfigs {
gemini: Some(vtcode_core::utils::dot_config::ProviderConfig {
api_key: std::env::var("GEMINI_API_KEY")?,
model: "gemini-3-flash-preview".to_string(),
..Default::default()
}),
..Default::default()
};
// Create client
let client = make_client(&providers, "gemini")?;
// Make a request
let messages = vec![
vtcode_core::llm::types::Message {
role: "user".to_string(),
content: "Hello, how can you help me with coding?".to_string(),
}
];
let response = client.chat(&messages, None).await?;
println!("Response: {}", response.content);
Ok(())
}§Provider Configuration
ⓘ
use vtcode_core::utils::dot_config::{ProviderConfigs, ProviderConfig};
let config = ProviderConfigs {
gemini: Some(ProviderConfig {
api_key: "your-api-key".to_string(),
model: "gemini-3-flash-preview".to_string(),
temperature: Some(0.7),
max_tokens: Some(4096),
..Default::default()
}),
openai: Some(ProviderConfig {
api_key: "your-openai-key".to_string(),
model: "gpt-5".to_string(),
temperature: Some(0.3),
max_tokens: Some(8192),
..Default::default()
}),
..Default::default()
};§Advanced Features
§Streaming Responses
ⓘ
use vtcode_core::llm::AnyClient;
use futures::StreamExt;
let client = make_client(&providers, "gemini")?;
let mut stream = client.chat_stream(&messages, None).await?;
while let Some(chunk) = stream.next().await {
match chunk {
Ok(response) => print!("{}", response.content),
Err(e) => eprintln!("Error: {}", e),
}
}§Function Calling
ⓘ
use vtcode_core::llm::types::{FunctionDeclaration, FunctionCall};
let functions = vec![
FunctionDeclaration {
name: "read_file".to_string(),
description: "Read a file from the filesystem".to_string(),
parameters: serde_json::json!({
"type": "object",
"properties": {
"path": {"type": "string", "description": "File path to read"}
},
"required": ["path"]
}),
}
];
let response = client.chat_with_functions(&messages, &functions, None).await?;
if let Some(function_call) = response.function_call {
match function_call.name.as_str() {
"read_file" => {
// Handle function call
}
_ => {}
}
}§Error Handling
The LLM layer provides comprehensive error handling:
ⓘ
use vtcode_core::llm::LLMError;
match client.chat(&messages, None).await {
Ok(response) => println!("Success: {}", response.content),
Err(LLMError::Authentication) => eprintln!("Authentication failed"),
Err(LLMError::RateLimit { metadata: None }) => eprintln!("Rate limit exceeded"),
Err(LLMError::Network { message: e, metadata: None }) => eprintln!("Network error: {}", e),
Err(LLMError::Provider { message: e, metadata: None }) => eprintln!("Provider error: {}", e),
Err(e) => eprintln!("Other error: {}", e),
}§Performance Considerations
- Connection Pooling: Efficient connection reuse
- Request Batching: Where supported by providers
- Caching: Built-in prompt caching for repeated requests
- Timeout Handling: Configurable timeouts and retries
- Rate Limiting: Automatic rate limit handling
§LLM abstraction layer with modular architecture
This module provides a unified interface for different LLM providers with provider-specific implementations.
Re-exports§
pub use client::AnyClient;pub use client::ProviderClientAdapter;pub use client::make_client;pub use factory::create_provider_with_config;pub use factory::get_factory;pub use factory::get_models_manager;pub use lightweight_routing::LightweightFeature;pub use lightweight_routing::LightweightRouteResolution;pub use lightweight_routing::LightweightRouteSource;pub use lightweight_routing::ModelRoute;pub use lightweight_routing::auto_lightweight_model;pub use lightweight_routing::create_provider_for_model_route;pub use lightweight_routing::lightweight_model_choices;pub use lightweight_routing::main_model_route;pub use lightweight_routing::resolve_api_key_for_model_route;pub use lightweight_routing::resolve_lightweight_route;pub use mock_client::StaticResponseClient;
Modules§
- capabilities
- Provider capability declarations and feature detection.
- cgp
- Context-Generic Provider (CGP) wiring for the LLM factory. Context-generic provider wiring for VT Code’s LLM factory.
- client
- Simplified LLM client trait and adapter.
- config_
adapter - Adapter between config-level and factory-level provider configurations.
Re-exported from
vtcode_llm::config_adapterto eliminate duplication. - error_
display - Human-readable error formatting for LLM errors.
Re-exported from
vtcode_llm::error_displayto eliminate duplication. - factory
- LLM provider factory and global registry.
- http_
client - Shared HTTP client utilities for provider implementations. Centralized HTTP client factory for LLM providers.
- lightweight_
routing - Lightweight (cheap/fast) model routing for auxiliary features.
- mock_
client - Mock LLM client for testing.
Utilities for deterministic tests that need an
LLMClientimplementation without performing network calls. - model_
resolver - Model resolution, availability checks, and dynamic metadata.
Re-exported from
vtcode_llm::model_resolverto eliminate duplication. - provider
- Core LLM provider trait and error types. Universal LLM provider abstraction with API-specific role handling.
- provider_
base - Shared provider utilities to eliminate duplicate code.
Re-exported from
vtcode_llm::provider_baseto eliminate duplication. - provider_
builder - Generic provider builder with builder-pattern construction.
- provider_
config - Per-provider configuration types and the unified creation shim.
- providers
- Re-exported provider implementations. LLM provider implementations.
- reasoning_
effort - Capability-driven reasoning validation before a provider request is sent.
- request_
gap - Shared idle-gap tracker for detecting when the provider prompt cache has likely expired between dispatched LLM requests. Shared tracker for detecting idle gaps between dispatched LLM requests.
- rig_
adapter - Adapter for the Rig agent framework.
Re-exported from
vtcode_llm::rig_adapterto eliminate duplication. - tool_
bridge - Tool-call correlation and intent extraction for LLM responses.
Re-exported from
vtcode_llm::tool_bridgeto eliminate duplication. - types
- LLM request/response types, errors, and backend kind.
- usage_
cost - Provider-normalized usage accumulation and cache-aware session cost estimation. Provider-normalized usage accumulation and cache-aware session cost estimation.
- utils
- Shared utilities for request/response processing.
Re-exported from
vtcode_llm::utilsto eliminate duplication.
Structs§
- Adapter
Hooks - Shared adapter that enriches
ProviderConfigconversions withWorkspacePaths, telemetry, and error-reporting hooks fromvtcode-commons. - Anthropic
Provider - Correlation
Stats - Dynamic
Model Meta - Dynamic
Model Ref - Gemini
Provider - Hugging
Face Provider - LLMResponse
- Universal LLM response structure
- Merge
Gateway Provider - Message
Correlation Tracker - Track correlations across a session
- Message
Tool Correlation - Correlation between message intent and tool execution
- Meta
Provider - Model
Resolver - Ollama
Provider - OpenAI
Provider - Owned
Provider Config - Simple builder-friendly provider configuration backed by owned values.
- Provider
Capabilities - Cached provider capabilities to reduce repeated trait method calls
- Resolved
Model - Tool
Execution - Tool execution record tied to message
- Tool
Intent Extractor - Extractor for tool intents from messages
- Usage
- ZAIProvider
Enums§
- Adapter
Event - Telemetry event emitted when adapter hooks adjust provider configuration.
- Backend
Kind - Finish
Reason - Intent
Fulfillment - Tracks intent fulfillment
- LLMError
- LLM error types with optional provider metadata
- LLMStream
Event - Model
Availability - Tool
Intent - Stated intent extracted from message
Traits§
- Adapter
Hooks Provider - Trait that bundles the adapter hook dependencies into a single interface.
This replaces the previous four-parameter generic bound
(
Paths,Telemetry,Reporter,Formatter) with a single trait, following the Config Trait pattern from the Rust Patterns guide (Ch 3 — Config Trait Pattern). - Provider
Config - Trait describing the configuration required to instantiate an LLM provider.
Functions§
- as_
factory_ config - Convert an implementor of
ProviderConfiginto the configuration used by thevtcode_coreprovider factory. - as_
factory_ config_ with_ hooks - Convert a
ProviderConfiginto the factory configuration using the supplied adapter hooks for workspace, telemetry, and error integration. - collect_
single_ response - infer_
provider_ from_ model - Infer provider from model slug.