Skip to content

Commit 12bb2d2

Browse files
committed
refactor: refactor agent input & output
1 parent 710b793 commit 12bb2d2

File tree

34 files changed

+1214
-2127
lines changed

34 files changed

+1214
-2127
lines changed

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ members = [
1212
]
1313

1414
[workspace.package]
15+
version = "0.8.0"
1516
description = "Anda is an AI agent framework built with Rust, powered by ICP and TEEs."
1617
repository = "https://github.com/ldclabs/anda"
1718
homepage = "https://github.com/ldclabs/anda"

agents/anda_assistant/Cargo.toml

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,15 @@ name = "anda_assistant"
33
description = "Anda -- an AI Assistant powered by the Knowledge Interaction Protocol (KIP)."
44
repository = "https://github.com/ldclabs/anda/tree/main/agents/anda_assistant"
55
publish = true
6-
version = "0.2.9"
6+
version = "0.3.0"
77
edition.workspace = true
88
keywords.workspace = true
99
categories.workspace = true
1010
license.workspace = true
1111

1212
[dependencies]
13-
anda_core = { path = "../../anda_core", version = "0.7" }
14-
anda_engine = { path = "../../anda_engine", version = "0.7" }
13+
anda_core = { path = "../../anda_core", version = "0.8" }
14+
anda_engine = { path = "../../anda_engine", version = "0.8" }
1515
anda_cognitive_nexus = { workspace = true }
1616
anda_db = { workspace = true }
1717
anda_kip = { workspace = true }

agents/anda_assistant/src/agent.rs

Lines changed: 31 additions & 71 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use anda_cognitive_nexus::{CognitiveNexus, ConceptPK};
22
use anda_core::{
3-
Agent, AgentContext, AgentOutput, BoxError, CompletionRequest, Document, Documents, Json,
3+
Agent, AgentContext, AgentOutput, BoxError, CompletionRequest, Document, Documents,
44
Message, Principal, Resource, StateFeatures, Tool, ToolSet, Usage, evaluate_tokens,
55
update_resources,
66
};
@@ -9,12 +9,11 @@ use anda_engine::{
99
ANONYMOUS,
1010
context::{AgentCtx, BaseCtx},
1111
extension::fetch::FetchWebResourcesTool,
12-
json_set_unix_ms_timestamp,
1312
memory::{
1413
Conversation, ConversationRef, ConversationState, ConversationStatus,
1514
GetResourceContentTool, ListConversationsTool, MemoryManagement, SearchConversationsTool,
1615
},
17-
rfc3339_datetime_now, unix_ms,
16+
rfc3339_datetime, unix_ms,
1817
};
1918
use anda_kip::{
2019
META_SELF_NAME, PERSON_SELF_KIP, PERSON_SYSTEM_KIP, PERSON_TYPE, SYSTEM_INSTRUCTIONS, parse_kml,
@@ -207,7 +206,7 @@ impl Agent<AgentCtx> for Assistant {
207206

208207
let created_at = unix_ms();
209208
let primer = self.memory.describe_primer().await?;
210-
let system = format!(
209+
let instructions = format!(
211210
"{}\n---\n# Your Identity & Knowledge Domain Map\n{}\n",
212211
SYSTEM_INSTRUCTIONS, primer
213212
);
@@ -217,7 +216,7 @@ impl Agent<AgentCtx> for Assistant {
217216
.list_conversations_by_user(caller, None, Some(7))
218217
.await?;
219218
let max_history_bytes = self.max_input_tokens.saturating_sub(
220-
((evaluate_tokens(&system) + evaluate_tokens(&prompt)) as f64 * 1.2) as usize,
219+
((evaluate_tokens(&instructions) + evaluate_tokens(&prompt)) as f64 * 1.2) as usize,
221220
) * 3; // Rough estimate of bytes per token
222221
let mut writer: Vec<u8> = Vec::with_capacity(256);
223222
let _ = serde_json::to_writer(&mut writer, &conversations);
@@ -234,7 +233,7 @@ impl Agent<AgentCtx> for Assistant {
234233
history_docs.push(Document {
235234
content: caller_info,
236235
metadata: BTreeMap::from([
237-
("_type".to_string(), "User".into()),
236+
("type".to_string(), "User".into()),
238237
("description".to_string(), "User identity".into()),
239238
]),
240239
});
@@ -243,7 +242,7 @@ impl Agent<AgentCtx> for Assistant {
243242
history_docs.push(Document {
244243
content: cursor.into(),
245244
metadata: BTreeMap::from([
246-
("_type".to_string(), "Cursor".into()),
245+
("type".to_string(), "Cursor".into()),
247246
(
248247
"description".to_string(),
249248
"List previous conversations with this cursor".into(),
@@ -252,18 +251,21 @@ impl Agent<AgentCtx> for Assistant {
252251
})
253252
}
254253

255-
let mut chat_history: Vec<Json> = vec![];
256-
chat_history.push(serde_json::json!(Message {
254+
let mut chat_history: Vec<Message> = vec![];
255+
chat_history.push(Message {
257256
role: "user".into(),
258-
content: format!(
259-
"Current Datetime: {}\n---\n{}",
260-
rfc3339_datetime_now(),
261-
Documents::new("history".to_string(), history_docs)
262-
)
263-
.into(),
257+
content: vec![
258+
format!(
259+
"Current Datetime: {}\n---\n{}",
260+
rfc3339_datetime(created_at).unwrap(),
261+
Documents::new("history".to_string(), history_docs)
262+
)
263+
.into(),
264+
],
264265
name: Some("$system".into()),
266+
timestamp: Some(created_at),
265267
..Default::default()
266-
}));
268+
});
267269

268270
let resources = update_resources(caller, resources);
269271
let rs = self.memory.try_add_resources(&resources).await?;
@@ -273,17 +275,16 @@ impl Agent<AgentCtx> for Assistant {
273275
_id: 0,
274276
user: *caller,
275277
thread: None,
276-
messages: json_set_unix_ms_timestamp(
277-
vec![serde_json::json!(Message {
278-
role: "user".into(),
279-
content: prompt.clone().into(),
280-
..Default::default()
281-
})],
282-
created_at,
283-
),
278+
messages: vec![serde_json::json!(Message {
279+
role: "user".into(),
280+
content: vec![prompt.clone().into()],
281+
timestamp: Some(created_at),
282+
..Default::default()
283+
})],
284284
resources: rs,
285285
artifacts: vec![],
286286
status: ConversationStatus::Submitted,
287+
failed_reason: None,
287288
period: created_at / 3600 / 1000,
288289
created_at,
289290
updated_at: created_at,
@@ -304,7 +305,7 @@ impl Agent<AgentCtx> for Assistant {
304305
let assistant = self.clone();
305306
let mut runner = ctx.completion_iter(
306307
CompletionRequest {
307-
system,
308+
instructions,
308309
prompt,
309310
chat_history,
310311
documents: Documents::new("resources".to_string(), resource_docs),
@@ -330,18 +331,11 @@ impl Agent<AgentCtx> for Assistant {
330331

331332
if first_round {
332333
first_round = false;
333-
let response = res.full_history.pop().ok_or(
334-
"No response message in the first round of completion",
335-
)?;
336334
conversation.messages.clear(); // clear the first pending message.
337-
conversation
338-
.append_messages(clear_messages(res.full_history), created_at);
339-
conversation
340-
.append_messages(clear_messages(vec![response]), now_ms);
335+
conversation.append_messages(res.chat_history);
341336
} else {
342-
res.full_history.drain(0..conversation.messages.len());
343-
conversation
344-
.append_messages(clear_messages(res.full_history), now_ms);
337+
res.chat_history.drain(0..conversation.messages.len());
338+
conversation.append_messages(res.chat_history);
345339
}
346340

347341
conversation.artifacts = artifacts;
@@ -356,15 +350,7 @@ impl Agent<AgentCtx> for Assistant {
356350
conversation.updated_at = now_ms;
357351

358352
if let Some(failed_reason) = res.failed_reason {
359-
conversation.append_messages(
360-
vec![serde_json::json!(Message {
361-
role: "assistant".into(),
362-
content: failed_reason.into(),
363-
name: Some("$system".into()),
364-
..Default::default()
365-
})],
366-
now_ms,
367-
);
353+
conversation.failed_reason = Some(failed_reason);
368354
}
369355

370356
let old = assistant.memory.get_conversation(conversation._id).await?;
@@ -391,16 +377,7 @@ impl Agent<AgentCtx> for Assistant {
391377
Err(err) => {
392378
log::error!("Conversation {id} in CompletionRunner error: {:?}", err);
393379
let now_ms = unix_ms();
394-
conversation.append_messages(
395-
vec![serde_json::json!(Message {
396-
role: "assistant".into(),
397-
content: err.to_string().into(),
398-
name: Some("$system_warning".into()),
399-
..Default::default()
400-
})],
401-
now_ms,
402-
);
403-
380+
conversation.failed_reason = Some(err.to_string());
404381
conversation.status = ConversationStatus::Failed;
405382
conversation.updated_at = now_ms;
406383
let _ = assistant
@@ -428,20 +405,3 @@ impl Agent<AgentCtx> for Assistant {
428405
Ok(res)
429406
}
430407
}
431-
432-
// clear Gemini's messages
433-
fn clear_messages(mut messages: Vec<Json>) -> Vec<Json> {
434-
for msg in messages.iter_mut() {
435-
if let Some(content) = msg.get_mut("content")
436-
&& let Some(parts) = content.as_array_mut()
437-
{
438-
for part in parts.iter_mut() {
439-
if let Some(part) = part.as_object_mut() {
440-
part.remove("thoughtSignature"); // thoughtSignature is verbose
441-
}
442-
}
443-
}
444-
}
445-
446-
messages
447-
}

agents/anda_bot/Cargo.toml

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,18 +3,18 @@ name = "anda_bot"
33
description = "I'm Anda ICP, Digital panda 🐼 by Anda framework. Secured in TEE, memories on ICP chain.✨"
44
repository = "https://github.com/ldclabs/anda/tree/main/agents/anda_bot"
55
publish = false
6-
version = "0.7.0"
6+
version = "0.8.0"
77
edition.workspace = true
88
keywords.workspace = true
99
categories.workspace = true
1010
license.workspace = true
1111

1212
[dependencies]
13-
anda_core = { path = "../../anda_core", version = "0.7" }
14-
anda_engine = { path = "../../anda_engine", version = "0.7" }
15-
anda_web3_client = { path = "../../anda_web3_client", version = "0.7" }
16-
anda_icp = { path = "../../tools/anda_icp", version = "0.7" }
17-
anda_engine_server = { path = "../../anda_engine_server", version = "0.7" }
13+
anda_core = { path = "../../anda_core", version = "0.8" }
14+
anda_engine = { path = "../../anda_engine", version = "0.8" }
15+
anda_web3_client = { path = "../../anda_web3_client", version = "0.8" }
16+
anda_icp = { path = "../../tools/anda_icp", version = "0.8" }
17+
anda_engine_server = { path = "../../anda_engine_server", version = "0.8" }
1818
anda_object_store = { workspace = true }
1919
axum = { workspace = true }
2020
config = { workspace = true }

agents/anda_bot/README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# `anda_bot` [WIP]
1+
# `anda_bot` [TODO: refactor]
22

33
`anda_bot` is an AI bot developed using the Anda framework, featuring:
44
1. Runs in a TEE (Trusted Execution Environment) to ensure security and privacy

0 commit comments

Comments
 (0)