DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • React, Angular, and Vue.js: What’s the Technical Difference?
  • GitOps: Flux vs Argo CD
  • How to Introduce a New API Quickly Using Micronaut
  • Rust, WASM, and Edge: Next-Level Performance

Trending

  • Navigating Change Management: A Guide for Engineers
  • Analyzing Techniques to Provision Access via IDAM Models During Emergency and Disaster Response
  • Introducing Graph Concepts in Java With Eclipse JNoSQL, Part 2: Understanding Neo4j
  • What’s Got Me Interested in OpenTelemetry—And Pursuing Certification
  1. DZone
  2. Coding
  3. Languages
  4. Building a Rust Command Line Interface to Chat With Llama 3.2

Building a Rust Command Line Interface to Chat With Llama 3.2

Building a CLI that can chat with a state-of-the-art language model like Llama 3.2 has never been this easy. Discover how Rust and the Ollama library make it a breeze.

By 
Aditya Karnam Gururaj Rao user avatar
Aditya Karnam Gururaj Rao
·
Jan. 06, 25 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
2.4K Views

Join the DZone community and get the full member experience.

Join For Free

As a developer learning Rust, I wanted to build a practical project to apply my new skills. With the rise of large language models like Anthropic's Llama 3.2, I thought it would be interesting to create a Rust command line interface (CLI) to interact with the model.

In just a couple of minutes, I was able to put together a working CLI using the Ollama Rust library. The CLI, which I call "Jarvis," allows you to chat with Llama 3.2, as well as perform some basic commands like checking the time, date, and listing directory contents.

In this post, I'll walk through the key components of the Jarvis CLI and explain how you can use Rust to interface with Llama 3.2 or other large language models. By the end, you'll see how Rust's performance and expressiveness make it a great choice for AI applications.

The Jarvis CLI Structure 

The main components of the Jarvis CLI include:

1. JarvisConfig Struct

  • Defines the available commands
  • Methods to validate commands and print help text

2. Command Handling Logic in main()

  • Parses command line arguments
  • Invokes the appropriate function based on the command

3. Functions for Each Command

  • time - Gets current time
  • date - Gets today's date
  • hello - Prints a customizable greeting
  • ls - Lists directory contents
  • chat - Interacts with Llama 3.2 using Ollama lib

Here's a condensed version of the code:

Plain Text
 
struct JarvisConfig {
    commands: Vec<&'static str>,
}

impl JarvisConfig {
    fn new() -> Self {...} 
    fn print_help(&self) {...}
    fn is_valid_command(&self, command: &str) -> bool {...}
}

#[tokio::main]
async fn main() {
    let config = JarvisConfig::new();
    let args: Vec<String> = env::args().collect();
    
    match args[1].as_str() {
        "time" => {...}
        "date" => {...}
        "hello" => {...}
        "ls" => {...}
        "chat" => {
            let ollama = Ollama::default(); 
            
            match ollama
                .generate(GenerationRequest::new(
                    "llama3.2".to_string(),
                    args[2].to_string(),
                ))
                .await
            {
                Ok(res) => println!("{}", res.response),
                Err(e) => println!("Failed to generate response: {}", e),
            }
        }
        _ => {
            println!("Unknown command: {}", args[1]);
            config.print_help();
        }
    }
}


Using Ollama to Chat with Llama 3.2 The most interesting part is the "chat" command, which interfaces with Llama 3.2 using the Ollama Rust library.

After adding the Ollama dependency to Cargo.toml, using it is fairly straightforward:

1. Create an Ollama instance with default settings:

Plain Text
 
let ollama = Ollama::default();


2. Prepare a GenerationRequest with the model name and prompt:

Plain Text
 
GenerationRequest::new(
    "llama3.2".to_string(), 
    args[2].to_string()
)


3. Asynchronously send the request using ollama.generate():

Plain Text
 
match ollama.generate(...).await {
    Ok(res) => println!("{}", res.response),
    Err(e) => println!("Failed to generate response: {}", e),
}


That's it! With just a few lines of code, we can send prompts to Llama 3.2 and receive generated responses.

Example Usage 

Here are some sample interactions with the Jarvis CLI:

Plain Text
 
$ jarvis hello  
Hello, World!

$ jarvis hello Alice
Hello, Alice! 

$ jarvis time
Current time in format (HH:mm:ss): 14:30:15

$ jarvis ls /documents
/documents/report.pdf: file
/documents/images: directory

$ jarvis chat "What is the capital of France?" 
Paris is the capital and most populous city of France.


While Python remains the go-to for AI/ML, Rust is a compelling alternative where maximum performance, concurrency, and/or safety are needed. It's exciting to see Rust increasingly adopted in this space.

Conclusion

In this post, we learned how to build a Rust CLI to interact with Llama 3.2 using the Ollama library. With basic Rust knowledge, we could put together a useful AI-powered tool in just a couple of minutes. Rust's unique advantages make it well-suited for AI/ML systems development. As the ecosystem matures, I expect we'll see even more adoption.

I encourage you to try out Rust for your next AI project, whether it's a simple CLI like this or a more complex system. The performance, safety, and expressiveness may surprise you.

Command-line interface Interface (computing) Rust (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • React, Angular, and Vue.js: What’s the Technical Difference?
  • GitOps: Flux vs Argo CD
  • How to Introduce a New API Quickly Using Micronaut
  • Rust, WASM, and Edge: Next-Level Performance

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!