OpenAI's ChatGPT API wrapper for Rust 🦀

Overview

Regarding API changes from December 11th 2022

OpenAI made a change to API, and now requires a cloudflare clearance token. Due to this, authentication is becoming complicated. You can view recent updates regarding authentication methods in the #3 Pull Request. The master branch version (and cargo published crate) does not work because of this.

ChatGPT-rs

This is a reverse-engineered wrapper for the OpenAI's ChatGPT model.

Usage

use chatgpt::prelude::*;

#[tokio::main]
async fn main() -> chatgpt::Result<()> {
    // Starting client
    let token: String = std::env::var("SESSION_TOKEN").unwrap(); // obtain the session token. More on session tokens later.
    let mut client = ChatGPT::new(token)?;
    client.refresh_token().await?; // it is recommended to refresh token after creating a client
    
    // sending a simple message
    // normal responses take ~10-30 seconds to complete
    let response: String = client.send_message("Write me an HTTP server in Rust using the Axum framework.").await?;

    // in case dynamic updates are important
    // this method allows to receive the message as a stream
    let mut stream = client.send_message_streaming(None, None, "Write me an HTTP server in Rust using the Axum framework.").await?;
    
    while let Some(part) = stream.next().await {
        // a single response part
        println!("Got response part: {part:?}");
    }

    Ok(())
}

Conversations

Conversations are the threads in which ChatGPT can analyze previous messages and chain it's thoughts.

use chatgpt::prelude::*;

#[tokio::main]
async fn main() -> chatgpt::Result<()> {
    let token: String = std::env::var("SESSION_TOKEN").unwrap(); 
    let mut client = ChatGPT::new(token)?;
    client.refresh_token().await?;
    
    // We create a new empty conversation
    let mut conversation = client.new_conversation();
    let response: String = conversation.send_message(&client, "Write me a simple HTTP server in Rust").await?;

    // Now we can refer to our previous message when talking to ChatGPT
    let response: String = conversation.send_message(&client, "Now can you rewrite in Kotlin using the ktor framework?").await?;

    // Streamed responses are also supported
    let mut stream = conversation.send_message_streaming(&client, "Now can you rewrite it in TypeScript?").await?;

    while let Some(response) = stream.next() {
        // ...
    }

    Ok(())
}

Since conversations only hold little data (conversation ID and latest message ID), you can have multiple conversations at the same time!

Session Tokens

Session tokens allow access to the OpenAI API. You can find them in the Cookie storage of your browser.

Chromium-based browsers

Do this on the ChatGPT website

  1. Ctrl+Shift+I to open dev tools
  2. Navigate to the Application tab
  3. On the left, choose Storage->Cookies->https://chat.openai.com/chat
  4. Get the value of the cookie with name __Secure-next-auth.session-token

Explained in image

Firefox-based browsers

Do this on the ChatGPT website

  1. Ctrl+Shift+I to open dev tools
  2. Navigate to the Storage tab
  3. On the left choose Cookies->https://chat.openai.com/chat
  4. Get the value of the cookie with name __Secure-next-auth.session-token

Explained in image

Library roadmap

  • Refreshing tokens
  • Sending message and receiving response
  • Receiving response as a stream
  • Scoped conversations
  • Multiple conversations at the same time
You might also like...
Rust HTTP API Template using PostgreSQL, Redis, RabbitMQ, and Hexagonal Architecture

Rust Template HTTP API Rust API Template using PostgreSQL, Redis, RabbitMQ, and Hexagonal Architecture The following template provides a basic structu

This is a simple Api template for Rust ( Axum framework )

Axum-Rust-Rest-Api-Template This project is an open source Rest Api Template built with Rust's Axum framework. Why this project? I have been learning

An API project using Rust, Actix Web and JWT. *WIP*

Actix-web REST API with JWT (WIP) A simple CRUD backend app using Actix-web, Diesel and JWT Require Rust Stable Postgres Or using Docker How to run Ma

Rust Open Source Login/Register API

Actix Web API with Rustls (OpenSSL available/Without SSL/TLS too) This API uses Actix Web to serve secure HTTP endpoints, utilizing Rustls for TLS enc

Grape is a REST-like API framework for Ruby
Grape is a REST-like API framework for Ruby

Grape is a REST-like API framework for Ruby. It's designed to run on Rack or complement existing web application frameworks such as Rails and Sinatra by providing a simple DSL to easily develop RESTful APIs. It has built-in support for common conventions, including multiple formats, subdomain/prefix restriction, content negotiation, versioning and much more.

An tiny web API for @QuarryProtocol

Warlock Warlock is a tiny web API layer around Quarry Protocol and has endpoints to deserialize Quarry accounts like quarries, miners, and rewarders t

A customizable, simple and easy to use json REST API consumer

JACK is a generic JSON API client. It is useful to interact with APIs from multiple services such as Google and Twitter

Print Apple WeatherKit REST API weather conditions and hourly/daily foreacast to the console.
Print Apple WeatherKit REST API weather conditions and hourly/daily foreacast to the console.

weatherkit-rust A Rust CLI program to print current conditions and daily/hourly forecast to the console. Please read authorization.md as you need an A

RESTful Todo API with Actix-web and SeaORM. Documented by swagger-ui

RESTful Todo RESTful Todo API with Actix and SeaORM. Documented by swagger-ui Prerequisites Rust Usage Clone the repository and run the following comm

Comments
  • 11th of December changes

    11th of December changes

    Since the 11th of December, ChatGPT now has an extra cloudflare protection. This pull request will implement an authentication backend a single embedded browser-based authentication method.

    More authentication methods will be added later

    bug 
    opened by Maxuss 3
  • unwrap() is causing the main thread to panic, and SerdeError

    unwrap() is causing the main thread to panic, and SerdeError

    By using your example, instead of using unwrap(), I have decided to paste the session key in the ChatGPT::new("SESSION_KEY_HERE"), to avoid panicking.

    The program did not produce any errors until running it for about 2-5 seconds. It led me to another error; Error: SerdeError(Error("invalid type: null, expected struct ConversationResponse", line: 1, column: 4))

    opened by K0dikas 3
Owner
Maksim
A very epic developer :sunglasses:
Maksim
A secure and efficient gateway for interacting with OpenAI's API, featuring load balancing, user request handling without individual API keys, and global access control.

OpenAI Hub OpenAI Hub is a comprehensive and robust tool designed to streamline and enhance your interaction with OpenAI's API. It features an innovat

Akase Cho 30 Jun 16, 2023
Rust implementation of the `URLPattern` web API

urlpattern This crate implements the URLPattern web API in Rust. We aim to follow the specification as closely as possible. Contributing We appreciate

Deno Land 40 Dec 14, 2022
A pure Rust implementation of the Web Local Storage API, for use in non-browser contexts

Rust Web Local Storage API A Rust implementation of the Web LocalStorage API, for use in non-browser contexts About the Web Local Storage API MDN docs

RICHΛRD ΛNΛYΛ 10 Nov 28, 2022
Scratch-Containerised Rust GraphQL-API using Dataloaders

Dockerize Graphql Rust More current version at https://github.com/jayy-lmao/rust-cult-graphql-server This project is currently for demonstrating the u

James H. 89 Dec 3, 2022
A Rust Boilerplate server with GraphQL API, Diesel, PostgreSQL, session authentication and JWT

Canduma rust Graphql A Rust authentication server with GraphQL API, Diesel, PostgreSQL session authentication and JWT This repository contains a Graph

Julien Lenne 738 Dec 28, 2022
Implementation of the RealWorld backend API spec in Actix, Rust's powerful actor system and most fun web framework.

Actix codebase containing real world examples (CRUD, auth, advanced patterns, etc) that adheres to the RealWorld spec and API. ❗ (2021/05/13) This cod

Allen 475 Jan 2, 2023
Rust Rest API Stack with User Management

A secure-by-default rest api stack implemented with hyper, tokio, bb8 and postgres. This project is focused on providing end-to-end encryption by default for 12-factor applications. Includes a working user management and authentication backend written in postgresql with async S3 uploading for POST-ed data files.

Jay 10 Dec 25, 2022
Fastest autocomplete API written in rust 🦀

rust-autocomplete-api fastest* autocomplete API written in rust ?? *probably Run it locally cargo build --release ./target/release/autocomplete-api-po

Alexander Osipenko 4 Sep 23, 2022
Rust Rocket MongoDB token-authorization REST API boilerplate

Rust Rocket MongoDB token-auth REST API boilerplate In this repository, you can find backend Rust rocket mongodb rest-api boilerplate with token autho

null 6 Dec 7, 2022
An API to track various stats written in Rust. Tracking Github, Wakatime, Spotify, and Duolingo

Null API API For collecting data Explore the docs » View Demo · Report Bug · Request Feature Table of Contents About The Project Built With Getting St

The Null Dev 2 Dec 15, 2022