欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 锐评 > Rust实现智能助手 - 项目初始化

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

2025/2/25 1:37:05 来源:https://blog.csdn.net/qq_67733273/article/details/145090875  浏览:    关键词:Rust实现智能助手 - 项目初始化

文章目录

  • 前言
  • 环境准备
  • 依赖
  • 代码
  • 运行
  • 使用
  • 最后

前言

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

环境准备

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

依赖

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

代码

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()})
}

运行

cargo run

使用

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

最后

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

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com