my-chatgpt 0.1.0

A simple API wrapper for the ChatGPT API
Documentation

ChatGPT API Rust Client

A Rust library for interacting with OpenAI's Response API with streaming support.

Features

  • Stream or non-stream mode for API responses
  • Comprehensive error handling
  • Token usage tracking
  • Flexible output handling via callback functions

Installation

Add this to your Cargo.toml:

[dependencies]

chatgpt-api = { git = "https://github.com/yourusername/chatgpt-api.git" }

Usage

use chatgpt_api::chat::{chat, ChatError, UsageInfo};

async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let api_key = "your-api-key";
    let model = "gpt-4o";
    let instructions = "You are a helpful assistant.";
    let input = "Tell me about Rust programming language.";
    
    // Define a handler function for the API responses
    let handler = |usage: Option<&UsageInfo>, error: Option<&ChatError>, raw_chunk: Option<&serde_json::Value>| {
        if let Some(e) = error {
            eprintln!("Error: {:?}", e);
        }
        
        if let Some(u) = usage {
            println!("Input tokens: {}", u.input_tokens.unwrap_or(0));
            println!("Output tokens: {}", u.output_tokens.unwrap_or(0));
            println!("Total tokens: {}", u.total_tokens.unwrap_or(0));
        }
        
        // Process raw chunks if needed
        if let Some(chunk) = raw_chunk {
            // Do something with the raw chunk
        }
    };
    
    // Call the API with streaming enabled
    chat(instructions, input, api_key, model, true, handler).await?;
    
    Ok(())
}

Error Handling

The library provides a ChatError enum for different error cases:

pub enum ChatError {
    RequestError(String),
    ParseError(String),
    NetworkError(String),
    Unknown(String),
}

Token Usage

Token usage information is provided via the UsageInfo struct:

pub struct UsageInfo {
    pub input_tokens: Option<u32>,
    pub output_tokens: Option<u32>,
    pub total_tokens: Option<u32>,
}

License

MIT