从零开始:用Rust和Ollama构建企业应用应用

云信安装大师
90
AI 质量分
11 5 月, 2025
3 分钟阅读
0 阅读

从零开始:用Rust和Ollama构建企业级应用

引言

在当今快速发展的技术环境中,Rust语言以其出色的性能和安全性成为构建企业级应用的理想选择。而Ollama作为本地运行大型语言模型(Large Language Models)的工具,可以为企业应用添加智能能力。本教程将带你从零开始,使用Rust和Ollama构建一个具备AI能力的企业级应用。

准备工作

在开始之前,请确保你的开发环境满足以下要求:

  1. Rust开发环境(安装Rust工具链)
  2. Ollama已安装并配置
  3. 基本的Rust编程知识
  4. 终端/命令行操作经验

环境安装

1. 安装Rust

代码片段
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

安装完成后,运行以下命令验证安装:

代码片段
rustc --version
cargo --version

2. 安装Ollama

访问Ollama官网下载并安装适合你操作系统的版本。

安装完成后,启动Ollama服务:

代码片段
ollama serve

在另一个终端中,你可以下载一个模型进行测试:

代码片段
ollama pull llama2

项目创建与设置

1. 创建新的Rust项目

代码片段
cargo new rust_ollama_demo
cd rust_ollama_demo

2. 添加必要的依赖

编辑Cargo.toml文件,添加以下依赖:

代码片段
[dependencies]
reqwest = { version = "0.11", features = ["json"] }
tokio = { version = "1.0", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
anyhow = "1.0"

这些依赖分别是:
reqwest: HTTP客户端库
tokio: Rust异步运行时
serde: Rust序列化/反序列化框架
anyhow: 简化错误处理

Ollama API集成

1. 创建API客户端模块

src目录下创建ollama.rs文件:

代码片段
use anyhow::Result;
use serde::{Deserialize, Serialize};
use reqwest::Client;

#[derive(Debug, Serialize, Deserialize)]
pub struct GenerateRequest {
    pub model: String,
    pub prompt: String,
    pub stream: bool,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct GenerateResponse {
    pub response: String,
}

pub struct OllamaClient {
    client: Client,
    base_url: String,
}

impl OllamaClient {
    pub fn new(base_url: &str) -> Self {
        Self {
            client: Client::new(),
            base_url: base_url.to_string(),
        }
    }

    pub async fn generate(&self, request: &GenerateRequest) -> Result<GenerateResponse> {
        let url = format!("{}/api/generate", self.base_url);
        let response = self.client.post(&url)
            .json(request)
            .send()
            .await?
            .json::<GenerateResponse>()
            .await?;

        Ok(response)
    }
}

2. 在主程序中使用API客户端

修改src/main.rs文件:

代码片段
mod ollama;

use ollama::{OllamaClient, GenerateRequest};
use anyhow::Result;

#[tokio::main]
async fn main() -> Result<()> {
    // 初始化Ollama客户端,默认地址为http://localhost:11434
    let ollama_client = OllamaClient::new("http://localhost:11434");

    // 准备请求参数
    let request = GenerateRequest {
        model: "llama2".to_string(),
        prompt: "为什么Rust适合构建企业级应用?".to_string(),
        stream: false,
    };

    // 发送请求并获取响应
    let response = ollama_client.generate(&request).await?;

    // 打印AI的响应
    println!("AI回复:\n{}", response.response);

    Ok(())
}

构建企业级应用功能

现在我们将扩展这个基础结构,构建一个简单的企业知识问答系统。

1. 创建业务逻辑模块

src目录下创建knowledge_base.rs文件:

代码片段
use anyhow::Result;
use crate::ollama::{OllamaClient, GenerateRequest};

pub struct KnowledgeBase {
    ollama_client: OllamaClient,
}

impl KnowledgeBase {
    pub fn new(ollama_client: OllamaClient) -> Self {
        Self { ollama_client }
    }

    pub async fn query(&self, question: &str) -> Result<String> {
        // 构造提示词模板,让AI以专业的方式回答问题
        let prompt = format!(
            "你是一个企业知识库助手。请用专业、简洁的语言回答以下问题:\n\n问题:{}\n\n回答:",
            question
        );

        let request = GenerateRequest {
            model: "llama2".to_string(),
            prompt,
            stream: false,
        };

        let response = self.ollama_client.generate(&request).await?;

        Ok(response.response)
    }
}

2. 更新主程序使用知识库功能

更新src/main.rs:

代码片段
mod ollama;
mod knowledge_base;

use ollama::OllamaClient;
use knowledge_base::KnowledgeBase;
use anyhow::Result;

#[tokio::main]
async fn main() -> Result<()> {
    // 初始化客户端和知识库系统
    let ollama_client = OllamaClient::new("http://localhost:11434");
    let knowledge_base = KnowledgeBase::new(ollama_client);

    // 示例问题列表 - 在实际应用中可以从数据库或用户输入获取
    let questions = [
        "我们公司的退货政策是什么?",
        "如何申请年假?",
        "新员工入职流程有哪些步骤?",
        "公司的核心价值观是什么?"
    ];

    // 查询并显示结果
    for question in questions.iter() {
        println!("问题:{}", question);

        match knowledge_base.query(question).await {
            Ok(answer) => println!("回答:{}\n", answer),
            Err(e) => eprintln!("查询失败:{}\n", e),
        }

        tokio::time::sleep(std::time::Duration::from_secs(1)).await; // API限流避免过快请求

        println!("-------------------");
    }   

    Ok(())
}

API性能优化与错误处理

为了构建真正的企业级应用,我们需要添加一些关键功能:

1. API限流与重试机制

更新ollama.rs中的客户端实现:

“`rust
use std::time::Duration;
use reqwest::{Client, ClientBuilder};

// …其他代码…

impl OllamaClient {
pub fn new(baseurl: &str) -> Self {
// 配置带有超时和连接池的HTTP客户端
let client = ClientBuilder::new()
.timeout(Duration::from
secs(30))
.poolidletimeout(Duration::from_secs(60))
.build()
.expect(“Failed to create HTTP client”);

代码片段
    Self { client, base_url }
原创 高质量