45 lines
2.2 KiB
C
Raw Normal View History

2025-01-04 07:40:31 +00:00
// Written by retoor@molodetz.nl
// This code manages a collection of messages using JSON objects. It provides functions to retrieve all messages as a JSON array, add a new message with a specified role and content, and free the allocated resources.
// Includes external library <json-c/json.h> for JSON manipulation
// MIT License
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
2025-01-05 21:59:51 +00:00
#ifndef R_MESSAGES_H
#define R_MESSAGES_H
2025-01-04 05:00:03 +00:00
#include "json-c/json.h"
2025-01-04 07:40:31 +00:00
2025-01-04 05:00:03 +00:00
struct json_object *_message_array = NULL;
2025-01-04 07:40:31 +00:00
struct json_object *message_list() {
if (_message_array == NULL) {
2025-01-04 05:00:03 +00:00
_message_array = json_object_new_array();
}
return _message_array;
2025-01-04 07:40:31 +00:00
}
2025-01-04 05:00:03 +00:00
2025-01-04 07:40:31 +00:00
struct json_object *message_add(char *role, char *content) {
2025-01-04 05:00:03 +00:00
struct json_object *messages = message_list();
struct json_object *message = json_object_new_object();
json_object_object_add(message, "role", json_object_new_string(role));
json_object_object_add(message, "content", json_object_new_string(content));
json_object_array_add(messages, message);
return message;
}
2025-01-04 07:40:31 +00:00
char *message_json() {
2025-01-04 05:00:03 +00:00
return (char *)json_object_to_json_string_ext(message_list(), JSON_C_TO_STRING_PRETTY);
}
2025-01-04 07:40:31 +00:00
void message_free() {
if (_message_array != NULL) {
2025-01-04 05:00:03 +00:00
json_object_put(_message_array);
_message_array = NULL;
}
}
2025-01-05 21:59:51 +00:00
#endif