fauna-api 1.0.801

The Fauna SDK for Rust: accounts, Drive, groups, calendar, chats, payments, Parrot and live rooms.
Documentation
use chrono::Utc;

use crate::authentification::{Credentials, CredentialsOrApiKey};
use crate::error::Result;
use crate::groups::Group;
use crate::parrot::generative::{
    Content, Part, Role, Text, TextOptions, TextPart, generate_text_sync,
};

const SYSTEM: &str =
    "You name chats. Reply with 2-3 words. No sentence. No punctuation. Nothing else.";
const TURNS: usize = 8;
const TURN_CHARS: usize = 240;

fn part_text(part: &Part) -> &str {
    match part {
        Part::Text(part) => &part.text,
        _ => "",
    }
}

fn content_text(message: &Content) -> String {
    message
        .parts
        .iter()
        .map(part_text)
        .collect::<Vec<_>>()
        .join(" ")
        .split_whitespace()
        .collect::<Vec<_>>()
        .join(" ")
}

fn transcript(messages: &[Content]) -> String {
    let mut lines = Vec::new();
    for message in &messages[messages.len().saturating_sub(TURNS)..] {
        let text: String = content_text(message).chars().take(TURN_CHARS).collect();
        if text.is_empty() {
            continue;
        }
        let role = match message.role {
            Role::User => "USER",
            Role::Model => "MODEL",
            Role::System => "SYSTEM",
            Role::Tool => "TOOL",
        };
        lines.push(format!("{role}: {text}"));
    }
    lines.join("\n")
}

fn clamp_name(raw: &str) -> Option<String> {
    let line = raw.trim().split('\n').next().unwrap_or_default();
    let line = line.trim_matches(|c| c == '"' || c == '\'').trim();
    let name = line
        .split_whitespace()
        .take(3)
        .collect::<Vec<_>>()
        .join(" ");
    let name = name.trim();
    (!name.is_empty()).then(|| name.to_string())
}

pub async fn name_conversation(
    credentials: &Credentials,
    model: Text,
    messages: &[Content],
    group: Option<&Group>,
) -> Result<Option<String>> {
    let dump = transcript(messages);
    let result = generate_text_sync(
        &CredentialsOrApiKey::Credentials(credentials.clone()),
        model,
        TextOptions {
            group: group.cloned(),
            content: Some(vec![
                Content {
                    role: Role::System,
                    created_at: Utc::now(),
                    parts: vec![Part::Text(TextPart {
                        text: SYSTEM.to_string(),
                    })],
                    author: None,
                    model: None,
                },
                Content {
                    role: Role::User,
                    created_at: Utc::now(),
                    parts: vec![Part::Text(TextPart {
                        text: if dump.is_empty() {
                            "Name this conversation.".to_string()
                        } else {
                            format!("{dump}\n\nName this conversation.")
                        },
                    })],
                    author: None,
                    model: None,
                },
            ]),
            ..TextOptions::default()
        },
    )
    .await?;
    let raw = result.content.parts.iter().find_map(|part| match part {
        Part::Text(part) => Some(part.text.as_str()),
        _ => None,
    });
    Ok(raw.filter(|raw| !raw.is_empty()).and_then(clamp_name))
}