nexgenomics 0.2.9

The official Rust crate for NexGenomics
Documentation

// src/agents.rs

use crate::utils;
use reqwest::{Client,Error};
use reqwest::header::{AUTHORIZATION, CONTENT_TYPE, HeaderValue};
use chrono::{DateTime,Utc};
use serde::Serialize;
use serde::Deserialize;
use serde_json::Value;


#[derive(Debug,Deserialize)]
pub struct Agent {
    pub id: String,
    pub name: String,
    pub creator: String,
    pub template: String,
    pub created_at: DateTime<Utc>,
}

async fn inner_get_agents() -> Result<Vec<Agent>, Error> {
    let auth_token = utils::get_api_auth_token().unwrap();
    let url_stem = utils::get_api_url_stem().unwrap();

    let token = format!("Bearer {}", auth_token);
    let url = format!("{}/api/v0/agents",url_stem);
    //println!("{}, {}", token, url);

    //println!("****************");
    let client = Client::new();
    let response = client
        .get(url)
        .header (AUTHORIZATION, HeaderValue::from_str(&token).unwrap())
        .send()
        .await?
        .error_for_status()?;

    let p = response.json::<Vec<Agent>>().await?;
    Ok(p)
    
}

#[cfg(feature = "async")]
pub async fn get_agents() -> Result<Vec<Agent>,Error> {
    inner_get_agents().await
}


#[cfg(feature = "blocking")]
pub fn get_agents() -> Result<Vec<Agent>,Error> {
    let rt = tokio::runtime::Runtime::new()
        .expect("Failed to create Tokio runtime");
    rt.block_on(inner_get_agents())
}



// Keep this around as a model for a bit, but don't complete this.
// The hire functionality is a security risk without a rate controller.

#[derive(Debug)]
pub struct HireAgentParms{
    pub template:String,
    pub title:String,
    pub desc:String,
}
impl Default for HireAgentParms{
    fn default()->Self {
        HireAgentParms{
            // Default template is the generic data connector
            template: "c7fc81ae-0df8-4518-899b-16a0076017c8".to_string(),
            title: "---now---".to_string(),
            desc: "This description is a placeholder".to_string(),
        }
    }
}
pub async fn hire_agent(parms:&HireAgentParms) -> Result<(),Box<dyn std::error::Error>> {
    let title = if parms.title == "---now---" {
        format!("agent hired {}", Utc::now().to_rfc2822())
    } else {
        parms.title.to_string()
    };


    let auth_token = utils::get_api_auth_token().unwrap();
    let url_stem = utils::get_api_url_stem().unwrap();

    let token = format!("Bearer {}", auth_token);
    let url = format!("{}/api/v0/agent/hire",url_stem);
    //println!("{}, {}", token, url);

    #[derive(Serialize)]
    struct Body {
        template: String,
        title: String,
    }
    let body = Body{template:parms.template.to_string(), title,};

    //println!("****************");
    let client = Client::new();
    let response = client
        .put(url)
        .json(&body)
        .header (AUTHORIZATION, HeaderValue::from_str(&token).unwrap())
        .send()
        .await?
        .error_for_status()?;

    println!("############ {:?}",response);
    //let p = response.json::<HashMap<any>>().await?;
    let p = response.text().await?;
    println!("AAAAAAAAAAAAAAAAAA {:?}",p);
    Ok(())
}



#[cfg(feature = "async")]
pub async fn post_agent_sentences(agent_id:&str, sentences:Vec<&str>) -> Result<(),Box<dyn std::error::Error>> {

    let auth_token = utils::get_api_auth_token().ok_or("No api auth token")?;
    let url_stem = utils::get_api_url_stem().ok_or("No api url stem")?;

    let token = format!("Bearer {}", auth_token);
    let url = format!("{}/api/v0/agent/{}/sentences",url_stem, agent_id);
    //println!("{}, {}", token, url);
    //println!("{:?}",sentences.join("\n")+"\n");

    /*
    #[derive(Serialize)]
    struct Body {
        sentences: Vec<String>,
    }
    let body = Body{sentences:vec!["A".to_string(),"B".to_string(),"C".to_string()],};
    */

    let client = Client::new();
    let response = client
        .post(url)
        .header (AUTHORIZATION, HeaderValue::from_str(&token).unwrap())
        .header(CONTENT_TYPE,"application/octet-stream")
        .body(sentences.join("\n")+"\n")
        .send()
        .await?
        .error_for_status()?; // remove this if capturing the error text

    // TODO, we might get error text from the server. Figure out a way to capture and return it.

    let p:Value = response.json().await?;
    println!("{:?}",p);

    Ok(())

}