File size: 7,683 Bytes
767452b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
use async_trait::async_trait;
use forge_domain::{
    Conversation, EndPayload, EventData, EventHandle, RequestPayload, ResponsePayload,
    StartPayload, ToolcallEndPayload, ToolcallStartPayload,
};
use tracing::{debug, info, warn};

/// Handler that provides comprehensive tracing/logging for all lifecycle events
///
/// This handler logs important information at various stages of the
/// orchestration:
/// - Start: Logs conversation and agent initialization
/// - Request: Logs each request iteration
/// - Response: Logs token usage, costs, and conversation metrics
/// - ToolcallStart: Logs tool execution start
/// - ToolcallEnd: Logs tool failures with details
/// - End: Logs title generation when available
#[derive(Clone)]
pub struct TracingHandler;

impl TracingHandler {
    pub fn new() -> Self {
        Self
    }
}

#[async_trait]
impl EventHandle<EventData<StartPayload>> for TracingHandler {
    async fn handle(
        &self,
        event: &EventData<StartPayload>,
        conversation: &mut Conversation,
    ) -> anyhow::Result<()> {
        debug!(
            conversation_id = %conversation.id,
            agent = %event.agent.id,
            model = %event.model_id,
            "Initializing agent"
        );

        Ok(())
    }
}

#[async_trait]
impl EventHandle<EventData<RequestPayload>> for TracingHandler {
    async fn handle(
        &self,
        _event: &EventData<RequestPayload>,
        _conversation: &mut Conversation,
    ) -> anyhow::Result<()> {
        // Request events are logged but don't need specific logging per request
        // The Start event logs initialization, Response events log the results
        Ok(())
    }
}

#[async_trait]
impl EventHandle<EventData<ResponsePayload>> for TracingHandler {
    async fn handle(
        &self,
        event: &EventData<ResponsePayload>,
        conversation: &mut Conversation,
    ) -> anyhow::Result<()> {
        let message = &event.payload.message;

        if let Some(context) = &conversation.context {
            info!(
                conversation_id = %conversation.id,
                conversation_length = context.messages.len(),
                token_usage = format!("{}", message.usage.prompt_tokens),
                total_tokens = format!("{}", message.usage.total_tokens),
                cached_tokens = format!("{}", message.usage.cached_tokens),
                cost = message.usage.cost.unwrap_or_default(),
                finish_reason = message.finish_reason.as_ref().map_or("", |reason| reason.into()),
                "Processing usage information"
            );
        }

        debug!(
            agent_id = %event.agent.id,
            tool_call_count = message.tool_calls.len(),
            "Tool call count"
        );

        Ok(())
    }
}

#[async_trait]
impl EventHandle<EventData<ToolcallStartPayload>> for TracingHandler {
    async fn handle(
        &self,
        event: &EventData<ToolcallStartPayload>,
        _conversation: &mut Conversation,
    ) -> anyhow::Result<()> {
        let tool_call = &event.payload.tool_call;

        debug!(
            agent_id = %event.agent.id,
            tool_name = %tool_call.name,
            call_id = ?tool_call.call_id,
            arguments = %tool_call.arguments.to_owned().into_string(),
            "Tool call started"
        );

        Ok(())
    }
}

#[async_trait]
impl EventHandle<EventData<ToolcallEndPayload>> for TracingHandler {
    async fn handle(
        &self,
        event: &EventData<ToolcallEndPayload>,
        _conversation: &mut Conversation,
    ) -> anyhow::Result<()> {
        let tool_call = &event.payload.tool_call;
        let result = &event.payload.result;

        if result.is_error() {
            warn!(
                agent_id = %event.agent.id,
                name = %tool_call.name,
                call_id = ?tool_call.call_id,
                arguments = %tool_call.arguments.to_owned().into_string(),
                output = ?result.output,
                "Tool call failed",
            );
        }

        Ok(())
    }
}

#[async_trait]
impl EventHandle<EventData<EndPayload>> for TracingHandler {
    async fn handle(
        &self,
        _event: &EventData<EndPayload>,
        conversation: &mut Conversation,
    ) -> anyhow::Result<()> {
        if let Some(title) = &conversation.title {
            debug!(
                conversation_id = %conversation.id,
                title,
                "Title generated for conversation"
            );
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use forge_domain::{
        Agent, ChatCompletionMessageFull, ModelId, ToolCallId, ToolName, ToolResult,
    };

    use super::*;

    fn test_agent() -> Agent {
        Agent::new(
            "test-agent",
            "test-provider".to_string().into(),
            ModelId::new("test-model"),
        )
    }

    fn test_model_id() -> ModelId {
        ModelId::new("test-model")
    }

    #[tokio::test]
    async fn test_tracing_handler_start() {
        let handler = TracingHandler::new();
        let mut conversation = Conversation::generate();
        let event = EventData::new(test_agent(), test_model_id(), StartPayload);

        // Should not panic
        handler.handle(&event, &mut conversation).await.unwrap();
    }

    #[tokio::test]
    async fn test_tracing_handler_request() {
        let handler = TracingHandler::new();
        let mut conversation = Conversation::generate();
        let event = EventData::new(test_agent(), test_model_id(), RequestPayload::new(0));

        // Should not panic
        handler.handle(&event, &mut conversation).await.unwrap();
    }

    #[tokio::test]
    async fn test_tracing_handler_response() {
        let handler = TracingHandler::new();
        let mut conversation = Conversation::generate();
        let message = ChatCompletionMessageFull {
            content: "test".to_string(),
            thought_signature: None,
            reasoning: None,
            reasoning_details: None,
            tool_calls: vec![],
            usage: Default::default(),
            finish_reason: None,
            phase: None,
        };
        let event = EventData::new(test_agent(), test_model_id(), ResponsePayload::new(message));

        // Should not panic
        handler.handle(&event, &mut conversation).await.unwrap();
    }

    #[tokio::test]
    async fn test_tracing_handler_toolcall_end_error() {
        let handler = TracingHandler::new();
        let mut conversation = Conversation::generate();
        let tool_call = forge_domain::ToolCallFull {
            name: ToolName::from("test-tool"),
            call_id: Some(ToolCallId::new("test-id")),
            arguments: serde_json::json!({"key": "value"}).into(),
            thought_signature: None,
        };
        let result = ToolResult::new(ToolName::from("test-tool"))
            .call_id(ToolCallId::new("test-id"))
            .failure(anyhow::anyhow!("Test error"));
        let event = EventData::new(
            test_agent(),
            test_model_id(),
            ToolcallEndPayload::new(tool_call, result),
        );

        // Should log warning but not panic
        handler.handle(&event, &mut conversation).await.unwrap();
    }

    #[tokio::test]
    async fn test_tracing_handler_end_with_title() {
        let handler = TracingHandler::new();
        let mut conversation = Conversation::generate().title(Some("Test Title".to_string()));
        let event = EventData::new(test_agent(), test_model_id(), EndPayload);

        // Should log debug message with title
        handler.handle(&event, &mut conversation).await.unwrap();
    }
}