#include "google/optimize/conversation.h" #include "google/errors.h" #include "google/optimize/caps.h" namespace molo::google::optimize { std::string Conversation::transcript() const { std::string out; for (const Turn& t : turns) { out += t.role + ": " + t.text + "\n"; for (const ToolCallRecord& c : t.calls) { out += " tool " + c.name + "(" + c.args.dump() + ")"; if (!c.result.is_null()) out += " -> " + c.result.dump(); out += "\n"; } if (out.size() > OptimizeCaps::kMaxTranscriptChars) { out.resize(OptimizeCaps::kMaxTranscriptChars); out += "\n[transcript truncated]\n"; break; } } return out; } void Conversation::validate() const { if (turns.empty()) throw GoogleError::invalid("conversation has no turns"); if (turns.size() > OptimizeCaps::kMaxTurns) throw GoogleError::invalid("conversation over " + std::to_string(OptimizeCaps::kMaxTurns) + " turns"); for (const Turn& t : turns) { if (t.role != "user" && t.role != "agent") throw GoogleError::invalid("turn role must be user or agent"); if (t.text.size() > OptimizeCaps::kMaxTextChars) throw GoogleError::invalid("turn text over the character cap"); } } Conversation Conversation::parse_transcript(const std::string& text, const std::string& id) { Conversation c; c.id = id; std::size_t pos = 0; while (pos <= text.size()) { std::size_t end = text.find('\n', pos); if (end == std::string::npos) end = text.size(); std::string line = text.substr(pos, end - pos); pos = end + 1; if (!line.empty() && line.back() == '\r') line.pop_back(); std::string role; std::size_t skip = 0; if (line.rfind("user:", 0) == 0) { role = "user"; skip = 5; } else if (line.rfind("agent:", 0) == 0) { role = "agent"; skip = 6; } if (!role.empty()) { while (skip < line.size() && line[skip] == ' ') ++skip; c.turns.push_back(Turn{role, line.substr(skip), {}}); if (c.turns.size() > OptimizeCaps::kMaxTurns) throw GoogleError::invalid("conversation over " + std::to_string(OptimizeCaps::kMaxTurns) + " turns"); } else if (!line.empty()) { if (c.turns.empty()) throw GoogleError::invalid("transcript lines must start with user: or agent:"); c.turns.back().text += "\n" + line; } if (end == text.size()) break; } c.validate(); return c; } } // namespace molo::google::optimize