High-performance, Reliable ChatGLM SDK natural language processing in Rust-Lang

Overview

RustGLM for ChatGLM Rust SDK - 中文文档

High-performance, high-quality Experience and Reliable ChatGLM SDK natural language processing in Rust-Language

1. Prepare beginning

1.1 Install Rust-up excutable programme (👇 Here only display Windows and Android files)

Rust-up-Windows-x64-Installation

Rust-up-Windows-x32-Installation

Rust-up-aarch64-android-Installation

if you are Linux user or MacOS user, please check here: Installation-User-Manual



1️⃣ After installation please use Command Line to Check Rust Version:

cargo -V

or

cargo --version


2️⃣ Then you can use command to add library to your own project:

cargo add RustGLM

or use

RustGLM = "0.1.1"

Other RustGLM Documation You may Need: 👉 🔗 RustGLM Documation



1.2 NTP Time Server for Rust

It provides highly accurate and secure time information via time servers on the Internet or LAN, and it is critical to ensure that all devices use the same time. The application here is for JWT authentication using:

pub fn time_sync() -> i64 {
    let client = SntpClient::new();
    let result = client.synchronize("ntp.aliyun.com").unwrap();

    let local_time: DateTime<Local> =
        DateTime::from(result.datetime().into_chrono_datetime().unwrap());

    let milliseconds = local_time.timestamp_millis() as i64;
    return milliseconds;
}

1.3 Store API Key

Saving Api key and store it in local file which call chatglm_api_key.txt file:

const API_KEY_FILE: &str = "chatglm_api_key.txt";

    pub fn save_api_key(api_key: &str) {
        match File::create(API_KEY_FILE) {
            Ok(mut file) => {
                if let Err(e) = writeln!(file, "{}", api_key) {
                    eprintln!("Failed to write to file: {}", e);
                }
            }
            Err(e) => eprintln!("Failed to create file: {}", e),
        }
    }

Load ChatGLM API key:

pub fn load_api_key() -> Option<String> {
        match File::open(API_KEY_FILE) {
            Ok(file) => {
                let reader = BufReader::new(file);
                reader.lines().next().map(|line| line.unwrap_or_default())
            }
            Err(_) => None,
        }
    }

1.4 Save Chat Content file

User chats and AI replies will be stored in chatglm_history.json.

const HISTORY_FILE: &str = "chatglm_history.json";

 pub fn add_history_to_file(&self, role: &str, content: &str) -> String {
        let json = self.create_json(role, content);

        if let Ok(mut file) = OpenOptions::new().write(true).append(true).open(&self.history_file_path) {
            if let Err(err) = writeln!(file, "{},", json) {
                eprintln!("Failed to write to history file: {}", err);
            }
        } else {
            eprintln!("Failed to open history file for writing");
        }

        json
    }

Load History Content from history file:

pub fn load_history_from_file(&self) -> String {
        if let Ok(file) = File::open(&self.history_file_path) {
            let reader = BufReader::new(file);
            reader.lines().filter_map(Result::ok).collect()
        } else {
            eprintln!("Failed to open history file for reading");
            String::new()
        }
    }


2. Easy-to-use SDK

2.1 Calling and Using the Rust Crate.io Library

Using this rust project SDK is less difficult 🤩. The following three examples to let you enter your question and the console will output ChatGLM to answer it:

🚩Enter the keywords: If there are no other characters, it will switch the Calling mode

Type the following keywords to switch the Calling mode:

Number Full-Name KeyWords
1 Server-Sent Events SSE, sse
2 Asynchronous ASYNC, Async, async
3 Synchronous SYNC, Sync, sync

The example for adding main function to your own project:

//Default is SSE calling method

#[tokio::main]
async fn main() {
    let mut rust_glm = RustGLM::RustGLM::new().await;
    loop {
        println!("You:");
        let ai_response = rust_glm.rust_chat_glm().await;
        if ai_response.is_empty() {
            break;
        }
        println!("Liliya: {}", rust_glm.get_ai_response());
        println!();
    }
}

Overall down, the introduction of this project three ways to request should still be relatively simple, the current BUG will try to fix 🥳, but also hope that all the developer of the support of this project! Thanks again 🎉!


4.Conclusion

Thank you for opening my project, this is a self-developed RustGLM development project, in order to expand different code language calling for the official SDK requirments. I am also working hard to develop and update this project, of course, I personally will continue to develop this project, I also adhere to the principle of open source more, so that everyone can enjoy my project. Finally, I hope more and more people will participate together 🚀 Thank you for seeing the end! 😆👏

You might also like...
Following along with the Geometry Processing with Intrinsic Triangulations course in Rust.

Intrinsic Triangulations in Rust In this repo is code I wrote following along with the Nicholas Sharp, Mark Gillespie, Keenan Crane's course on geomet

A simple, efficient Rust library for handling asynchronous job processing and task queuing.

job_queue Setup cargo add job_queue Usage Create a job use job_queue::{Error, Job, typetag, async_trait, serde}; #[derive(Debug, serde::Deserialize,

Rusoto is an AWS SDK for Rust
Rusoto is an AWS SDK for Rust

Rusoto is an AWS SDK for Rust You may be looking for: An overview of Rusoto AWS services supported by Rusoto API documentation Getting help with Rusot

A Polkadot SDK-like state machine written from scratch in Rust.

Rust State Machine This repository is the basis for a tutorial teaching how to develop a simple state machine using Rust. Goal The goal of this tutori

Membrane is an opinionated crate that generates a Dart package from a Rust library. Extremely fast performance with strict typing and zero copy returns over the FFI boundary via bincode.

Membrane is an opinionated crate that generates a Dart package from a Rust library. Extremely fast performance with strict typing and zero copy returns over the FFI boundary via bincode.

A Diablo II library for core and simple client functionality, written in Rust for performance, safety and re-usability

A Diablo II library for core and simple client functionality, written in Rust for performance, safety and re-usability

syncmap is a fast, concurrent cache library built with a focus on performance and correctness.

syncmap syncmap syncmap is a fast, concurrent cache library syncmap is a fast, concurrent cache library built with a focus on performance and correctn

Let Tauri's transparent background rendering window be stacked on Bevy's rendering window in real time to run the game with native-level performance!

Native Bevy with Tauri HUD DEMO 将 Tauri 的透明背景渲染窗口实时叠在 Bevy 的渲染窗口上,以使用原生级别性能运行游戏! Let Tauri's transparent background rendering window be stacked on Bev

A high level diffing library for rust based on diffs
A high level diffing library for rust based on diffs

Similar: A Diffing Library Similar is a dependency free crate for Rust that implements different diffing algorithms and high level interfaces for it.

Releases(v0.1.1)
  • v0.1.1(Feb 11, 2024)

    ChatGLM SDK for RustLang

    High-performance, Reliable ChatGLM SDK natural language processing in Rust-Lang

    1. The program is currently uploaded to the crate.io official repository, and you can build your own binaries. The application also supports streaming or synchronous request dependencies.
    2. Supports saving API keys locally and loading local API key files.
    3. Comparable to the operating efficiency of C and C++ languages, it can be called multiple times quickly to reduce performance costs.
    4. There is a system_role setting by default for fun role playing ChatGLM-4, Context-sensitive continuous conversations with ChatGLM-4
    Source code(tar.gz)
    Source code(zip)
Owner
Blueokanna
A young man passionate about the spirit of open source
Blueokanna
Rust SDK wrapper for the Mystic Light SDK

mystic_light_sdk Rust SDK wrapper for the Mystic Light SDK Requirements Any MSI device with RGB support Only Windows 7+ Dragon Center or Msi Center in

null 4 May 3, 2022
A formal, politely verbose programming language for building next-gen reliable applications

vfpl Pronounced "Veepl", the f is silent A politely verbose programming language for building next-gen reliable applications Syntax please initialize

VFPL 4 Jun 27, 2022
A simple script (in Rust lang) to create HTML from SVD

A simple script to create HTML from an SVD file This is a simple script written in Rust language to create a single HTML file from an SVD file. It's r

Björn Quentin 14 Aug 22, 2022
A fork of 'discord-token-botter' for rust lang.

Shahzain Botter V3(Rust) - If you were sold this tool, you have been scammed, this tool is free & open source Please DO NOT pay money for this tool A

Shahzain 5 Nov 7, 2022
Director is a simple, versatile, ergonomic state machine in Rust-lang.

Director Director is a simple, versatile, ergonomic state machine in Rust-lang. (no-std) | Examples | Docs | Latest Note | director = "0.5.0" Why? Bec

Doha Lee 2 Sep 19, 2022
A high-performance SPSC bounded circular buffer of bytes

Cueue A high performance, single-producer, single-consumer, bounded circular buffer of contiguous elements, that supports lock-free atomic batch opera

Thaler Benedek 38 Dec 28, 2022
Monorep for fnRPC (high performance serverless rpc framework)

fnrpc Monorep for fnRPC (high performance serverless rpc framework) cli Cli tool help build and manage functions Create RPC functions Create & Manage

Faasly 3 Dec 21, 2022
High-performance BitTorrent tracker compatible with UNIT3D tracker software

UNIT3D-Announce High-performance backend BitTorrent tracker compatible with UNIT3D tracker software. Usage # Clone this repository $ git clone https:/

HDInnovations 4 Feb 6, 2023
High-performance QEMU memory and instruction tracing

Cannoli Cannoli is a high-performance tracing engine for qemu-user. It can record a trace of both PCs executed, as well as memory operations. It consi

Margin Research 412 Oct 18, 2023
A high-performance Lambda authorizer for API Gateway that can validate OIDC tokens

oidc-authorizer A high-performance token-based API Gateway authorizer Lambda that can validate OIDC-issued JWT tokens. ?? Use case This project provid

Luciano Mammino 4 Oct 30, 2023