1use std::sync::Arc;
20
21use futures::future::{BoxFuture, ready};
22use gadk_agent::{
23 AfterAgentCallback, AfterModelCallback, AfterRunCallback, AfterToolCallback, AgentError,
24 BeforeAgentCallback, BeforeModelCallback, BeforeRunCallback, BeforeToolCallback, Context,
25 InvocationContext, OnEventCallback, OnModelErrorCallback, OnToolErrorCallback,
26 OnUserMessageCallback, Plugin, Tool, ToolError,
27};
28use gadk_genai::Content;
29use gadk_model::{LlmRequest, LlmResponse, ModelError};
30use gadk_session::Event;
31use serde_json::{Map, Value};
32
33const NAME: &str = "logging_plugin";
34
35type ContentResult = BoxFuture<'static, Result<Option<Content>, AgentError>>;
36type ResponseResult = BoxFuture<'static, Result<Option<LlmResponse>, AgentError>>;
37type MapResult = BoxFuture<'static, Result<Option<Map<String, Value>>, AgentError>>;
38type ArgsMapResult = BoxFuture<
39 'static,
40 (
41 Map<String, Value>,
42 Result<Option<Map<String, Value>>, AgentError>,
43 ),
44>;
45
46pub fn logging_plugin() -> Plugin {
49 let p = Arc::new(LoggingPlugin {
50 name: NAME.to_string(),
51 });
52 let on_user_message: OnUserMessageCallback = {
53 let p = p.clone();
54 Arc::new(
55 move |ctx: InvocationContext, msg: Content| -> ContentResult {
56 p.on_user_message(&ctx, &msg);
57 Box::pin(ready(Ok(None)))
58 },
59 )
60 };
61 let before_run: BeforeRunCallback = {
62 let p = p.clone();
63 Arc::new(move |ctx: InvocationContext| -> ContentResult {
64 p.before_run(&ctx);
65 Box::pin(ready(Ok(None)))
66 })
67 };
68 let on_event: OnEventCallback = {
69 let p = p.clone();
70 Arc::new(
71 move |_ctx: InvocationContext,
72 event: Event|
73 -> BoxFuture<'static, Result<Option<Event>, AgentError>> {
74 p.on_event(&event);
75 Box::pin(ready(Ok(None)))
76 },
77 )
78 };
79 let after_run: AfterRunCallback = {
80 let p = p.clone();
81 Arc::new(move |ctx: InvocationContext| -> BoxFuture<'static, ()> {
82 p.after_run(&ctx);
83 Box::pin(ready(()))
84 })
85 };
86 let before_agent: BeforeAgentCallback = {
87 let p = p.clone();
88 Arc::new(move |ctx: Context| -> ContentResult {
89 p.before_agent(&ctx);
90 Box::pin(ready(Ok(None)))
91 })
92 };
93 let after_agent: AfterAgentCallback = {
94 let p = p.clone();
95 Arc::new(move |ctx: Context| -> ContentResult {
96 p.after_agent(&ctx);
97 Box::pin(ready(Ok(None)))
98 })
99 };
100 let before_model: BeforeModelCallback = {
101 let p = p.clone();
102 Arc::new(
103 move |ctx: Context,
104 req: LlmRequest|
105 -> BoxFuture<'static, (LlmRequest, Result<Option<LlmResponse>, AgentError>)> {
106 p.before_model(&ctx, &req);
107 Box::pin(ready((req, Ok(None))))
108 },
109 )
110 };
111 let after_model: AfterModelCallback = {
112 let p = p.clone();
113 Arc::new(
114 move |ctx: Context,
115 resp: LlmResponse,
116 err: Option<Arc<ModelError>>|
117 -> BoxFuture<'static, (LlmResponse, Result<Option<LlmResponse>, AgentError>)> {
118 p.after_model(&ctx, &resp, err.as_deref());
119 Box::pin(ready((resp, Ok(None))))
120 },
121 )
122 };
123 let on_model_error: OnModelErrorCallback = {
124 let p = p.clone();
125 Arc::new(
126 move |ctx: Context, _req: LlmRequest, err: Arc<ModelError>| -> ResponseResult {
127 p.on_model_error(&ctx, &err);
128 Box::pin(ready(Ok(None)))
129 },
130 )
131 };
132 let before_tool: BeforeToolCallback = {
133 let p = p.clone();
134 Arc::new(
135 move |ctx: Context, tool: Arc<dyn Tool>, args: Map<String, Value>| -> ArgsMapResult {
136 p.before_tool(&ctx, &*tool, &args);
137 Box::pin(ready((args, Ok(None))))
138 },
139 )
140 };
141 let after_tool: AfterToolCallback = {
142 let p = p.clone();
143 Arc::new(
144 move |ctx: Context,
145 tool: Arc<dyn Tool>,
146 _args: Map<String, Value>,
147 result: Map<String, Value>,
148 err: Option<Arc<ToolError>>|
149 -> MapResult {
150 p.after_tool(&ctx, &*tool, &result, err.as_deref());
151 Box::pin(ready(Ok(None)))
152 },
153 )
154 };
155 let on_tool_error: OnToolErrorCallback = {
156 let p = p.clone();
157 Arc::new(
158 move |ctx: Context,
159 tool: Arc<dyn Tool>,
160 args: Map<String, Value>,
161 err: Arc<ToolError>|
162 -> MapResult {
163 p.on_tool_error(&ctx, &*tool, &args, &err);
164 Box::pin(ready(Ok(None)))
165 },
166 )
167 };
168 Plugin::new(gadk_agent::PluginConfig {
170 name: NAME.to_string(),
171 on_user_message_callback: Some(on_user_message),
172 before_run_callback: Some(before_run),
173 on_event_callback: Some(on_event),
174 after_run_callback: Some(after_run),
175 before_agent_callback: Some(before_agent),
176 after_agent_callback: Some(after_agent),
177 on_agent_error_callback: None,
179 before_model_callback: Some(before_model),
180 after_model_callback: Some(after_model),
181 on_model_error_callback: Some(on_model_error),
182 before_tool_callback: Some(before_tool),
183 after_tool_callback: Some(after_tool),
184 on_tool_error_callback: Some(on_tool_error),
185 close: None,
186 state: None,
187 })
188}
189
190struct LoggingPlugin {
191 name: String,
192}
193
194fn truncate(s: &str, max: usize) -> Option<&str> {
197 if s.len() <= max {
198 return None;
199 }
200 let mut end = max;
201 while !s.is_char_boundary(end) {
202 end -= 1;
203 }
204 Some(&s[..end])
205}
206
207fn go_list(items: &[String]) -> String {
209 format!("[{}]", items.join(" "))
210}
211
212fn format_content(content: Option<&Content>, max: usize) -> String {
215 let Some(content) = content.filter(|c| !c.parts.is_empty()) else {
216 return "None".to_string();
217 };
218 let parts: Vec<String> = content
219 .parts
220 .iter()
221 .map(|part| {
222 if !part.text.is_empty() {
223 let text = part.text.trim();
224 match truncate(text, max) {
225 Some(cut) => format!("text: '{cut}...'"),
226 None => format!("text: '{text}'"),
227 }
228 } else if let Some(fc) = &part.function_call {
229 format!("function_call: {}", fc.name)
230 } else if let Some(fr) = &part.function_response {
231 format!("function_response: {}", fr.name)
232 } else if part.code_execution_result.is_some() {
233 "code_execution_result".to_string()
234 } else {
235 "other_part".to_string()
236 }
237 })
238 .collect();
239 parts.join(" | ")
240}
241
242fn format_args(args: &Map<String, Value>, max: usize) -> String {
244 if args.is_empty() {
245 return "{}".to_string();
246 }
247 let formatted = Value::Object(args.clone()).to_string();
248 match truncate(&formatted, max) {
249 Some(cut) => format!("{cut}...}}"),
250 None => formatted,
251 }
252}
253
254impl LoggingPlugin {
255 fn log(&self, msg: impl AsRef<str>) {
257 tracing::info!(target: "gadk_engine::plugin::logging", "[{}] {}", self.name, msg.as_ref());
258 }
259
260 fn on_user_message(&self, ctx: &InvocationContext, msg: &Content) {
261 self.log("🚀 USER MESSAGE RECEIVED");
262 self.log(format!(" Invocation ID: {}", ctx.invocation_id()));
263 let session = ctx.session();
264 self.log(format!(" Session ID: {}", session.id()));
265 self.log(format!(" User ID: {}", session.user_id()));
266 self.log(format!(" App Name: {}", session.app_name()));
267 self.log(format!(" Root Agent: {}", ctx.agent().name()));
268 self.log(format!(
269 " User Content: {}",
270 format_content(Some(msg), 200)
271 ));
272 let branch = ctx.branch();
273 if !branch.is_empty() {
274 self.log(format!(" Branch: {branch}"));
275 }
276 }
277
278 fn before_run(&self, ctx: &InvocationContext) {
279 self.log("🏃 INVOCATION STARTING");
280 self.log(format!(" Invocation ID: {}", ctx.invocation_id()));
281 self.log(format!(" Starting Agent: {}", ctx.agent().name()));
282 }
283
284 fn on_event(&self, event: &Event) {
285 self.log("📢 EVENT YIELDED");
286 self.log(format!(" Event ID: {}", event.id));
287 self.log(format!(" Author: {}", event.author));
288 self.log(format!(
289 " Content: {}",
290 format_content(event.response.content.as_ref(), 200)
291 ));
292 self.log(format!(" Final Response: {}", event.is_final_response()));
293 let mut func_calls = Vec::new();
294 let mut func_responses = Vec::new();
295 if let Some(content) = &event.response.content {
296 for part in &content.parts {
297 if let Some(fc) = &part.function_call {
298 func_calls.push(fc.name.clone());
299 }
300 if let Some(fr) = &part.function_response {
301 func_responses.push(fr.name.clone());
302 }
303 }
304 }
305 if !func_calls.is_empty() {
306 self.log(format!(" Function Calls: {}", go_list(&func_calls)));
307 }
308 if !func_responses.is_empty() {
309 self.log(format!(
310 " Function Responses: {}",
311 go_list(&func_responses)
312 ));
313 }
314 if !event.long_running_tool_ids.is_empty() {
315 self.log(format!(
316 " Long Running Tools: {}",
317 go_list(&event.long_running_tool_ids)
318 ));
319 }
320 }
321
322 fn after_run(&self, ctx: &InvocationContext) {
323 self.log("✅ INVOCATION COMPLETED");
324 self.log(format!(" Invocation ID: {}", ctx.invocation_id()));
325 self.log(format!(" Final Agent: {}", ctx.agent().name()));
326 }
327
328 fn before_agent(&self, ctx: &Context) {
329 self.log("🤖 AGENT STARTING");
330 self.log(format!(" Agent Name: {}", ctx.agent_name()));
331 self.log(format!(" Invocation ID: {}", ctx.invocation_id()));
332 let branch = ctx.branch();
333 if !branch.is_empty() {
334 self.log(format!(" Branch: {branch}"));
335 }
336 }
337
338 fn after_agent(&self, ctx: &Context) {
339 self.log("🤖 AGENT COMPLETED");
340 self.log(format!(" Agent Name: {}", ctx.agent_name()));
341 self.log(format!(" Invocation ID: {}", ctx.invocation_id()));
342 }
343
344 fn before_model(&self, ctx: &Context, req: &LlmRequest) {
345 self.log("🧠 LLM REQUEST");
346 let model = if req.model.is_empty() {
347 "default"
348 } else {
349 req.model.as_str()
350 };
351 self.log(format!(" Model: {model}"));
352 self.log(format!(" Agent: {}", ctx.agent_name()));
353 if let Some(si) = req
354 .config
355 .as_ref()
356 .and_then(|c| c.system_instruction.as_ref())
357 .filter(|si| !si.parts.is_empty())
358 {
359 let instruction: String = si.parts.iter().map(|p| p.text.as_str()).collect();
360 let shown = match truncate(&instruction, 200) {
361 Some(cut) => format!("{cut}..."),
362 None => instruction.clone(),
363 };
364 self.log(format!(" System Instruction: '{shown}'"));
365 }
366 if !req.tools.is_empty() {
367 let mut names: Vec<String> = req.tools.keys().cloned().collect();
369 names.sort();
370 self.log(format!(" Available Tools: {}", go_list(&names)));
371 }
372 }
373
374 fn after_model(&self, ctx: &Context, resp: &LlmResponse, err: Option<&ModelError>) {
375 self.log("🧠 LLM RESPONSE");
376 self.log(format!(" Agent: {}", ctx.agent_name()));
377 if let Some(e) = err {
378 self.log(format!(" ❌ ERROR - {e}"));
379 return;
380 }
381 if !resp.error_code.is_empty() {
382 self.log(format!(" ❌ ERROR - Code: {}", resp.error_code));
383 self.log(format!(" Error Message: {}", resp.error_message));
384 } else {
385 self.log(format!(
386 " Content: {}",
387 format_content(resp.content.as_ref(), 200)
388 ));
389 if resp.partial {
390 self.log(format!(" Partial: {}", resp.partial));
391 }
392 self.log(format!(" Turn Complete: {}", resp.turn_complete));
393 }
394 if let Some(usage) = &resp.usage_metadata {
395 self.log(format!(
396 " Token Usage - Input: {}, Output: {}",
397 usage.prompt_token_count, usage.candidates_token_count
398 ));
399 }
400 }
401
402 fn on_model_error(&self, ctx: &Context, err: &ModelError) {
403 self.log("🧠 LLM ERROR");
404 self.log(format!(" Agent: {}", ctx.agent_name()));
405 self.log(format!(" Error: {err}"));
406 }
407
408 fn before_tool(&self, ctx: &Context, tool: &dyn Tool, args: &Map<String, Value>) {
409 self.log("🔧 TOOL STARTING");
410 self.log(format!(" Tool Name: {}", tool.name()));
411 self.log(format!(" Agent: {}", ctx.agent_name()));
412 self.log(format!(" Function Call ID: {}", ctx.function_call_id()));
413 self.log(format!(" Arguments: {}", format_args(args, 300)));
414 }
415
416 fn after_tool(
417 &self,
418 ctx: &Context,
419 tool: &dyn Tool,
420 result: &Map<String, Value>,
421 err: Option<&ToolError>,
422 ) {
423 self.log("🔧 TOOL COMPLETED");
424 self.log(format!(" Tool Name: {}", tool.name()));
425 self.log(format!(" Agent: {}", ctx.agent_name()));
426 self.log(format!(" Function Call ID: {}", ctx.function_call_id()));
427 match err {
428 Some(e) => self.log(format!(" Error: {e}")),
429 None => self.log(format!(" Result: {}", format_args(result, 300))),
430 }
431 }
432
433 fn on_tool_error(
434 &self,
435 ctx: &Context,
436 tool: &dyn Tool,
437 args: &Map<String, Value>,
438 err: &ToolError,
439 ) {
440 self.log("🔧 TOOL ERROR");
441 self.log(format!(" Tool Name: {}", tool.name()));
442 self.log(format!(" Agent: {}", ctx.agent_name()));
443 self.log(format!(" Function Call ID: {}", ctx.function_call_id()));
444 self.log(format!(" Arguments: {}", format_args(args, 300)));
445 self.log(format!(" Error: {err}"));
446 }
447}
448
449#[cfg(test)]
450#[allow(clippy::unwrap_used)]
451mod tests {
452 use super::*;
453 use gadk_genai::{CodeExecutionResult, FunctionCall, FunctionResponse, Part};
454 use serde_json::json;
455
456 fn content(parts: Vec<Part>) -> Content {
457 Content {
458 role: "user".into(),
459 parts,
460 }
461 }
462
463 #[test]
464 fn format_content_cases() {
465 assert_eq!(format_content(None, 200), "None");
466 assert_eq!(format_content(Some(&content(vec![])), 200), "None");
467 assert_eq!(
468 format_content(Some(&content(vec![Part::from_text(" hi ")])), 200),
469 "text: 'hi'"
470 );
471 let fc = Part {
472 function_call: Some(FunctionCall {
473 name: "f".into(),
474 ..Default::default()
475 }),
476 ..Default::default()
477 };
478 let fr = Part {
479 function_response: Some(FunctionResponse {
480 name: "g".into(),
481 ..Default::default()
482 }),
483 ..Default::default()
484 };
485 let cer = Part {
486 code_execution_result: Some(CodeExecutionResult::default()),
487 ..Default::default()
488 };
489 assert_eq!(
490 format_content(
491 Some(&content(vec![
492 Part::from_text("t"),
493 fc,
494 fr,
495 cer,
496 Part::default()
497 ])),
498 200
499 ),
500 "text: 't' | function_call: f | function_response: g | code_execution_result | other_part"
501 );
502 }
503
504 #[test]
505 fn format_content_truncates_without_splitting_a_char() {
506 let s = format!("{}é{}", "a".repeat(199), "b".repeat(10)); let got = format_content(Some(&content(vec![Part::from_text(s)])), 200);
508 assert_eq!(got, format!("text: '{}...'", "a".repeat(199)));
509 let exact = "a".repeat(200);
510 assert_eq!(
511 format_content(Some(&content(vec![Part::from_text(exact.clone())])), 200),
512 format!("text: '{exact}'")
513 );
514 }
515
516 #[test]
517 fn format_args_cases() {
518 assert_eq!(format_args(&Map::new(), 300), "{}");
519 let Value::Object(small) = json!({"a": 1}) else {
520 unreachable!()
521 };
522 assert_eq!(format_args(&small, 300), r#"{"a":1}"#);
523 let Value::Object(big) = json!({"k": "x".repeat(400)}) else {
524 unreachable!()
525 };
526 let got = format_args(&big, 300);
527 assert!(got.ends_with("...}"));
528 assert_eq!(got.len(), 300 + 4);
529 }
530}