Skip to main content

fauna_api/parrot/
agent.rs

1use futures_util::stream::BoxStream;
2use serde::{Deserialize, Serialize};
3use serde_json::{Map, Value, json};
4
5use super::generative::{
6    Content, Image, StreamEvent, Text, TextResponse, ToolsOrTool, Video, Voice, VoiceEvent,
7};
8use super::socket;
9use crate::ant::persona::PartialDemographic;
10use crate::authentification::CredentialsOrApiKey;
11use crate::cicada::inboxes::Inbox;
12use crate::error::Result;
13use crate::groups::Group;
14use crate::http::{client, ok};
15
16/// How private a memory is. A chat with other people in it reads memories up to MODERATE.
17#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
18#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
19pub enum Sensitivity {
20    VeryLow,
21    Low,
22    Moderate,
23    High,
24    VeryHigh,
25}
26
27#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
28pub struct Memory {
29    pub id: u64,
30    pub memory: String,
31    pub scope: String,
32    pub sensitivity: Sensitivity,
33    #[serde(default)]
34    pub embedding: Vec<f64>,
35}
36
37#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
38pub struct Memories {
39    pub nodes: Vec<Memory>,
40    pub edges: Vec<(u64, u64)>,
41    pub scopes: Vec<String>,
42}
43
44/// Observe: store a new memory. Pass `group` to act on that group's shared
45/// memory graph instead of the caller's personal one (caller must be a member).
46pub async fn observe(
47    authorization: &CredentialsOrApiKey,
48    content: &str,
49    group: Option<&Group>,
50) -> Result<Memory> {
51    let mut request = client()
52        .post(format!("{}/agent/memories", super::get_url()))
53        .header(
54            "Authorization",
55            match authorization {
56                CredentialsOrApiKey::Credentials(credentials) => {
57                    format!("Token {}", credentials.token)
58                }
59                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
60            },
61        );
62    if let Some(group) = group {
63        request = request.header("Group", &group.id);
64    }
65    let response = request.json(&json!({ "content": content })).send().await?;
66    Ok(ok(response).await?.json().await?)
67}
68
69/// Recall: query associative memory. Pass `group` for that group's shared graph.
70pub async fn recall(
71    authorization: &CredentialsOrApiKey,
72    query: &str,
73    scope: Option<&str>,
74    group: Option<&Group>,
75) -> Result<Vec<Memory>> {
76    let mut request = client()
77        .post(format!("{}/agent/recall", super::get_url()))
78        .header(
79            "Authorization",
80            match authorization {
81                CredentialsOrApiKey::Credentials(credentials) => {
82                    format!("Token {}", credentials.token)
83                }
84                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
85            },
86        );
87    if let Some(group) = group {
88        request = request.header("Group", &group.id);
89    }
90    let mut body = Map::new();
91    body.insert("query".to_string(), Value::from(query));
92    if let Some(scope) = scope {
93        body.insert("scope".to_string(), Value::from(scope));
94    }
95    let response = request.json(&body).send().await?;
96    Ok(ok(response).await?.json().await?)
97}
98
99/// Export: get the full memory graph. Pass `group` for that group's shared graph.
100pub async fn export_memory(
101    authorization: &CredentialsOrApiKey,
102    group: Option<&Group>,
103) -> Result<Memories> {
104    let mut request = client()
105        .get(format!("{}/agent/memories", super::get_url()))
106        .header(
107            "Authorization",
108            match authorization {
109                CredentialsOrApiKey::Credentials(credentials) => {
110                    format!("Token {}", credentials.token)
111                }
112                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
113            },
114        );
115    if let Some(group) = group {
116        request = request.header("Group", &group.id);
117    }
118    let response = request.send().await?;
119    Ok(ok(response).await?.json().await?)
120}
121
122/// Remove: delete a specific memory node. Pass `group` for that group's graph.
123pub async fn remove_memory(
124    authorization: &CredentialsOrApiKey,
125    id: u64,
126    group: Option<&Group>,
127) -> Result<()> {
128    let mut request = client()
129        .delete(format!("{}/agent/memories/{id}", super::get_url()))
130        .header(
131            "Authorization",
132            match authorization {
133                CredentialsOrApiKey::Credentials(credentials) => {
134                    format!("Token {}", credentials.token)
135                }
136                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
137            },
138        );
139    if let Some(group) = group {
140        request = request.header("Group", &group.id);
141    }
142    ok(request.send().await?).await?;
143    Ok(())
144}
145
146/// Clear: wipe the entire memory graph. Pass `group` for that group's graph.
147pub async fn clear_memory(
148    authorization: &CredentialsOrApiKey,
149    group: Option<&Group>,
150) -> Result<()> {
151    let mut request = client()
152        .delete(format!("{}/agent/memories", super::get_url()))
153        .header(
154            "Authorization",
155            match authorization {
156                CredentialsOrApiKey::Credentials(credentials) => {
157                    format!("Token {}", credentials.token)
158                }
159                CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
160            },
161        );
162    if let Some(group) = group {
163        request = request.header("Group", &group.id);
164    }
165    ok(request.send().await?).await?;
166    Ok(())
167}
168
169/// The `options` argument of the agent's `generate_text` and `generate_text_sync`:
170/// the generative options plus `memories`, how many to recall on the latest
171/// request, `inbox`, the one inbox the caller's inbox tools work in, and `group`,
172/// whose memory graph. Dropping the returned stream closes the socket.
173#[derive(Debug, Clone, Default)]
174pub struct TextOptions {
175    pub content: Option<Vec<Content>>,
176    pub tools: Option<ToolsOrTool>,
177    pub max_tools: Option<u32>,
178    pub memories: Option<u32>,
179    pub reasoning: Option<String>,
180    pub inbox: Option<Inbox>,
181    pub group: Option<Group>,
182}
183
184/// Streaming text generation. A singular Tool forces it; an array lets the model
185/// choose. Where the model can call tools it can also save memories with
186/// observe_memory. Unless a tool is forced, the model also gets the caller's own
187/// calendar and inbox tools, which run in Fauna; with `inbox` they work there and
188/// take no inbox.
189pub async fn generate_text(
190    authorization: &CredentialsOrApiKey,
191    model: Text,
192    options: TextOptions,
193) -> Result<BoxStream<'static, StreamEvent>> {
194    socket::stream_text(
195        authorization,
196        "/agent/text",
197        model.as_str(),
198        socket::TextOptions {
199            content: options.content,
200            tools: options.tools,
201            max_tools: options.max_tools,
202            memories: options.memories,
203            reasoning: options.reasoning,
204            inbox: options.inbox.map(|inbox| inbox.id),
205            group: options.group,
206        },
207    )
208    .await
209}
210
211pub async fn generate_text_sync(
212    authorization: &CredentialsOrApiKey,
213    model: Text,
214    options: TextOptions,
215) -> Result<TextResponse> {
216    socket::collect_text(generate_text(authorization, model, options).await?).await
217}
218
219/// The `options` argument of the agent's `generate_voice` and `generate_voice_sync`.
220#[derive(Default)]
221pub struct VoiceOptions {
222    pub content: Option<Vec<Content>>,
223    pub audio: Option<BoxStream<'static, Vec<u8>>>,
224    pub notes: Option<BoxStream<'static, String>>,
225    pub tools: Option<ToolsOrTool>,
226    pub max_tools: Option<u32>,
227    pub voice: Option<PartialDemographic>,
228    pub memories: Option<u32>,
229    pub group: Option<Group>,
230}
231
232/// Realtime voice: PCM16 16 kHz in from `audio`, PCM16 24 kHz out as audio events. Each of
233/// `notes` tells the model something to act on now.
234pub async fn generate_voice(
235    authorization: &CredentialsOrApiKey,
236    model: Voice,
237    options: VoiceOptions,
238) -> Result<BoxStream<'static, VoiceEvent>> {
239    socket::stream_voice(
240        authorization,
241        "/agent/voice",
242        model.as_str(),
243        socket::VoiceOptions {
244            content: options.content,
245            audio: options.audio,
246            notes: options.notes,
247            tools: options.tools,
248            max_tools: options.max_tools,
249            voice: options.voice,
250            memories: options.memories,
251            group: options.group,
252        },
253    )
254    .await
255}
256
257pub async fn generate_voice_sync(
258    authorization: &CredentialsOrApiKey,
259    model: Voice,
260    options: VoiceOptions,
261) -> Result<TextResponse> {
262    socket::collect_voice(
263        authorization,
264        generate_voice(authorization, model, options).await?,
265    )
266    .await
267}
268
269/// The `options` argument of the agent's `generate_image`.
270#[derive(Debug, Clone, Default)]
271pub struct ImageOptions {
272    pub content: Option<Vec<Content>>,
273    pub size: Option<[u32; 2]>,
274    pub memories: Option<u32>,
275    pub group: Option<Group>,
276}
277
278pub async fn generate_image(
279    authorization: &CredentialsOrApiKey,
280    model: Image,
281    options: ImageOptions,
282) -> Result<TextResponse> {
283    let mut extra = Map::new();
284    if let Some(size) = options.size {
285        extra.insert("size".to_string(), json!(size));
286    }
287    if let Some(memories) = options.memories {
288        extra.insert("memories".to_string(), Value::from(memories));
289    }
290    socket::generate_media(
291        authorization,
292        "/agent/image",
293        model.as_str(),
294        options.content,
295        options.group,
296        extra,
297        "image/png",
298    )
299    .await
300}
301
302/// The `options` argument of the agent's `generate_video`.
303#[derive(Debug, Clone, Default)]
304pub struct VideoOptions {
305    pub content: Option<Vec<Content>>,
306    pub duration: Option<f64>,
307    pub size: Option<[u32; 2]>,
308    pub memories: Option<u32>,
309    pub group: Option<Group>,
310}
311
312pub async fn generate_video(
313    authorization: &CredentialsOrApiKey,
314    model: Video,
315    options: VideoOptions,
316) -> Result<TextResponse> {
317    let mut extra = Map::new();
318    if let Some(duration) = options.duration {
319        extra.insert("duration".to_string(), Value::from(duration));
320    }
321    if let Some(size) = options.size {
322        extra.insert("size".to_string(), json!(size));
323    }
324    if let Some(memories) = options.memories {
325        extra.insert("memories".to_string(), Value::from(memories));
326    }
327    socket::generate_media(
328        authorization,
329        "/agent/video",
330        model.as_str(),
331        options.content,
332        options.group,
333        extra,
334        "video/mp4",
335    )
336    .await
337}