(conversationId, teamId, userId)
| 239 | } |
| 240 | |
| 241 | async function getConversation(conversationId, teamId, userId) { |
| 242 | const conversation = await db.AiConversation.findOne({ |
| 243 | where: { |
| 244 | id: conversationId, |
| 245 | team_id: teamId, |
| 246 | }, |
| 247 | }); |
| 248 | |
| 249 | assertConversationOwnership(conversation, userId); |
| 250 | |
| 251 | // Load messages from AiMessage table |
| 252 | const messages = await db.AiMessage.findAll({ |
| 253 | where: { conversation_id: conversationId }, |
| 254 | order: [["sequence", "ASC"]], |
| 255 | }); |
| 256 | |
| 257 | // Rebuild full_history for backward compatibility with client |
| 258 | const fullHistory = messages.map((msg) => { |
| 259 | const messageObj = { |
| 260 | role: msg.role, |
| 261 | content: msg.content, |
| 262 | }; |
| 263 | |
| 264 | // Add tool-specific fields |
| 265 | if (msg.tool_calls) { |
| 266 | messageObj.tool_calls = msg.tool_calls; |
| 267 | } |
| 268 | if (msg.tool_name) { |
| 269 | messageObj.name = msg.tool_name; |
| 270 | } |
| 271 | if (msg.tool_call_id) { |
| 272 | messageObj.tool_call_id = msg.tool_call_id; |
| 273 | } |
| 274 | |
| 275 | return messageObj; |
| 276 | }); |
| 277 | |
| 278 | // Compute token usage stats |
| 279 | const usageStats = await db.AiUsage.findAll({ |
| 280 | where: { conversation_id: conversationId }, |
| 281 | attributes: [ |
| 282 | [fn("SUM", col("total_tokens")), "total_tokens"], |
| 283 | [fn("SUM", col("prompt_tokens")), "prompt_tokens"], |
| 284 | [fn("SUM", col("completion_tokens")), "completion_tokens"], |
| 285 | ], |
| 286 | raw: true, |
| 287 | }); |
| 288 | |
| 289 | const stats = usageStats[0] || {}; |
| 290 | |
| 291 | // Return conversation with messages and usage stats |
| 292 | return { |
| 293 | ...conversation.toJSON(), |
| 294 | full_history: fullHistory, |
| 295 | total_tokens: parseInt(stats.total_tokens, 10) || 0, |
| 296 | prompt_tokens: parseInt(stats.prompt_tokens, 10) || 0, |
| 297 | completion_tokens: parseInt(stats.completion_tokens, 10) || 0, |
| 298 | }; |
no test coverage detected