1use std::collections::{HashMap, VecDeque};
2use std::ops::Deref;
3use std::sync::atomic::{AtomicU64, Ordering};
4use std::sync::{Arc, Mutex, MutexGuard, PoisonError, Weak};
5
6use chrono::{DateTime, Utc};
7use futures_util::stream::{self, BoxStream};
8use futures_util::{SinkExt, StreamExt};
9use serde::{Deserialize, Serialize};
10use serde_json::{Map, Value, json};
11use tokio::sync::mpsc;
12use tokio_tungstenite::tungstenite::Message;
13
14use super::persona::Identity;
15use crate::authentification::{CredentialsOrApiKey, Profile};
16use crate::drive::{self, FileDates};
17use crate::error::{Error, Result};
18use crate::groups::Group;
19use crate::http::{client, encode, ok, websocket};
20use crate::parrot::agent::Memory;
21use crate::parrot::generative::{Content, Part, StreamEvent, Tool, file_ref};
22use crate::parrot::room::{ChatRoom as ParrotChatRoom, RoomHooks, connect_room};
23use crate::parrot::share::ChatTarget;
24use crate::shared::server::{Authorization, Hooks, Presence, Room, connect as connect_server};
25use crate::termite::versioning::Repository;
26
27pub(crate) async fn serialize_messages(
30 authorization: &CredentialsOrApiKey,
31 messages: &[Content],
32) -> Result<Vec<Value>> {
33 let mut out = Vec::with_capacity(messages.len());
34 for message in messages {
35 let mut parts = Vec::with_capacity(message.parts.len());
36 for part in &message.parts {
37 match part {
38 Part::File(part) if !part.file.online() => {
39 let file = &part.file;
40 let dest = format!("tmp/{}-{}", uuid::Uuid::new_v4(), file.name());
41 let bytes = file.clone().download(false, None).await?;
42 let mut ready = drive::from_bytes(
43 authorization.clone(),
44 &dest,
45 &file.content_type,
46 bytes,
47 FileDates::default(),
48 );
49 ready.upload(None).await?;
50 parts.push(file_ref(&ready));
51 }
52 part => parts.push(part.wire()),
53 }
54 }
55 out.push(json!({ "parts": parts, "role": message.role }));
56 }
57 Ok(out)
58}
59
60pub(crate) async fn agent_stream(
63 url: String,
64 generate: Value,
65 tools: Vec<Tool>,
66) -> Result<BoxStream<'static, StreamEvent>> {
67 let socket = match tokio_tungstenite::connect_async(url.as_str()).await {
68 Ok((socket, _)) => socket,
69 Err(_) => return Err(Error::Message("WebSocket connection failed".to_string())),
70 };
71 let (mut write, read) = socket.split();
72 write.send(Message::text(generate.to_string())).await?;
73 write
74 .send(Message::text(json!({ "event": "start" }).to_string()))
75 .await?;
76 let (outbox, mut queue) = mpsc::unbounded_channel::<Message>();
77 tokio::spawn(async move {
78 while let Some(message) = queue.recv().await {
79 if write.send(message).await.is_err() {
80 break;
81 }
82 }
83 let _ = write.close().await;
84 });
85
86 let state = (read, outbox, tools, VecDeque::<StreamEvent>::new(), false);
87 Ok(stream::unfold(state, |(mut read, outbox, tools, mut queue, finished)| async move {
88 if finished {
89 return None;
90 }
91 loop {
92 if let Some(event) = queue.pop_front() {
93 let finished = matches!(event, StreamEvent::Done { .. } | StreamEvent::Error { .. });
94 return Some((event, (read, outbox, tools, queue, finished)));
95 }
96 match read.next().await {
97 Some(Ok(Message::Text(raw))) => {
98 let Ok(packet) = serde_json::from_str::<Value>(raw.as_str()) else {
99 continue;
100 };
101 if packet["event"] == "tool_call" {
102 let tool = tools
103 .iter()
104 .find(|tool| packet["name"].as_str() == Some(tool.function.name.as_str()))
105 .cloned();
106 let outbox = outbox.clone();
107 tokio::spawn(async move {
108 let declined = json!({ "declined": true }).to_string();
109 let result = match tool {
110 Some(tool) => {
111 let args = match &packet["args"] {
112 Value::Object(args) => Value::Object(args.clone()),
113 _ => json!({}),
114 };
115 (tool.evaluate)(args).await.unwrap_or(declined)
116 }
117 None => declined,
118 };
119 let _ = outbox.send(Message::text(
120 json!({ "event": "tool_result", "id": packet["id"], "result": result }).to_string(),
121 ));
122 });
123 continue;
124 }
125 if let Ok(event) = serde_json::from_value::<StreamEvent>(packet) {
126 queue.push_back(event);
127 }
128 }
129 Some(Ok(Message::Close(_))) | Some(Err(_)) | None => return None,
130 Some(Ok(_)) => {}
131 }
132 }
133 })
134 .boxed())
135}
136
137#[derive(Debug, Clone, Serialize, Deserialize)]
138#[serde(rename_all = "camelCase")]
139pub struct ChatLast {
140 #[serde(default)]
141 pub parts: Vec<Value>,
142 pub role: String,
143 #[serde(
144 deserialize_with = "crate::http::deserialize_date",
145 serialize_with = "crate::http::serialize_date"
146 )]
147 pub created_at: DateTime<Utc>,
148 pub position: u32,
149 #[serde(default, skip_serializing_if = "Option::is_none")]
150 pub author: Option<Profile>,
151 #[serde(default, skip_serializing_if = "Option::is_none")]
152 pub model: Option<String>,
153}
154
155#[derive(Debug, Clone, Serialize, Deserialize)]
157pub struct ChatEntry {
158 pub name: String,
159 pub id: String,
160 #[serde(default)]
161 pub last: Option<ChatLast>,
162}
163
164#[derive(Debug, Clone, Default)]
166pub struct GroupOptions {
167 pub group: Option<Group>,
168}
169
170fn authorized(
171 request: reqwest::RequestBuilder,
172 authorization: &CredentialsOrApiKey,
173 group: Option<&Group>,
174) -> reqwest::RequestBuilder {
175 let request = request.header(
176 "Authorization",
177 match authorization {
178 CredentialsOrApiKey::Credentials(credentials) => format!("Token {}", credentials.token),
179 CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
180 },
181 );
182 match group {
183 Some(group) => request.header("Group", &group.id),
184 None => request,
185 }
186}
187
188pub async fn list_chats(
189 authorization: &CredentialsOrApiKey,
190 opts: GroupOptions,
191) -> Result<Vec<ChatEntry>> {
192 let response = authorized(
193 client().get(format!("{}/chats", super::get_url())),
194 authorization,
195 opts.group.as_ref(),
196 )
197 .send()
198 .await?;
199 let rows: Value = ok(response).await?.json().await?;
200 Ok(rows
201 .as_array()
202 .into_iter()
203 .flatten()
204 .filter_map(|row| serde_json::from_value(row.clone()).ok())
205 .collect())
206}
207
208#[derive(Debug, Clone, Default)]
210pub struct CreateChatOptions {
211 pub group: Option<Group>,
212 pub audience: Option<Vec<String>>,
213 pub repository: Option<Repository>,
214}
215
216#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
218pub struct CreatedChat {
219 pub name: String,
220 pub id: String,
221}
222
223pub async fn create_chat(
225 authorization: &CredentialsOrApiKey,
226 name: &str,
227 opts: CreateChatOptions,
228) -> Result<CreatedChat> {
229 let mut body = Map::new();
230 body.insert("name".to_string(), Value::from(name));
231 if let Some(audience) = opts.audience.filter(|audience| !audience.is_empty()) {
232 body.insert("audience".to_string(), json!(audience));
233 }
234 if let Some(repository) = &opts.repository {
235 body.insert("repository".to_string(), Value::from(repository.id));
236 }
237 let response = authorized(
238 client().post(format!("{}/chats", super::get_url())),
239 authorization,
240 opts.group.as_ref(),
241 )
242 .json(&body)
243 .send()
244 .await?;
245 Ok(ok(response).await?.json().await?)
246}
247
248pub async fn delete_chat(
249 authorization: &CredentialsOrApiKey,
250 id: &str,
251 opts: GroupOptions,
252) -> Result<()> {
253 let response = authorized(
254 client().delete(format!("{}/chat", super::get_url())),
255 authorization,
256 opts.group.as_ref(),
257 )
258 .header("Chat", id)
259 .send()
260 .await?;
261 ok(response).await?;
262 Ok(())
263}
264
265#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
267#[serde(rename_all = "camelCase")]
268pub struct MovedChat {
269 pub id: String,
270 pub name: String,
271 pub group_id: String,
272 pub remapped: bool,
273}
274
275pub async fn move_chat_to_group(
276 authorization: &CredentialsOrApiKey,
277 id: &str,
278 group_id: &str,
279) -> Result<MovedChat> {
280 let response = authorized(
281 client().post(format!("{}/chat/move", super::get_url())),
282 authorization,
283 None,
284 )
285 .header("Chat", id)
286 .json(&json!({ "groupId": group_id }))
287 .send()
288 .await?;
289 Ok(ok(response).await?.json().await?)
290}
291
292pub async fn rename_chat(
293 authorization: &CredentialsOrApiKey,
294 id: &str,
295 name: &str,
296 opts: GroupOptions,
297) -> Result<()> {
298 let response = authorized(
299 client().post(format!("{}/chat/rename", super::get_url())),
300 authorization,
301 opts.group.as_ref(),
302 )
303 .header("Chat", id)
304 .json(&json!({ "name": name }))
305 .send()
306 .await?;
307 ok(response).await?;
308 Ok(())
309}
310
311#[derive(Debug, Clone, Default)]
313pub struct AgentGenerateOptions {
314 pub tools: Option<Vec<Tool>>,
315}
316
317#[derive(Clone)]
318pub struct Agent {
319 room: Room,
320 parent: Weak<AntChatState>,
321 pub id: String,
322 pub persona: Identity,
323 pub repository: Option<u64>,
325}
326
327impl Agent {
328 pub fn parent(&self) -> Option<AntChatRoom> {
329 self.parent.upgrade().map(|state| AntChatRoom {
330 room: self.room.clone(),
331 state,
332 })
333 }
334
335 pub fn set_repository(&self, repository: Option<&Repository>) {
337 self.room.post(&json!({
338 "event": "set-agent-repository",
339 "agentId": self.id,
340 "repository": repository.map(|repository| repository.id),
341 }));
342 }
343
344 fn chat_id(&self) -> String {
345 self.parent().map(|room| room.chat_id()).unwrap_or_default()
346 }
347
348 fn access(&self) -> (Option<Group>, Option<String>) {
349 match self.room.authorization() {
350 Authorization::AccessCode { access_code, .. } => (None, Some(access_code.clone())),
351 Authorization::Server { group, .. } => (
352 group
353 .as_ref()
354 .map(|group| Group::from_json(&json!({ "id": group }))),
355 None,
356 ),
357 }
358 }
359
360 pub async fn observe(&self, content: &str) -> Result<Memory> {
361 let (group, access_code) = self.access();
362 observe_agent(
363 self.room.get_authorization(),
364 &self.chat_id(),
365 &self.id,
366 content,
367 AgentOptions { group, access_code },
368 )
369 .await
370 }
371
372 pub async fn generate(
374 &self,
375 messages: &[Content],
376 opts: AgentGenerateOptions,
377 ) -> Result<BoxStream<'static, StreamEvent>> {
378 let (group, access_code) = self.access();
379 generate_agent(
380 self.room.get_authorization(),
381 &self.chat_id(),
382 &self.id,
383 messages,
384 GenerateOptions {
385 group,
386 access_code,
387 tools: opts.tools,
388 },
389 )
390 .await
391 }
392
393 pub fn to_json(&self) -> Value {
394 json!({ "id": self.id, "persona": self.persona })
395 }
396
397 pub fn from_json(json: &Value, parent: &AntChatRoom) -> Option<Agent> {
398 Some(Agent {
399 room: parent.room.clone(),
400 parent: Arc::downgrade(&parent.state),
401 id: match &json["id"] {
402 Value::String(id) => id.clone(),
403 id => id.to_string(),
404 },
405 persona: serde_json::from_value(json["persona"].clone()).ok()?,
406 repository: json["repository"]
407 .as_f64()
408 .filter(|repository| *repository > 0.0)
409 .map(|repository| repository as u64),
410 })
411 }
412}
413
414type RepositoryWatcher = Arc<dyn Fn(Option<u64>) + Send + Sync>;
415
416#[derive(Default)]
417struct AntChat {
418 chat_id: String,
419 name: String,
420 agents: HashMap<String, Agent>,
421 repository: Option<u64>,
422 owner: String,
423}
424
425struct AntChatState {
426 chat: Mutex<AntChat>,
427 watchers: Mutex<Vec<(u64, RepositoryWatcher)>>,
428 next_watcher: AtomicU64,
429}
430
431fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
432 mutex.lock().unwrap_or_else(PoisonError::into_inner)
433}
434
435#[derive(Clone)]
437pub struct ArchitectChat {
438 pub room: ParrotChatRoom,
439 pub me: Presence,
440 pub chat_id: String,
441}
442
443#[derive(Default)]
446pub struct ConnectOptions {
447 pub group: Option<Group>,
448 pub hooks: Option<Arc<dyn Hooks>>,
449 pub server: Option<String>,
450}
451
452#[derive(Clone)]
453pub struct AntChatRoom {
454 room: Room,
455 state: Arc<AntChatState>,
456}
457
458pub use self::AntChatRoom as ChatRoom;
459
460impl Deref for AntChatRoom {
461 type Target = Room;
462 fn deref(&self) -> &Room {
463 &self.room
464 }
465}
466
467fn positive(value: &Value) -> Option<u64> {
468 value
469 .as_f64()
470 .filter(|repository| *repository > 0.0)
471 .map(|repository| repository as u64)
472}
473
474impl AntChatRoom {
475 fn chat(&self) -> MutexGuard<'_, AntChat> {
476 lock(&self.state.chat)
477 }
478
479 pub fn chat_id(&self) -> String {
480 self.chat().chat_id.clone()
481 }
482
483 pub fn name(&self) -> String {
484 self.chat().name.clone()
485 }
486
487 pub fn agents(&self) -> HashMap<String, Agent> {
488 self.chat().agents.clone()
489 }
490
491 pub fn repository(&self) -> Option<u64> {
493 self.chat().repository
494 }
495
496 pub fn owner(&self) -> String {
498 self.chat().owner.clone()
499 }
500
501 pub fn group(&self) -> Option<Group> {
503 let owner = self.owner();
504 owner
505 .strip_prefix("group:")
506 .filter(|id| !id.is_empty() && id.bytes().all(|byte| byte.is_ascii_digit()))
507 .map(|id| Group::from_json(&json!({ "id": id })))
508 }
509
510 pub async fn set_repository(&self, repository: Option<&Repository>) -> Result<()> {
512 self.post(&json!({ "event": "set-repository", "repository": repository.map(|repository| repository.id) }));
513 Ok(())
514 }
515
516 pub fn watch_repository(
518 &self,
519 listener: impl Fn(Option<u64>) + Send + Sync + 'static,
520 ) -> Box<dyn FnOnce() + Send + Sync> {
521 let id = self.state.next_watcher.fetch_add(1, Ordering::Relaxed);
522 lock(&self.state.watchers).push((id, Arc::new(listener)));
523 let state = Arc::downgrade(&self.state);
524 Box::new(move || {
525 if let Some(state) = state.upgrade() {
526 lock(&state.watchers).retain(|(other, _)| *other != id);
527 }
528 })
529 }
530
531 fn apply_repository(&self, raw: &Value) {
532 let repository = positive(raw);
533 {
534 let mut chat = self.chat();
535 if chat.repository == repository {
536 return;
537 }
538 chat.repository = repository;
539 }
540 let watchers: Vec<RepositoryWatcher> = lock(&self.state.watchers)
541 .iter()
542 .map(|(_, listener)| listener.clone())
543 .collect();
544 for listener in watchers {
545 listener(repository);
546 }
547 }
548
549 pub fn hydrate(&self, state: &Value) {
550 {
551 let mut chat = self.chat();
552 if let Some(id) = state["id"].as_str() {
553 chat.chat_id = id.to_string();
554 }
555 if let Some(name) = state["name"].as_str() {
556 chat.name = name.to_string();
557 }
558 if let Some(owner) = state["owner"].as_str() {
559 chat.owner = owner.to_string();
560 }
561 }
562 self.apply_repository(&state["repository"]);
563 let agents: HashMap<String, Agent> = state["agents"]
564 .as_array()
565 .into_iter()
566 .flatten()
567 .filter_map(|agent| Agent::from_json(agent, self))
568 .map(|agent| (agent.id.clone(), agent))
569 .collect();
570 self.chat().agents = agents;
571 }
572
573 pub fn handle_event(&self, packet: &Value) -> bool {
574 let pick = |key: &str| {
575 if packet["data"][key].is_null() {
576 &packet[key]
577 } else {
578 &packet["data"][key]
579 }
580 };
581 match packet["event"].as_str().unwrap_or_default() {
582 "upsert-agent" => {
583 if let Some(agent) = Agent::from_json(pick("agent"), self) {
584 self.chat().agents.insert(agent.id.clone(), agent);
585 }
586 true
587 }
588 "remove-agent" => {
589 let id = match pick("id") {
590 Value::Null => String::new(),
591 Value::String(id) => id.clone(),
592 id => id.to_string(),
593 };
594 if !id.is_empty() {
595 self.chat().agents.remove(&id);
596 }
597 true
598 }
599 "update-chat" => {
600 let chat = pick("chat");
601 if let Some(name) = chat["name"].as_str() {
602 self.chat().name = name.to_string();
603 }
604 if chat.get("repository").is_some() {
605 self.apply_repository(&chat["repository"]);
606 }
607 true
608 }
609 _ => false,
610 }
611 }
612
613 pub fn upsert_agent(&self, identity: Identity) -> Agent {
614 let agent = {
615 let mut chat = self.chat();
616 let preferred = identity.id.trim().to_string();
617 let id = if !preferred.is_empty() && !chat.agents.contains_key(&preferred) {
618 preferred
619 } else {
620 let mut n = 0;
621 while chat.agents.contains_key(&n.to_string()) {
622 n += 1;
623 }
624 n.to_string()
625 };
626 let agent = Agent {
627 room: self.room.clone(),
628 parent: Arc::downgrade(&self.state),
629 id,
630 persona: identity,
631 repository: None,
632 };
633 chat.agents.insert(agent.id.clone(), agent.clone());
634 agent
635 };
636 self.post(&json!({ "event": "upsert-agent", "agent": agent.to_json() }));
637 agent
638 }
639
640 pub fn remove_agent(&self, id: &str) {
641 self.chat().agents.remove(id);
642 self.post(&json!({ "event": "remove-agent", "id": id }));
643 }
644
645 pub async fn get_chat(&self, hooks: Option<Arc<dyn RoomHooks>>) -> Result<ArchitectChat> {
647 let authorization = self.get_authorization();
648 let request = authorized(
649 client().post(format!("{}/chat/ensure", super::get_url())),
650 authorization,
651 None,
652 );
653 let request = match self.authorization() {
654 Authorization::AccessCode { access_code, .. } => {
655 request.header("Access-Code", access_code)
656 }
657 Authorization::Server { group, .. } => {
658 let request = request.header("Chat", self.chat_id());
659 match group {
660 Some(group) => request.header("Group", group),
661 None => request,
662 }
663 }
664 };
665 let json: Value = ok(request.json(&json!({})).send().await?)
666 .await?
667 .json()
668 .await?;
669 let chat_id = json["chatId"].as_str().unwrap_or_default().to_string();
670 let code = json["code"].as_str().unwrap_or_default().to_string();
671 if chat_id.is_empty() || code.is_empty() {
672 return Err(Error::Message("Invalid ensure response.".to_string()));
673 }
674 let target = match self.authorization() {
675 Authorization::AccessCode { .. } => ChatTarget::Code { code },
676 Authorization::Server { .. } => ChatTarget::Reference {
677 reference: json["reference"]
678 .as_str()
679 .filter(|reference| !reference.is_empty())
680 .map(str::to_string)
681 .unwrap_or_else(|| format!("parrot:chat:{chat_id}")),
682 },
683 };
684 let (room, me) = connect_room(authorization, &target, hooks).await?;
685 Ok(ArchitectChat { room, me, chat_id })
686 }
687
688 pub async fn connect(
689 authorization: &CredentialsOrApiKey,
690 target_id: &str,
691 opts: ConnectOptions,
692 ) -> Result<(AntChatRoom, Presence)> {
693 AntChatRoom::open(
694 Authorization::Server {
695 authorization: authorization.clone(),
696 server: opts.server.unwrap_or_else(|| target_id.to_string()),
697 group: opts.group.as_ref().map(|group| group.id.clone()),
698 },
699 opts.hooks,
700 )
701 .await
702 }
703
704 pub async fn join(
705 authorization: &CredentialsOrApiKey,
706 access_code: &str,
707 hooks: Option<Arc<dyn Hooks>>,
708 ) -> Result<(AntChatRoom, Presence)> {
709 AntChatRoom::open(
710 Authorization::AccessCode {
711 authorization: authorization.clone(),
712 access_code: access_code.to_string(),
713 },
714 hooks,
715 )
716 .await
717 }
718
719 async fn open(
720 auth: Authorization,
721 hooks: Option<Arc<dyn Hooks>>,
722 ) -> Result<(AntChatRoom, Presence)> {
723 let state = Arc::new(AntChatState {
724 chat: Mutex::new(AntChat::default()),
725 watchers: Mutex::new(Vec::new()),
726 next_watcher: AtomicU64::new(0),
727 });
728 let me = connect_server(
729 auth,
730 &format!("{}/chat", super::get_url()),
731 Arc::new(AntChatHooks {
732 state: state.clone(),
733 user: hooks.unwrap_or_else(|| Arc::new(())),
734 }),
735 )
736 .await?;
737 Ok((
738 AntChatRoom {
739 room: me.room().clone(),
740 state,
741 },
742 me,
743 ))
744 }
745}
746
747struct AntChatHooks {
748 state: Arc<AntChatState>,
749 user: Arc<dyn Hooks>,
750}
751
752impl AntChatHooks {
753 fn room(&self, room: &Room) -> AntChatRoom {
754 AntChatRoom {
755 room: room.clone(),
756 state: self.state.clone(),
757 }
758 }
759}
760
761impl Hooks for AntChatHooks {
762 fn create_room(&self, room: &Room, state: &Value) {
763 lock(&self.state.chat).chat_id = room.id().to_string();
764 self.user.create_room(room, state);
765 }
766
767 fn create_presence(&self, room: &Room, presence: &Presence) {
768 self.user.create_presence(room, presence);
769 }
770
771 fn remove_presence(&self, room: &Room, presence: &Presence) {
772 self.user.remove_presence(room, presence);
773 }
774
775 fn on_connection(&self, room: &Room, state: &Value) {
776 self.room(room).hydrate(state);
777 self.user.on_connection(room, state);
778 }
779
780 fn on_event(&self, room: &Room, packet: &Value) -> bool {
781 let handled = self.room(room).handle_event(packet);
782 self.user.on_event(room, packet) || handled
783 }
784
785 fn on_presence(&self, room: &Room) {
786 self.user.on_presence(room);
787 }
788
789 fn on_closed(&self, room: &Room, reason: Option<&str>) {
790 self.user.on_closed(room, reason);
791 }
792}
793
794#[derive(Debug, Clone, Default)]
796pub struct AgentOptions {
797 pub group: Option<Group>,
798 pub access_code: Option<String>,
799}
800
801fn scoped(
802 request: reqwest::RequestBuilder,
803 chat_id: &str,
804 group: Option<&Group>,
805 access_code: Option<&str>,
806) -> reqwest::RequestBuilder {
807 match access_code.filter(|code| !code.is_empty()) {
808 Some(access_code) => request.header("Access-Code", access_code),
809 None => {
810 let request = request.header("Chat", chat_id);
811 match group {
812 Some(group) => request.header("Group", &group.id),
813 None => request,
814 }
815 }
816 }
817}
818
819pub async fn observe_agent(
821 authorization: &CredentialsOrApiKey,
822 chat_id: &str,
823 agent_id: &str,
824 content: &str,
825 opts: AgentOptions,
826) -> Result<Memory> {
827 let request = authorized(
828 client().post(format!("{}/chat/agent/observe", super::get_url())),
829 authorization,
830 None,
831 );
832 let response = scoped(
833 request,
834 chat_id,
835 opts.group.as_ref(),
836 opts.access_code.as_deref(),
837 )
838 .json(&json!({ "agentId": agent_id, "content": content }))
839 .send()
840 .await?;
841 Ok(ok(response).await?.json().await?)
842}
843
844#[derive(Debug, Clone, Default)]
846pub struct GenerateOptions {
847 pub group: Option<Group>,
848 pub access_code: Option<String>,
849 pub tools: Option<Vec<Tool>>,
850}
851
852pub(crate) fn socket_auth(
853 authorization: &CredentialsOrApiKey,
854 chat_header: (&str, &str),
855 group: Option<&Group>,
856 access_code: Option<&str>,
857) -> String {
858 let mut headers = Map::new();
859 headers.insert(
860 "Authorization".to_string(),
861 Value::from(match authorization {
862 CredentialsOrApiKey::Credentials(credentials) => format!("Token {}", credentials.token),
863 CredentialsOrApiKey::ApiKey(key) => format!("ApiKey {}", key.id),
864 }),
865 );
866 match access_code.filter(|code| !code.is_empty()) {
867 Some(access_code) => {
868 headers.insert("Access-Code".to_string(), Value::from(access_code));
869 }
870 None => {
871 headers.insert(chat_header.0.to_string(), Value::from(chat_header.1));
872 if let Some(group) = group {
873 headers.insert("Group".to_string(), Value::from(group.id.as_str()));
874 }
875 }
876 }
877 encode(&Value::Object(headers).to_string())
878}
879
880pub async fn generate_agent(
884 authorization: &CredentialsOrApiKey,
885 chat_id: &str,
886 agent_id: &str,
887 messages: &[Content],
888 opts: GenerateOptions,
889) -> Result<BoxStream<'static, StreamEvent>> {
890 let auth = socket_auth(
891 authorization,
892 ("Chat", chat_id),
893 opts.group.as_ref(),
894 opts.access_code.as_deref(),
895 );
896 let url = format!(
897 "{}/chat/agent/generate?authorization={auth}",
898 websocket(&super::get_url())
899 );
900 let tools = opts.tools.unwrap_or_default();
901 let messages = serialize_messages(authorization, messages).await?;
902 let functions: Vec<&crate::parrot::generative::Function> =
903 tools.iter().map(|tool| &tool.function).collect();
904 let generate = json!({ "event": "generate", "agentId": agent_id, "messages": messages, "tools": functions });
905 agent_stream(url, generate, tools).await
906}
907
908#[cfg(test)]
909mod tests {
910 use serde_json::{Value, json};
911 use tokio::sync::mpsc;
912
913 use super::*;
914 use crate::authentification::ApiKey;
915
916 fn persona(id: &str) -> Value {
917 json!({
918 "id": id, "background": "Nurse", "dialect": "Southern",
919 "demographic": {
920 "age": 30, "sex": "MALE", "race": "BLACK", "ethnicity": [], "religion": "CHRISTIAN",
921 "birthplace": [0, 0], "location": [0, 0], "marital": "MARRIED", "education": "BACHELOR",
922 "occupation": "nurse", "income": 60000
923 }
924 })
925 }
926
927 #[test]
928 fn ant_chat_rooms_track_agents_and_repository() {
929 let (ws, mut outbox) = mpsc::unbounded_channel();
930 let room = AntChatRoom {
931 room: Room::new(
932 "http://localhost/chat".to_string(),
933 ws,
934 Authorization::Server {
935 authorization: CredentialsOrApiKey::ApiKey(ApiKey::default()),
936 server: "c1".to_string(),
937 group: None,
938 },
939 "c1".to_string(),
940 ),
941 state: Arc::new(AntChatState {
942 chat: Mutex::new(AntChat::default()),
943 watchers: Mutex::new(Vec::new()),
944 next_watcher: AtomicU64::new(0),
945 }),
946 };
947 let seen = Arc::new(Mutex::new(Vec::new()));
948 let sink = seen.clone();
949 let _stop = room.watch_repository(move |repository| sink.lock().unwrap().push(repository));
950 room.hydrate(&json!({
951 "id": "c1", "name": "Panel", "owner": "group:5", "repository": 9,
952 "agents": [{ "id": "0", "persona": persona("p0"), "repository": 3 }, { "id": "bad" }]
953 }));
954 assert_eq!(room.group().unwrap().id, "5");
955 assert_eq!(room.agents().len(), 1);
956 assert_eq!(room.agents()["0"].repository, Some(3));
957 assert_eq!(room.agents()["0"].parent().unwrap().chat_id(), "c1");
958
959 let identity: Identity = serde_json::from_value(persona("0")).unwrap();
960 let agent = room.upsert_agent(identity);
961 assert_eq!(agent.id, "1");
962 let Some(Message::Text(frame)) = outbox.blocking_recv() else {
963 panic!("expected a frame");
964 };
965 assert_eq!(
966 serde_json::from_str::<Value>(frame.as_str()).unwrap()["event"],
967 "upsert-agent"
968 );
969
970 assert!(room.handle_event(&json!({ "event": "remove-agent", "data": { "id": "0" } })));
971 assert!(room.handle_event(
972 &json!({ "event": "update-chat", "chat": { "name": "Jury", "repository": null } })
973 ));
974 assert_eq!(room.agents().len(), 1);
975 assert_eq!(room.name(), "Jury");
976 assert_eq!(*seen.lock().unwrap(), vec![Some(9), None]);
977 }
978}