For fun I wanted to try to make a tool to ask chatgpt to document rust files. I found an issue, in that the maximum message length the API allows seems to be 2048 characters.
It seems that the OpenAI API allows you to send files, so I was hoping that by sending the files to the server the model would have the context it needs to generate the comments.
However, I don't seem to be able to do so, I tried this:
use std::fmt::Write;
use std::fs;
use std::io;
use std::io::Read;
use chatgpt::prelude::*;
use clap::Parser;
use syn;
use syn::Item;
use reqwest;
#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None)]
struct Args
{
/// Path to the source code to document
#[arg(short, long)]
file_path: String,
}
fn main()
{
let args = Args::parse();
let mut file = std::fs::File::open(args.file_path).unwrap();
let mut content = String::new();
file.read_to_string(&mut content).unwrap();
let ast = syn::parse_file(&content).unwrap();
let mut input_buffer = String::new();
// Getting the API key here
let key = "My key that I have replaced for obvious reasons";
{
// Create a reqwest client
let client = reqwest::blocking::Client::new();
// Make a POST request to the OpenAI API
let response = client
.post("https://api.openai.com/v1/files")
.header("Authorization", "Bearer My key that I have replaced for obvious reasons")
.header("Content-Type", "application/json")
.body(content.clone())
.send().unwrap();
// Check if the request was successful
if response.status().is_success() {
println!("File uploaded successfully!");
} else {
println!("Failed to upload file. Status code: {}", response.status());
}
std::mem::forget(client);
std::mem::forget(response);
}
}
The response I get is:
Failed to upload file. Status code: 415 Unsupported Media Type
I am not sure what I am doing wrong. I have also tried changign the content type to text/plain
, I get the same error.
The async-openai
crate has Files
, which allows you to upload files to OpenAI:
let client = Client::new();
let request = CreateFileRequest {
input: "path/to/my/file.bin".into(),
purpose: "test".into(),
};
let response = client.files().create (request).await?;