Rust实现智能助手 - 项目初始化

文章目录

前言

你好,我是醉墨居士,最近准备花一些时间来使用Rust语言实现一个智能助手,希望能够帮助到你。

环境准备

  1. 安装Rust语言环境,你可以从官网下载安装包安装。
  2. 安装Ollama,你可以在官网下载安装包安装。(我这里暂时qwen2.5:0.5b模型)
  3. 安装PostgreSQL数据库。

依赖

toml 复制代码
ollama-rs = "0.2.2"
tokio = { version = "1.43.0", features = ["full"] }
tokio-stream = { version = "0.1.17" }
axum = "0.8.1"

代码

rust 复制代码
use std::{collections::HashMap, sync::OnceLock};

use axum::{
    extract::Query, routing::get, Json, Router
};
use ollama_rs::{
    generation::completion::request::GenerationRequest, Ollama
};

#[derive(Debug)]
struct Context {
    ollama: Ollama,
}

static CONTEXT: OnceLock<Context> = OnceLock::new();

impl Context {
    fn global() -> &'static Self {
        CONTEXT.get_or_init(|| {
            println!("Initializing Ollama...");
            Context {
                ollama: Ollama::default(),
            }
        })
    }
}

#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(chat));

    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

async fn chat(Query(mut query): Query<HashMap<String, String>>) -> Json<String> {
    let prompt = if let Some(prompt) = query.remove("prompt") {
        prompt
    } else {
        return Json("Error: prompt not provided".to_string());
    };

    let req = GenerationRequest::new("qwen2.5:0.5b".into(), prompt);
    let res = Context::global().ollama.generate(req).await;
    Json(
        if let Ok(res) = res {
            res.response
        } else {
            "Error".to_string()
        }
    )
}

运行

bash 复制代码
cargo run

使用

打开浏览器,访问http://localhost:3000?prompt=你好,即可得到AI回复

最后

我是醉墨居士,这篇博客就先到这里,后续我会继续更新,欢迎你提出宝贵意见,互相交流,共同进步

相关推荐
颜酱16 分钟前
图结构完全解析:从基础概念到遍历实现
javascript·后端·算法
m0_7369191029 分钟前
C++代码风格检查工具
开发语言·c++·算法
2501_9449347340 分钟前
高职大数据技术专业,CDA和Python认证优先考哪个?
大数据·开发语言·python
黎雁·泠崖1 小时前
【魔法森林冒险】5/14 Allen类(三):任务进度与状态管理
java·开发语言
2301_763472462 小时前
C++20概念(Concepts)入门指南
开发语言·c++·算法
TechWJ2 小时前
PyPTO编程范式深度解读:让NPU开发像写Python一样简单
开发语言·python·cann·pypto
Coder_Boy_3 小时前
基于SpringAI的在线考试系统-考试系统开发流程案例
java·数据库·人工智能·spring boot·后端
lly2024063 小时前
C++ 文件和流
开发语言
m0_706653233 小时前
分布式系统安全通信
开发语言·c++·算法
寻寻觅觅☆3 小时前
东华OJ-基础题-104-A == B ?(C++)
开发语言·c++