yaze 0.3.2
Link to the Past ROM Editor
 
Loading...
Searching...
No Matches
conversation_test.cc
Go to the documentation of this file.
1#include <fstream>
2#include <iostream>
3#include <string>
4#include <vector>
5
6#include "absl/flags/declare.h"
7#include "absl/flags/flag.h"
8#include "absl/status/status.h"
9#include "absl/strings/str_cat.h"
10#include "rom/rom.h"
14#include "core/project.h"
15#include "nlohmann/json.hpp"
17
18ABSL_DECLARE_FLAG(std::string, rom);
19ABSL_DECLARE_FLAG(bool, mock_rom);
20
21namespace yaze {
22namespace cli {
23namespace agent {
24
25namespace {
26
27absl::Status LoadRomForAgent(Rom& rom) {
28 if (rom.is_loaded()) {
29 return ::absl::OkStatus();
30 }
31
32 // Check if mock ROM mode is enabled
33 bool use_mock = ::absl::GetFlag(FLAGS_mock_rom);
34 if (use_mock) {
35 // Initialize mock ROM with embedded labels
36 auto status = InitializeMockRom(rom);
37 if (!status.ok()) {
38 return status;
39 }
40 std::cout << "โœ… Mock ROM initialized with embedded Zelda3 labels\n";
41 return ::absl::OkStatus();
42 }
43
44 // Otherwise load from file
45 std::string rom_path = ::absl::GetFlag(FLAGS_rom);
46 if (rom_path.empty()) {
47 return ::absl::InvalidArgumentError(
48 "No ROM loaded. Pass --rom=<path> or use --mock-rom for testing.");
49 }
50
51 auto status = rom.LoadFromFile(rom_path);
52 if (!status.ok()) {
53 return ::absl::FailedPreconditionError(::absl::StrCat(
54 "Failed to load ROM from '", rom_path, "': ", status.message()));
55 }
56
57 return ::absl::OkStatus();
58}
59
61 std::string name;
62 std::string description;
63 std::vector<std::string> user_prompts;
64 std::vector<std::string>
65 expected_keywords; // Keywords to look for in responses
66 bool expect_tool_calls = false;
67 bool expect_commands = false;
68};
69
70std::vector<ConversationTestCase> GetDefaultTestCases() {
71 return {
72 {
73 .name = "embedded_labels_room_query",
74 .description = "Ask about room names using embedded labels",
75 .user_prompts = {"What is the name of room 5?"},
76 .expected_keywords = {"room", "Tower of Hera", "Moldorm"},
77 .expect_tool_calls = false,
78 .expect_commands = false,
79 },
80 {
81 .name = "embedded_labels_sprite_query",
82 .description = "Ask about sprite names using embedded labels",
83 .user_prompts = {"What is sprite 9?"},
84 .expected_keywords = {"sprite", "Moldorm", "Boss"},
85 .expect_tool_calls = false,
86 .expect_commands = false,
87 },
88 {
89 .name = "embedded_labels_entrance_query",
90 .description = "Ask about entrance names using embedded labels",
91 .user_prompts = {"What is entrance 0?"},
92 .expected_keywords = {"entrance", "Link", "House"},
93 .expect_tool_calls = false,
94 .expect_commands = false,
95 },
96 {
97 .name = "simple_question",
98 .description = "Ask about dungeons in the ROM",
99 .user_prompts = {"What dungeons are in this ROM?"},
100 .expected_keywords = {"dungeon", "palace", "castle"},
101 .expect_tool_calls = true,
102 .expect_commands = false,
103 },
104 {
105 .name = "list_all_rooms",
106 .description = "List all room names with embedded labels",
107 .user_prompts = {"List the first 10 dungeon rooms"},
108 .expected_keywords = {"room", "Ganon", "Hyrule", "Palace"},
109 .expect_tool_calls = true,
110 .expect_commands = false,
111 },
112 {
113 .name = "overworld_tile_search",
114 .description = "Find specific tiles in overworld",
115 .user_prompts = {"Find all trees on the overworld"},
116 .expected_keywords = {"tree", "tile", "map"},
117 .expect_tool_calls = true,
118 .expect_commands = false,
119 },
120 {
121 .name = "multi_step_query",
122 .description = "Ask multiple questions in sequence",
123 .user_prompts =
124 {
125 "What is the name of room 0?",
126 "What sprites are defined in the game?",
127 },
128 .expected_keywords = {"Ganon", "sprite", "room"},
129 .expect_tool_calls = true,
130 .expect_commands = false,
131 },
132 {
133 .name = "map_description",
134 .description = "Get information about a specific map",
135 .user_prompts = {"Describe overworld map 0"},
136 .expected_keywords = {"map", "light world", "tile"},
137 .expect_tool_calls = true,
138 .expect_commands = false,
139 },
140 };
141}
142
143void PrintTestHeader(const ConversationTestCase& test_case) {
144 std::cout << "\n===========================================\n";
145 std::cout << "Test: " << test_case.name << "\n";
146 std::cout << "Description: " << test_case.description << "\n";
147 std::cout << "===========================================\n\n";
148}
149
150void PrintUserPrompt(const std::string& prompt) {
151 std::cout << "๐Ÿ‘ค User: " << prompt << "\n\n";
152}
153
154void PrintAgentResponse(const ChatMessage& response, bool verbose) {
155 std::cout << "๐Ÿค– Agent: " << response.message << "\n\n";
156
157 if (verbose && response.json_pretty.has_value()) {
158 std::cout << "๐Ÿงพ JSON Output:\n" << *response.json_pretty << "\n\n";
159 }
160
161 if (response.table_data.has_value()) {
162 std::cout << "๐Ÿ“Š Table Output:\n";
163 const auto& table = response.table_data.value();
164
165 // Print headers
166 std::cout << " ";
167 for (size_t i = 0; i < table.headers.size(); ++i) {
168 std::cout << table.headers[i];
169 if (i < table.headers.size() - 1) {
170 std::cout << " | ";
171 }
172 }
173 std::cout << "\n ";
174 for (size_t i = 0; i < table.headers.size(); ++i) {
175 std::cout << std::string(table.headers[i].length(), '-');
176 if (i < table.headers.size() - 1) {
177 std::cout << " | ";
178 }
179 }
180 std::cout << "\n";
181
182 // Print rows (limit to 10 for readability)
183 const size_t max_rows = std::min<size_t>(10, table.rows.size());
184 for (size_t i = 0; i < max_rows; ++i) {
185 std::cout << " ";
186 for (size_t j = 0; j < table.rows[i].size(); ++j) {
187 std::cout << table.rows[i][j];
188 if (j < table.rows[i].size() - 1) {
189 std::cout << " | ";
190 }
191 }
192 std::cout << "\n";
193 }
194
195 if (!verbose && table.rows.size() > max_rows) {
196 std::cout << " ... (" << (table.rows.size() - max_rows)
197 << " more rows)\n";
198 }
199
200 if (verbose && table.rows.size() > max_rows) {
201 for (size_t i = max_rows; i < table.rows.size(); ++i) {
202 std::cout << " ";
203 for (size_t j = 0; j < table.rows[i].size(); ++j) {
204 std::cout << table.rows[i][j];
205 if (j < table.rows[i].size() - 1) {
206 std::cout << " | ";
207 }
208 }
209 std::cout << "\n";
210 }
211 }
212 std::cout << "\n";
213 }
214}
215
216bool ValidateResponse(const ChatMessage& response,
217 const ConversationTestCase& test_case) {
218 bool passed = true;
219
220 // Check for expected keywords
221 for (const auto& keyword : test_case.expected_keywords) {
222 if (response.message.find(keyword) == std::string::npos) {
223 std::cout << "โš ๏ธ Warning: Expected keyword '" << keyword
224 << "' not found in response\n";
225 // Don't fail test, just warn
226 }
227 }
228
229 // Check for tool calls (if we have table data, tools were likely called)
230 if (test_case.expect_tool_calls && !response.table_data.has_value()) {
231 std::cout << "โš ๏ธ Warning: Expected tool calls but no table data found\n";
232 }
233
234 // Check for commands
235 if (test_case.expect_commands) {
236 bool has_commands =
237 response.message.find("overworld") != std::string::npos ||
238 response.message.find("dungeon") != std::string::npos ||
239 response.message.find("set-tile") != std::string::npos;
240 if (!has_commands) {
241 std::cout << "โš ๏ธ Warning: Expected commands but none found\n";
242 }
243 }
244
245 return passed;
246}
247
248absl::Status RunTestCase(const ConversationTestCase& test_case,
249 ConversationalAgentService& service, bool verbose) {
250 PrintTestHeader(test_case);
251
252 bool all_passed = true;
253
254 service.ResetConversation();
255
256 for (const auto& prompt : test_case.user_prompts) {
257 PrintUserPrompt(prompt);
258
259 auto response_or = service.SendMessage(prompt);
260 if (!response_or.ok()) {
261 std::cout << "โŒ FAILED: " << response_or.status().message() << "\n\n";
262 all_passed = false;
263 continue;
264 }
265
266 const auto& response = response_or.value();
267 PrintAgentResponse(response, verbose);
268
269 if (!ValidateResponse(response, test_case)) {
270 all_passed = false;
271 }
272 }
273
274 if (verbose) {
275 const auto& history = service.GetHistory();
276 std::cout << "๐Ÿ—‚ Conversation Summary (" << history.size() << " message"
277 << (history.size() == 1 ? "" : "s") << ")\n";
278 for (const auto& message : history) {
279 const char* sender =
280 message.sender == ChatMessage::Sender::kUser ? "User" : "Agent";
281 std::cout << " [" << sender << "] " << message.message << "\n";
282 }
283 std::cout << "\n";
284 }
285
286 if (all_passed) {
287 std::cout << "โœ… Test PASSED: " << test_case.name << "\n";
288 return absl::OkStatus();
289 }
290
291 std::cout << "โš ๏ธ Test completed with warnings: " << test_case.name << "\n";
292 return absl::InternalError(
293 absl::StrCat("Conversation test failed validation: ", test_case.name));
294}
295
297 const std::string& file_path,
298 std::vector<ConversationTestCase>* test_cases) {
299 std::ifstream file(file_path);
300 if (!file.is_open()) {
301 return absl::NotFoundError(
302 absl::StrCat("Could not open test file: ", file_path));
303 }
304
305 nlohmann::json test_json;
306 try {
307 file >> test_json;
308 } catch (const nlohmann::json::parse_error& e) {
309 return absl::InvalidArgumentError(
310 absl::StrCat("Failed to parse test file: ", e.what()));
311 }
312
313 if (!test_json.is_array()) {
314 return absl::InvalidArgumentError(
315 "Test file must contain a JSON array of test cases");
316 }
317
318 for (const auto& test_obj : test_json) {
319 ConversationTestCase test_case;
320 test_case.name = test_obj.value("name", "unnamed_test");
321 test_case.description = test_obj.value("description", "");
322
323 if (test_obj.contains("prompts") && test_obj["prompts"].is_array()) {
324 for (const auto& prompt : test_obj["prompts"]) {
325 if (prompt.is_string()) {
326 test_case.user_prompts.push_back(prompt.get<std::string>());
327 }
328 }
329 }
330
331 if (test_obj.contains("expected_keywords") &&
332 test_obj["expected_keywords"].is_array()) {
333 for (const auto& keyword : test_obj["expected_keywords"]) {
334 if (keyword.is_string()) {
335 test_case.expected_keywords.push_back(keyword.get<std::string>());
336 }
337 }
338 }
339
340 test_case.expect_tool_calls = test_obj.value("expect_tool_calls", false);
341 test_case.expect_commands = test_obj.value("expect_commands", false);
342
343 test_cases->push_back(test_case);
344 }
345
346 return absl::OkStatus();
347}
348
349} // namespace
350
352 const std::vector<std::string>& arg_vec) {
353 std::string test_file;
354 bool use_defaults = true;
355 bool verbose = false;
356
357 for (size_t i = 0; i < arg_vec.size(); ++i) {
358 const std::string& arg = arg_vec[i];
359 if (arg == "--file" && i + 1 < arg_vec.size()) {
360 test_file = arg_vec[i + 1];
361 use_defaults = false;
362 ++i;
363 } else if (arg == "--verbose") {
364 verbose = true;
365 }
366 }
367
368 std::cout << "๐Ÿ” Debug: Starting test-conversation handler...\n";
369
370 // Load ROM context
371 Rom rom;
372 std::cout << "๐Ÿ” Debug: Loading ROM...\n";
373 auto load_status = LoadRomForAgent(rom);
374 if (!load_status.ok()) {
375 std::cerr << "โŒ Error loading ROM: " << load_status.message() << "\n";
376 return load_status;
377 }
378
379 std::cout << "โœ… ROM loaded: " << rom.title() << "\n";
380
381 // Load embedded labels for natural language queries
382 std::cout << "๐Ÿ” Debug: Initializing embedded labels...\n";
383 project::YazeProject project;
384 auto labels_status = project.InitializeEmbeddedLabels(
386 if (!labels_status.ok()) {
387 std::cerr << "โš ๏ธ Warning: Could not initialize embedded labels: "
388 << labels_status.message() << "\n";
389 } else {
390 std::cout << "โœ… Embedded labels initialized successfully\n";
391 }
392
393 // Associate labels with ROM if it has a resource label manager
394 std::cout << "๐Ÿ” Debug: Checking resource label manager...\n";
395 if (rom.resource_label() && project.use_embedded_labels) {
396 std::cout << "๐Ÿ” Debug: Associating labels with ROM...\n";
397 rom.resource_label()->labels_ = project.resource_labels;
398 rom.resource_label()->labels_loaded_ = true;
399 std::cout << "โœ… Embedded labels loaded and associated with ROM\n";
400 } else {
401 std::cout << "โš ๏ธ ROM has no resource label manager\n";
402 }
403
404 // Create conversational agent service
405 std::cout << "๐Ÿ” Debug: Creating conversational agent service...\n";
406 std::cout << "๐Ÿ” Debug: About to construct service object...\n";
407
409 std::cout << "โœ… Service object created\n";
410
411 std::cout << "๐Ÿ” Debug: Setting ROM context...\n";
412 service.SetRomContext(&rom);
413 std::cout << "โœ… Service initialized\n";
414
415 // Load test cases
416 std::vector<ConversationTestCase> test_cases;
417 if (use_defaults) {
418 test_cases = GetDefaultTestCases();
419 std::cout << "Using default test cases (" << test_cases.size()
420 << " tests)\n";
421 } else {
422 auto status = LoadTestCasesFromFile(test_file, &test_cases);
423 if (!status.ok()) {
424 return status;
425 }
426 std::cout << "Loaded " << test_cases.size() << " test cases from "
427 << test_file << "\n";
428 }
429
430 if (test_cases.empty()) {
431 return absl::InvalidArgumentError("No test cases to run");
432 }
433
434 // Run all test cases
435 int passed = 0;
436 int failed = 0;
437
438 for (const auto& test_case : test_cases) {
439 auto status = RunTestCase(test_case, service, verbose);
440 if (status.ok()) {
441 ++passed;
442 } else {
443 ++failed;
444 std::cerr << "Test case '" << test_case.name
445 << "' failed: " << status.message() << "\n";
446 }
447 }
448
449 // Print summary
450 std::cout << "\n===========================================\n";
451 std::cout << "Test Summary\n";
452 std::cout << "===========================================\n";
453 std::cout << "Total tests: " << test_cases.size() << "\n";
454 std::cout << "Passed: " << passed << "\n";
455 std::cout << "Failed: " << failed << "\n";
456
457 if (failed == 0) {
458 std::cout << "\nโœ… All tests passed!\n";
459 } else {
460 std::cout << "\nโš ๏ธ Some tests failed\n";
461 }
462
463 if (failed == 0) {
464 return absl::OkStatus();
465 }
466
467 return absl::InternalError(
468 absl::StrCat(failed, " conversation test(s) reported failures"));
469}
470
471} // namespace agent
472} // namespace cli
473} // namespace yaze
The Rom class is used to load, save, and modify Rom data. This is a generic SNES ROM container and do...
Definition rom.h:24
project::ResourceLabelManager * resource_label()
Definition rom.h:146
absl::Status LoadFromFile(const std::string &filename, const LoadOptions &options=LoadOptions::Defaults())
Definition rom.cc:74
bool is_loaded() const
Definition rom.h:128
auto title() const
Definition rom.h:133
absl::StatusOr< ChatMessage > SendMessage(const std::string &message)
const std::vector< ChatMessage > & GetHistory() const
ABSL_DECLARE_FLAG(std::string, rom)
bool ValidateResponse(const ChatMessage &response, const ConversationTestCase &test_case)
void PrintTestHeader(const ConversationTestCase &test_case)
absl::Status LoadTestCasesFromFile(const std::string &file_path, std::vector< ConversationTestCase > *test_cases)
void PrintAgentResponse(const ChatMessage &response, bool verbose)
absl::Status RunTestCase(const ConversationTestCase &test_case, ConversationalAgentService &service, bool verbose)
absl::Status HandleTestConversationCommand(const std::vector< std::string > &args)
absl::Status InitializeMockRom(Rom &rom)
Initialize a mock ROM for testing without requiring an actual ROM file.
Definition mock_rom.cc:16
std::optional< std::string > json_pretty
std::unordered_map< std::string, std::unordered_map< std::string, std::string > > labels_
Definition project.h:301
Modern project structure with comprehensive settings consolidation.
Definition project.h:84
std::unordered_map< std::string, std::unordered_map< std::string, std::string > > resource_labels
Definition project.h:108
absl::Status InitializeEmbeddedLabels(const std::unordered_map< std::string, std::unordered_map< std::string, std::string > > &labels)
Definition project.cc:1334
static std::unordered_map< std::string, std::unordered_map< std::string, std::string > > ToResourceLabels()
Convert all labels to a structured map for project embedding.