direct_llm_usage/
direct_llm_usage.rs

1//! # Example: Direct LLM Usage
2//!
3//! This example demonstrates how to use the Helios Engine as a library to make
4//! direct calls to LLM models, without using the `Agent` abstraction. This is
5//! useful for simple use cases where you just need to interact with an LLM directly.
6
7use helios_engine::config::LLMConfig;
8use helios_engine::{ChatMessage, ChatSession, LLMClient};
9use std::io::{self, Write};
10
11#[tokio::main]
12async fn main() -> helios_engine::Result<()> {
13    println!("๐Ÿš€ Helios Direct LLM Usage Examples\n");
14
15    // --- Example 1: Simple single call ---
16    println!("๐Ÿ“ Example 1: Simple Single Call");
17    println!("{}", "=".repeat(50));
18    simple_call().await?;
19    println!();
20
21    // --- Example 2: Conversation with context ---
22    println!("๐Ÿ’ฌ Example 2: Conversation with Context");
23    println!("{}", "=".repeat(50));
24    conversation_with_context().await?;
25    println!();
26
27    // --- Example 3: Different providers ---
28    println!("๐ŸŒ Example 3: Using Different Providers");
29    println!("{}", "=".repeat(50));
30    different_providers_info();
31    println!();
32
33    // --- Example 4: Interactive chat ---
34    println!("๐ŸŽฎ Example 4: Interactive Chat");
35    println!("{}", "=".repeat(50));
36    println!("Would you like to start an interactive chat? (y/n)");
37
38    let mut choice = String::new();
39    io::stdin().read_line(&mut choice)?;
40
41    if choice.trim().to_lowercase() == "y" {
42        interactive_chat().await?;
43    } else {
44        println!("Skipping interactive chat.\n");
45    }
46
47    println!("โœ… All examples completed!");
48    Ok(())
49}
50
51/// Makes a simple, single call to the LLM.
52async fn simple_call() -> helios_engine::Result<()> {
53    // Create a configuration for the LLM.
54    let llm_config = LLMConfig {
55        model_name: "gpt-3.5-turbo".to_string(),
56        base_url: "https://api.openai.com/v1".to_string(),
57        api_key: std::env::var("OPENAI_API_KEY")
58            .unwrap_or_else(|_| "your-api-key-here".to_string()),
59        temperature: 0.7,
60        max_tokens: 2048,
61    };
62
63    // Create a new LLM client.
64    let client = LLMClient::new(helios_engine::llm::LLMProviderType::Remote(llm_config)).await?;
65
66    // Prepare the messages to send to the LLM.
67    let messages = vec![
68        ChatMessage::system("You are a helpful assistant that gives concise answers."),
69        ChatMessage::user("What is the capital of France? Answer in one sentence."),
70    ];
71
72    // Make the call to the LLM.
73    println!("Sending request...");
74    match client.chat(messages, None).await {
75        Ok(response) => {
76            println!("โœ“ Response: {}", response.content);
77        }
78        Err(e) => {
79            println!("โœ— Error: {}", e);
80            println!("  (Make sure to set OPENAI_API_KEY environment variable)");
81        }
82    }
83
84    Ok(())
85}
86
87/// Demonstrates a multi-turn conversation with context.
88async fn conversation_with_context() -> helios_engine::Result<()> {
89    // Create a configuration for the LLM.
90    let llm_config = LLMConfig {
91        model_name: "gpt-3.5-turbo".to_string(),
92        base_url: "https://api.openai.com/v1".to_string(),
93        api_key: std::env::var("OPENAI_API_KEY")
94            .unwrap_or_else(|_| "your-api-key-here".to_string()),
95        temperature: 0.7,
96        max_tokens: 2048,
97    };
98
99    // Create a new LLM client.
100    let client = LLMClient::new(helios_engine::llm::LLMProviderType::Remote(llm_config)).await?;
101
102    // Use a `ChatSession` to manage the conversation history.
103    let mut session = ChatSession::new()
104        .with_system_prompt("You are a helpful math tutor. Give brief, clear explanations.");
105
106    // --- First turn ---
107    println!("Turn 1:");
108    session.add_user_message("What is 15 * 23?");
109    print!("  User: What is 15 * 23?\n  ");
110
111    match client.chat(session.get_messages(), None).await {
112        Ok(response) => {
113            session.add_assistant_message(&response.content);
114            println!("Assistant: {}", response.content);
115        }
116        Err(e) => {
117            println!("Error: {}", e);
118            return Ok(());
119        }
120    }
121
122    // --- Second turn (with context from the first turn) ---
123    println!("\nTurn 2:");
124    session.add_user_message("Now divide that by 5.");
125    print!("  User: Now divide that by 5.\n  ");
126
127    match client.chat(session.get_messages(), None).await {
128        Ok(response) => {
129            session.add_assistant_message(&response.content);
130            println!("Assistant: {}", response.content);
131        }
132        Err(e) => {
133            println!("Error: {}", e);
134        }
135    }
136
137    println!("\n๐Ÿ’ก Notice how the assistant remembered the result from the first calculation!");
138
139    Ok(())
140}
141
142/// Provides information about using different LLM providers.
143fn different_providers_info() {
144    println!("You can use Helios with various LLM providers:\n");
145
146    println!("๐Ÿ”ต OpenAI:");
147    println!("   LLMConfig {{");
148    println!("       model_name: \"gpt-4\".to_string(),");
149    println!("       base_url: \"https://api.openai.com/v1\".to_string(),");
150    println!("       api_key: env::var(\"OPENAI_API_KEY\").unwrap(),");
151    println!("       temperature: 0.7,");
152    println!("       max_tokens: 2048,");
153    println!("   }}\n");
154
155    println!("๐ŸŸข Local LM Studio:");
156    println!("   LLMConfig {{");
157    println!("       model_name: \"local-model\".to_string(),");
158    println!("       base_url: \"http://localhost:1234/v1\".to_string(),");
159    println!("       api_key: \"not-needed\".to_string(),");
160    println!("       temperature: 0.7,");
161    println!("       max_tokens: 2048,");
162    println!("   }}\n");
163
164    println!("๐Ÿฆ™ Ollama:");
165    println!("   LLMConfig {{");
166    println!("       model_name: \"llama2\".to_string(),");
167    println!("       base_url: \"http://localhost:11434/v1\".to_string(),");
168    println!("       api_key: \"not-needed\".to_string(),");
169    println!("       temperature: 0.7,");
170    println!("       max_tokens: 2048,");
171    println!("   }}\n");
172
173    println!("๐Ÿ”ท Azure OpenAI:");
174    println!("   LLMConfig {{");
175    println!("       model_name: \"gpt-35-turbo\".to_string(),");
176    println!("       base_url: \"https://your-resource.openai.azure.com/...\".to_string(),");
177    println!("       api_key: env::var(\"AZURE_OPENAI_KEY\").unwrap(),");
178    println!("       temperature: 0.7,");
179    println!("       max_tokens: 2048,");
180    println!("   }}\n");
181}
182
183/// Starts an interactive chat session with the LLM.
184async fn interactive_chat() -> helios_engine::Result<()> {
185    // Create a configuration for the LLM.
186    let llm_config = LLMConfig {
187        model_name: "gpt-3.5-turbo".to_string(),
188        base_url: "https://api.openai.com/v1".to_string(),
189        api_key: std::env::var("OPENAI_API_KEY")
190            .unwrap_or_else(|_| "your-api-key-here".to_string()),
191        temperature: 0.7,
192        max_tokens: 2048,
193    };
194
195    // Create a new LLM client.
196    let client = LLMClient::new(helios_engine::llm::LLMProviderType::Remote(llm_config)).await?;
197    let mut session =
198        ChatSession::new().with_system_prompt("You are a friendly and helpful AI assistant.");
199
200    println!("Chat started! Type 'exit' or 'quit' to end the conversation.\n");
201
202    loop {
203        print!("You: ");
204        io::stdout().flush()?;
205
206        let mut input = String::new();
207        io::stdin().read_line(&mut input)?;
208        let input = input.trim();
209
210        if input.is_empty() {
211            continue;
212        }
213
214        if input == "exit" || input == "quit" {
215            println!("\n๐Ÿ‘‹ Goodbye!");
216            break;
217        }
218
219        // Handle special commands.
220        if input == "clear" {
221            session.clear();
222            println!("๐Ÿงน Conversation cleared!\n");
223            continue;
224        }
225
226        if input == "history" {
227            println!("\n๐Ÿ“œ Conversation history:");
228            for (i, msg) in session.messages.iter().enumerate() {
229                println!("  {}. {:?}: {}", i + 1, msg.role, msg.content);
230            }
231            println!();
232            continue;
233        }
234
235        session.add_user_message(input);
236
237        print!("Assistant: ");
238        io::stdout().flush()?;
239
240        match client.chat(session.get_messages(), None).await {
241            Ok(response) => {
242                session.add_assistant_message(&response.content);
243                println!("{}\n", response.content);
244            }
245            Err(e) => {
246                println!("\nโŒ Error: {}", e);
247                println!("   (Make sure OPENAI_API_KEY is set correctly)\n");
248                // Remove the last user message since it failed.
249                session.messages.pop();
250            }
251        }
252    }
253
254    Ok(())
255}