How can I multithread this ureq request?

I have an egui app with a button to ask questions to chatgpt. However while connecting to chatgpt the main thread is blocked so the application isn't drawn as long as it's connecting.
This is the ask_chatgpt function:

pub(crate) fn ask_chatgpt(prompt: String) -> Result<String, String> {
    let url = "https://www.pizzagpt.it/api/chat-completion";

    let response = ureq::post(url)
        .send_json(ureq::json!({
            "question": prompt,
            "secret": "salame"
        })).unwrap();

    if response.status() >= 200 && response.status() < 300 {
        Ok(response.into_string().unwrap())
    } else {
        Err(String::from("Response wasn't succesfull"))
    }
}

How can I make this multithreaded? I already tried with this:

pub(crate) fn ask_chatgpt(prompt: String) -> Result<String, String> {
    let url = "https://www.pizzagpt.it/api/chat-completion";

    let handle = thread::spawn(move || {
        let response = ureq::post(url)
            .send_json(ureq::json!({
                "question": prompt,
                "secret": "salame"
            })).unwrap();

        if response.status() >= 200 && response.status() < 300 {
            Ok(response.into_string().unwrap())
        } else {
            Err(String::from("Response wasn't succesfull"))
        }
    });

    handle.join().unwrap()
}

While there are no errors, the main thread is still clogged.

Not an egui user, but I found this section in their README linking to this example, which will hopefully help you. Looks to me like using a channel to pass the response from the background thread to the place where it is needed would be a good approach in an immediate mode GUI framework, rather than waiting in the main thread for the background thread to finish. Which—what you've already discovered—does not free the main thread to do other things, as it is busy waiting for the background thread.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.