仿搜狐视频网站源码,网站建设需求 百度文库,21ic项目外包平台,wordpress播放swf插件文章目录 前言环境准备依赖代码运行使用最后 前言
你好#xff0c;我是醉墨居士#xff0c;最近准备花一些时间来使用Rust语言实现一个智能助手#xff0c;希望能够帮助到你。
环境准备
安装Rust语言环境#xff0c;你可以从官网下载安装包安装。安装Ollama#xff0c;… 文章目录 前言环境准备依赖代码运行使用最后 前言
你好我是醉墨居士最近准备花一些时间来使用Rust语言实现一个智能助手希望能够帮助到你。
环境准备
安装Rust语言环境你可以从官网下载安装包安装。安装Ollama你可以在官网下载安装包安装。(我这里暂时qwen2.5:0.5b模型)安装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: OnceLockContext 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): QueryHashMapString, String) - JsonString {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回复
最后
我是醉墨居士这篇博客就先到这里后续我会继续更新欢迎你提出宝贵意见互相交流共同进步