Function translate_code_from_string_stream

Source
pub fn translate_code_from_string_stream(
    code: &str,
    target_language: &str,
) -> Result<Response, TranslationError>
Expand description

Translates the code from a string to the target language using the Ollama API, returning a streaming response.

§Arguments

  • code - A string slice containing the code to be translated.
  • target_language - A string slice that holds the target language for the translation.

§Returns

  • Ok(Response) - A streaming HTTP response containing the translated code fragments.
  • Err(TranslationError) - An error that occurred during the translation process.
Examples found in repository?
examples/basic_string_stream/main.rs (line 19)
7fn main() {
8    let args: Vec<String> = env::args().collect();
9    if args.len() != 3 {
10        eprintln!("Usage: basic_string_stream <code> <target_language>");
11        process::exit(1);
12    }
13
14    let code = &args[1];
15    let target_language = &args[2];
16
17    println!("Translating code '{}' to '{}':", code, target_language);
18
19    match translate_code_from_string_stream(code, target_language) {
20        Ok(response) => {
21            let reader = io::BufReader::new(response);
22            for line in reader.lines() {
23                if let Ok(raw_line) = line {
24                    if let Ok(json) = serde_json::from_str::<Value>(&raw_line) {
25                        if let Some(fragment) = json.get("response").and_then(|v| v.as_str()) {
26                            print!("{}", fragment);  // Print without newline
27                        }
28                    }
29                }
30            }
31            println!();  // Add a final newline
32        }
33        Err(error) => eprintln!("Error: {}", error),
34    }
35}