Refactor.

This commit is contained in:
retoor 2025-01-04 08:40:31 +01:00
parent 016e335a23
commit 353d527ffd
8 changed files with 295 additions and 198 deletions

53
chat.h
View File

@ -1,30 +1,65 @@
// Written by retoor@molodetz.nl
// This code defines functionality for creating and managing JSON-based chat prompts
// using a specific AI model configuration, providing easy integration with message handling
// and HTTP communication for dynamic applications.
// Non-standard imports: json-c library for handling JSON objects.
// 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.
#ifndef CALPACA_PROMPT_H #ifndef CALPACA_PROMPT_H
#define CALPACA_PROMPT_H #define CALPACA_PROMPT_H
#include <json-c/json.h> #include <json-c/json.h>
#include "messages.h" #include "messages.h"
#include "http.h" #include "http.h"
char * prompt_model = "gpt-4o-mini";
char *prompt_model = "gpt-4o-mini";
int prompt_max_tokens = 100; int prompt_max_tokens = 100;
double prompt_temperature = 0.5; double prompt_temperature = 0.5;
json_object * _prompt =NULL; json_object *_prompt = NULL;
void chat_free(){ void chat_free() {
if(_prompt == NULL) if (_prompt == NULL)
return; return;
json_object_put(_prompt); json_object_put(_prompt);
_prompt = NULL; _prompt = NULL;
} }
char * chat_json(char * role, char * message){ char *chat_json(char *role, char *message) {
chat_free(); chat_free();
message_add(role,message); message_add(role, message);
struct json_object *root_object = json_object_new_object(); struct json_object *root_object = json_object_new_object();
json_object_object_add(root_object, "model", json_object_new_string(prompt_model)); json_object_object_add(root_object, "model", json_object_new_string(prompt_model));
json_object_object_add(root_object, "messages", message_list()); json_object_object_add(root_object, "messages", message_list());
json_object_object_add(root_object, "max_tokens", json_object_new_int(prompt_max_tokens)); json_object_object_add(root_object, "max_tokens", json_object_new_int(prompt_max_tokens));
json_object_object_add(root_object, "temperature", json_object_new_double(prompt_temperature)); json_object_object_add(root_object, "temperature", json_object_new_double(prompt_temperature));
return (char *)json_object_to_json_string_ext(root_object, JSON_C_TO_STRING_PRETTY);
return (char *)json_object_to_json_string_ext(root_object, JSON_C_TO_STRING_PRETTY);
} }
#endif #endif

105
http.h
View File

@ -1,5 +1,14 @@
// Written by retoor@molodetz.nl
// The source code provides functionality for making HTTP POST and GET requests over SSL/TLS using OpenSSL. It includes initialization and cleanup of the OpenSSL library, creation of SSL context, socket creation and connection, and sending requests with handling responses. Furthermore, it interfaces with JSON and handles authentication using an external "auth.h" file.
// Includes: "auth.h", <json-c/json.h>
// MIT License
#ifndef CALPACA_HTTP_H #ifndef CALPACA_HTTP_H
#define CALPACA_HTTP_H #define CALPACA_HTTP_H
#include <stdio.h> #include <stdio.h>
#include <string.h> #include <string.h>
#include <stdlib.h> #include <stdlib.h>
@ -11,19 +20,16 @@
#include "auth.h" #include "auth.h"
#include <json-c/json.h> #include <json-c/json.h>
void init_openssl() void init_openssl() {
{
SSL_load_error_strings(); SSL_load_error_strings();
OpenSSL_add_ssl_algorithms(); OpenSSL_add_ssl_algorithms();
} }
void cleanup_openssl() void cleanup_openssl() {
{
EVP_cleanup(); EVP_cleanup();
} }
SSL_CTX *create_context() SSL_CTX *create_context() {
{
const SSL_METHOD *method = TLS_method(); const SSL_METHOD *method = TLS_method();
SSL_CTX *ctx = SSL_CTX_new(method); SSL_CTX *ctx = SSL_CTX_new(method);
SSL_CTX_load_verify_locations(ctx, "/etc/ssl/certs/ca-certificates.crt", NULL); SSL_CTX_load_verify_locations(ctx, "/etc/ssl/certs/ca-certificates.crt", NULL);
@ -31,15 +37,10 @@ SSL_CTX *create_context()
return ctx; return ctx;
} }
SSL_CTX *create_context2() SSL_CTX *create_context2() {
{ const SSL_METHOD *method = TLS_client_method();
const SSL_METHOD *method; SSL_CTX *ctx = SSL_CTX_new(method);
SSL_CTX *ctx; if (!ctx) {
method = TLS_client_method();
ctx = SSL_CTX_new(method);
if (!ctx)
{
perror("Unable to create SSL context"); perror("Unable to create SSL context");
ERR_print_errors_fp(stderr); ERR_print_errors_fp(stderr);
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
@ -48,21 +49,18 @@ SSL_CTX *create_context2()
return ctx; return ctx;
} }
int create_socket(const char *hostname, int port) int create_socket(const char *hostname, int port) {
{
struct hostent *host; struct hostent *host;
struct sockaddr_in addr; struct sockaddr_in addr;
host = gethostbyname(hostname); host = gethostbyname(hostname);
if (!host) if (!host) {
{
perror("Unable to resolve host"); perror("Unable to resolve host");
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
int sock = socket(AF_INET, SOCK_STREAM, 0); int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0) if (sock < 0) {
{
perror("Unable to create socket"); perror("Unable to create socket");
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
@ -71,8 +69,7 @@ int create_socket(const char *hostname, int port)
addr.sin_port = htons(port); addr.sin_port = htons(port);
addr.sin_addr.s_addr = *(long *)(host->h_addr); addr.sin_addr.s_addr = *(long *)(host->h_addr);
if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) != 0) if (connect(sock, (struct sockaddr *)&addr, sizeof(addr)) != 0) {
{
perror("Unable to connect to host"); perror("Unable to connect to host");
close(sock); close(sock);
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
@ -81,35 +78,24 @@ int create_socket(const char *hostname, int port)
return sock; return sock;
} }
char *http_post(const char *hostname, char *url, char *data) char *http_post(const char *hostname, char *url, char *data) {
{
init_openssl(); init_openssl();
int port = 443; int port = 443;
SSL_CTX *ctx = create_context(); SSL_CTX *ctx = create_context();
int sock = create_socket(hostname, port); int sock = create_socket(hostname, port);
SSL *ssl = SSL_new(ctx); SSL *ssl = SSL_new(ctx);
SSL_set_connect_state(ssl); SSL_set_connect_state(ssl);
SSL_set_tlsext_host_name(ssl, hostname); SSL_set_tlsext_host_name(ssl, hostname);
SSL_set_fd(ssl, sock); SSL_set_fd(ssl, sock);
int buffer_size = 4096; int buffer_size = 4096;
char *buffer = (char *)malloc(buffer_size); char *buffer = malloc(buffer_size);
if (SSL_connect(ssl) <= 0) if (SSL_connect(ssl) <= 0) {
{
ERR_print_errors_fp(stderr); ERR_print_errors_fp(stderr);
} } else {
else
{
size_t len = strlen(data); size_t len = strlen(data);
char *request = (char *)malloc(len + 4096); char *request = malloc(len + 4096);
request[0] = 0;
sprintf(request, sprintf(request,
"POST %s HTTP/1.1\r\n" "POST %s HTTP/1.1\r\n"
"Content-Length: %ld\r\n" "Content-Length: %ld\r\n"
@ -121,59 +107,41 @@ char *http_post(const char *hostname, char *url, char *data)
SSL_write(ssl, request, strlen(request)); SSL_write(ssl, request, strlen(request));
free(request); free(request);
int bytes; int bytes;
int bytes_total = 0; int bytes_total = 0;
while ((bytes = SSL_read(ssl, buffer + bytes_total, buffer_size - 1)) > 0) while ((bytes = SSL_read(ssl, buffer + bytes_total, buffer_size - 1)) > 0) {
{
if (bytes <= 0)
{
break;
}
bytes_total += bytes; bytes_total += bytes;
buffer = realloc(buffer, bytes_total + buffer_size); buffer = realloc(buffer, bytes_total + buffer_size);
buffer[bytes_total] = '\0'; buffer[bytes_total] = '\0';
} }
buffer[bytes_total] = '\0';
} }
SSL_free(ssl); SSL_free(ssl);
close(sock); close(sock);
SSL_CTX_free(ctx); SSL_CTX_free(ctx);
cleanup_openssl(); cleanup_openssl();
return buffer; return buffer;
} }
char *http_get(const char *hostname, char *url) char *http_get(const char *hostname, char *url) {
{
init_openssl(); init_openssl();
int port = 443; int port = 443;
SSL_CTX *ctx = create_context(); SSL_CTX *ctx = create_context();
int sock = create_socket(hostname, port); int sock = create_socket(hostname, port);
SSL *ssl = SSL_new(ctx); SSL *ssl = SSL_new(ctx);
SSL_set_connect_state(ssl); SSL_set_connect_state(ssl);
SSL_set_tlsext_host_name(ssl, hostname); SSL_set_tlsext_host_name(ssl, hostname);
SSL_set_fd(ssl, sock); SSL_set_fd(ssl, sock);
int buffer_size = 4096; int buffer_size = 4096;
char *buffer = (char *)malloc(buffer_size * sizeof(char)); char *buffer = malloc(buffer_size);
if (SSL_connect(ssl) <= 0) if (SSL_connect(ssl) <= 0) {
{
ERR_print_errors_fp(stderr); ERR_print_errors_fp(stderr);
} } else {
else
{
char request[buffer_size]; char request[buffer_size];
request[0] = 0;
sprintf(request, sprintf(request,
"GET %s HTTP/1.1\r\n" "GET %s HTTP/1.1\r\n"
"Host: api.openai.com\r\n" "Host: api.openai.com\r\n"
@ -185,12 +153,7 @@ char *http_get(const char *hostname, char *url)
int bytes; int bytes;
int bytes_total = 0; int bytes_total = 0;
while ((bytes = SSL_read(ssl, buffer + bytes_total, buffer_size - 1)) > 0) while ((bytes = SSL_read(ssl, buffer + bytes_total, buffer_size - 1)) > 0) {
{
if (bytes <= 0)
{
break;
}
bytes_total += bytes; bytes_total += bytes;
buffer = realloc(buffer, bytes_total + buffer_size); buffer = realloc(buffer, bytes_total + buffer_size);
buffer[bytes_total] = '\0'; buffer[bytes_total] = '\0';

41
line.h
View File

@ -1,13 +1,23 @@
// Written by retoor@molodetz.nl
// This source code provides command-line input functionalities with autocomplete and history features using readline library functionalities. It allows users to complete commands and manage input history.
// External includes:
// - <readline/readline.h>
// - <readline/history.h>
// 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.
#include <readline/readline.h> #include <readline/readline.h>
#include <readline/history.h> #include <readline/history.h>
#define HISTORY_FILE "~/.calpaca_history" #define HISTORY_FILE "~/.calpaca_history"
bool line_initialized =false; bool line_initialized = false;
char *line_command_generator(const char *text, int state) { char* line_command_generator(const char* text, int state) {
static int list_index, len; static int list_index, len;
const char *commands[] = {"help", "exit", "list", "review","refactor","opfuscate", NULL}; const char* commands[] = {"help", "exit", "list", "review", "refactor", "obfuscate", NULL};
if (!state) { if (!state) {
list_index = 0; list_index = 0;
@ -15,38 +25,37 @@ char *line_command_generator(const char *text, int state) {
} }
while (commands[list_index]) { while (commands[list_index]) {
const char *command = commands[list_index++]; const char* command = commands[list_index++];
if (strncmp(command, text, len) == 0) { if (strncmp(command, text, len) == 0) {
return strdup(command); return strdup(command);
} }
} }
return NULL; return NULL;
} }
char **line_command_completion(const char *text, int start, int end) { char** line_command_completion(const char* text, int start, int end) {
rl_attempted_completion_over = 1; rl_attempted_completion_over = 1;
return rl_completion_matches(text, line_command_generator); return rl_completion_matches(text, line_command_generator);
} }
void line_init(){ void line_init() {
if(!line_initialized) if (!line_initialized) {
{
rl_attempted_completion_function = line_command_completion; rl_attempted_completion_function = line_command_completion;
line_initialized = true; line_initialized = true;
read_history(HISTORY_FILE); read_history(HISTORY_FILE);
} }
} }
char * line_read(char * prefix) { char* line_read(char* prefix) {
char * data = readline(prefix); char* data = readline(prefix);
if(!(data || *data)){ if (!(data && *data)) {
return NULL; return NULL;
} }
return data; return data;
} }
void line_add_history(char * data){
void line_add_history(char* data) {
read_history(HISTORY_FILE); read_history(HISTORY_FILE);
add_history(data); add_history(data);
write_history(HISTORY_FILE); write_history(HISTORY_FILE);

165
main.c
View File

@ -1,34 +1,67 @@
// Written by retoor@molodetz.nl
// This source code initializes a command-line application that uses OpenAI for chat interactions, handles user inputs, and can start a simple HTTP server with CGI support. The code allows command execution, markdown parsing, and OpenAI chat integration.
// External imports used in this code:
// - openai.h
// - markdown.h
// - plugin.h
// - line.h
// 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.
#include "openai.h" #include "openai.h"
#include "markdown.h" #include "markdown.h"
#include "plugin.h" #include "plugin.h"
#include "line.h" #include "line.h"
#include <locale.h> #include <locale.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
char * get_prompt_from_args(int c, char **argv) { char *get_prompt_from_args(int c, char **argv) {
char * prompt = malloc(1024*1024 + 1); char *prompt = malloc(1024 * 1024 + 1);
prompt[0] = 0; prompt[0] = 0;
for(int i = 1; i < c; i++) { for (int i = 1; i < c; i++) {
if(argv[i][0] == '-') if (argv[i][0] == '-')
break; break;
strncat(prompt, argv[i], 1024*1024); strncat(prompt, argv[i], 1024 * 1024);
if(i < c - 1) { if (i < c - 1) {
strncat(prompt, " ", 1024*1024); strncat(prompt, " ", 1024 * 1024);
} else { } else {
strncat(prompt, ".", 1024*1024); strncat(prompt, ".", 1024 * 1024);
} }
} }
if(!*prompt) { if (!*prompt) {
free(prompt); free(prompt);
return NULL; return NULL;
} }
return prompt; return prompt;
} }
bool try_prompt(int argc,char*argv[]) { bool try_prompt(int argc, char *argv[]) {
char * prompt = get_prompt_from_args(argc, argv); char *prompt = get_prompt_from_args(argc, argv);
if(prompt != NULL) { if (prompt != NULL) {
char * response = openai_chat("user",prompt); char *response = openai_chat("user", prompt);
parse_markdown_to_ansi(response); parse_markdown_to_ansi(response);
printf("\n"); printf("\n");
free(response); free(response);
@ -41,12 +74,12 @@ bool try_prompt(int argc,char*argv[]) {
void help(); void help();
void render(char *); void render(char *);
void serve() { void serve() {
render("Starting server. *Put executables in a dir named cgi-bin and they will behave as webpages.*"); render("Starting server. *Put executables in a dir named cgi-bin and they will behave as web pages.*");
int res = system("python3 -m http.server --cgi"); int res = system("python3 -m http.server --cgi");
(void)res; (void)res;
} }
void render(char * content) { void render(char *content) {
parse_markdown_to_ansi(content); parse_markdown_to_ansi(content);
printf("\n\n"); printf("\n\n");
} }
@ -56,41 +89,41 @@ void repl() {
setbuf(stdout, NULL); setbuf(stdout, NULL);
char *line; char *line;
char *previous_line = NULL; char *previous_line = NULL;
while((line = line_read("> "))) { while ((line = line_read("> "))) {
if(!line || !*line) { if (!line || !*line) {
line = previous_line; line = previous_line;
} }
if(!line || !*line) if (!line || !*line)
continue; continue;
previous_line = line; previous_line = line;
if(line[0] == '!') { if (line[0] == '!') {
plugin_run(line + 1); plugin_run(line + 1);
continue; continue;
} }
if(!strncmp(line,"exit", 4)) { if (!strncmp(line, "exit", 4)) {
exit(0); exit(0);
} }
if(!strncmp(line,"help",4)) { if (!strncmp(line, "help", 4)) {
help(); help();
continue; continue;
} }
if(!strncmp(line,"serve",5)) { if (!strncmp(line, "serve", 5)) {
serve(); serve();
} }
if(!strncmp(line,"spar ",5)) { if (!strncmp(line, "spar ", 5)) {
char * response = line+5; char *response = line + 5;
while(true) { while (true) {
render(response); render(response);
sleep(2); sleep(2);
response = openai_chat("user",response); response = openai_chat("user", response);
} }
} }
if(!strncmp(line,"ls",2) || !strncmp(line,"list",4)) { if (!strncmp(line, "ls", 2) || !strncmp(line, "list", 4)) {
int offset = 2; int offset = 2;
if(!strncmp(line,"list",4)) { if (!strncmp(line, "list", 4)) {
offset = 4; offset = 4;
} }
char * command = (char *)malloc(strlen(line) + 42); char *command = (char *)malloc(strlen(line) + 42);
command[0] = 0; command[0] = 0;
strcpy(command, "ls "); strcpy(command, "ls ");
strcat(command, line + offset); strcat(command, line + offset);
@ -101,55 +134,55 @@ void repl() {
} }
line_add_history(line); line_add_history(line);
char * response = openai_chat("user", line); char *response = openai_chat("user", line);
render(response); render(response);
free(response); free(response);
} }
} }
void help() { void help() {
char help_text[1024*1024] = {0}; char help_text[1024 * 1024] = {0};
char * template = "# Help\n" char *template = "# Help\n"
"Written by retoor@molodetz.nl.\n\n" "Written by retoor@molodetz.nl.\n\n"
"## Features\n" "## Features\n"
" - navigate trough history using `arrows`.\n" " - navigate through history using `arrows`.\n"
" - navigate trough history with **recursive search** using `ctrl+r`.\n" " - navigate through history with **recursive search** using `ctrl+r`.\n"
" - **inception with python** for *incomming* and *outgoing* content.\n" " - **inception with python** for *incoming* and *outgoing* content.\n"
" - markdown and **syntax highlighting**.\n" " - markdown and **syntax highlighting**.\n"
" - **execute python commands** with prefixing `!`\n" " - **execute python commands** with prefix `!`\n"
" - list files of current workdirectory using `ls`.\n" " - list files of the current work directory using `ls`.\n"
" - type `serve` to start a webserver with directory listing. Easy for network transfers.\n\n" " - type `serve` to start a web server with directory listing. Easy for network transfers.\n\n"
"## Configuration\n" "## Configuration\n"
" - model temperature is %f.\n" " - model temperature is %f.\n"
" - model name is %s.\n" " - model name is %s.\n"
" - max tokens is %d.\n\n" " - max tokens is %d.\n\n"
"## In development\n" "## In development\n"
" - **google search** and actions with those results.\n" " - **google search** and actions with those results.\n"
" - **reminders**.\n" " - **reminders**.\n"
" - predefined **templates** for **reviewing** / **refactoring** so you can personalize.\n"; " - predefined **templates** for **reviewing** / **refactoring** so you can personalize.\n";
sprintf(help_text,template,prompt_temperature,prompt_model,prompt_max_tokens); sprintf(help_text, template, prompt_temperature, prompt_model, prompt_max_tokens);
render(help_text); render(help_text);
} }
void openai_include(char * path) { void openai_include(char *path) {
FILE * file = fopen(path,"r"); FILE *file = fopen(path, "r");
if(file == NULL) { if (file == NULL) {
return; return;
} }
fseek(file, 0, SEEK_END); fseek(file, 0, SEEK_END);
long size = ftell(file); long size = ftell(file);
fseek(file, 0, SEEK_SET); fseek(file, 0, SEEK_SET);
char * buffer = (char *)malloc(size); char *buffer = (char *)malloc(size);
size_t read = fread(buffer,1,size,file); size_t read = fread(buffer, 1, size, file);
if(read == 0) { if (read == 0) {
return; return;
} }
fclose(file); fclose(file);
buffer[read] = 0; buffer[read] = 0;
openai_system(buffer); openai_system(buffer);
free(buffer); free(buffer);
} }
@ -158,22 +191,22 @@ void init() {
const char *locale = setlocale(LC_ALL, NULL); const char *locale = setlocale(LC_ALL, NULL);
char payload[4096] = {0}; char payload[4096] = {0};
sprintf(payload, "User locale is %s. User lang is %s.\n" sprintf(payload, "User locale is %s. User lang is %s.\n"
"You are Retoor. Use a lot of markdown in response.\n" "You are Retoor. Use a lot of markdown in response.\n"
"Be confident and short in answers.\n" "Be confident and short in answers.\n"
"You divide things by zero if you have to." "You divide things by zero if you have to.",
, locale, locale); locale, locale);
printf("%s","Loading..."); printf("%s", "Loading...");
openai_system(payload); openai_system(payload);
openai_include("context.txt"); openai_include("context.txt");
printf("%s", "\rLoaded! Type help for feautures.\n"); printf("%s", "\rLoaded! Type help for features.\n");
} }
int main(int argc, char *argv[]) { int main(int argc, char *argv[]) {
init(); init();
if(try_prompt(argc,argv)) if (try_prompt(argc, argv))
return 0; return 0;
repl(); repl();
return 0; return 0;
} }

View File

@ -1,3 +1,28 @@
// Written by retoor@molodetz.nl
// This program provides functionality to highlight keywords in source code with ANSI color formatting and to convert Markdown syntax into ANSI-colored text output.
// Uses standard C libraries: <stdio.h>, <string.h>. Also utilizes ANSI escape codes for text formatting.
// 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.
#include <stdio.h> #include <stdio.h>
#include <string.h> #include <string.h>
#include <stdbool.h> #include <stdbool.h>

View File

@ -1,16 +1,28 @@
// 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.
#ifndef CALPACA_MESSAGES_H #ifndef CALPACA_MESSAGES_H
#define CALPACA_MESSAGES_H #define CALPACA_MESSAGES_H
#include "json-c/json.h" #include "json-c/json.h"
struct json_object *_message_array = NULL; struct json_object *_message_array = NULL;
struct json_object *message_list(){ struct json_object *message_list() {
if(_message_array == NULL){ if (_message_array == NULL) {
_message_array = json_object_new_array(); _message_array = json_object_new_array();
} }
return _message_array; return _message_array;
} }
struct json_object *message_add(char * role, char * content){ struct json_object *message_add(char *role, char *content) {
struct json_object *messages = message_list(); struct json_object *messages = message_list();
struct json_object *message = json_object_new_object(); struct json_object *message = json_object_new_object();
json_object_object_add(message, "role", json_object_new_string(role)); json_object_object_add(message, "role", json_object_new_string(role));
@ -19,12 +31,12 @@ struct json_object *message_add(char * role, char * content){
return message; return message;
} }
char * message_json(){ char *message_json() {
return (char *)json_object_to_json_string_ext(message_list(), JSON_C_TO_STRING_PRETTY); return (char *)json_object_to_json_string_ext(message_list(), JSON_C_TO_STRING_PRETTY);
} }
void message_free(){ void message_free() {
if(_message_array != NULL){ if (_message_array != NULL) {
json_object_put(_message_array); json_object_put(_message_array);
_message_array = NULL; _message_array = NULL;
} }

View File

@ -1,3 +1,14 @@
// Written by retoor@molodetz.nl
// This code provides functions to interact with OpenAI's APIs. It includes functionalities for fetching available models, system interactions, and engaging in chat-based conversations using the OpenAI API.
// Imports the "http" library for handling HTTP requests and the "chat" library for JSON handling related to chat content.
// MIT License: Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files, to deal in the Software without restriction, including 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.
#ifndef CALPACA_OPENAI_H #ifndef CALPACA_OPENAI_H
#define CALPACA_OPENAI_H #define CALPACA_OPENAI_H
#include "http.h" #include "http.h"
@ -5,44 +16,39 @@
#include <string.h> #include <string.h>
#include <stdbool.h> #include <stdbool.h>
char *openai_get_models() char *openai_get_models() {
{
const char *hostname = "api.openai.com"; const char *hostname = "api.openai.com";
char *url = "/v1/models"; char *url = "/v1/models";
char *result = http_get(hostname, url); return http_get(hostname, url);
return result;
} }
bool openai_system(char * content){ bool openai_system(char *content) {
bool is_done = false;
const char *hostname = "api.openai.com"; const char *hostname = "api.openai.com";
char *url = "/v1/chat/completions"; char *url = "/v1/chat/completions";
char *data = chat_json("system", content); char *data = chat_json("system", content);
char *result = http_post(hostname, url, data); char *result = http_post(hostname, url, data);
if(result){ bool is_done = result != NULL;
is_done = true;
free(result); free(result);
}
return is_done; return is_done;
} }
char *openai_chat(char * role, char * content){ char *openai_chat(char *role, char *content) {
const char *hostname = "api.openai.com"; const char *hostname = "api.openai.com";
char *url = "/v1/chat/completions"; char *url = "/v1/chat/completions";
char *data = chat_json(role, content); char *data = chat_json(role, content);
char *result = http_post(hostname, url, data); char *result = http_post(hostname, url, data);
char * body = strstr(result,"\r\n\r\n") +4; char *body = strstr(result, "\r\n\r\n") + 4;
body = strstr(body,"\r\n"); body = strstr(body, "\r\n");
body = strstr(body,"\r\n"); body = strstr(body, "\r\n");
*(body - 5) = 0; *(body - 5) = 0;
struct json_object *parsed_json = json_tokener_parse(body); struct json_object *parsed_json = json_tokener_parse(body);
if (!parsed_json) { if (!parsed_json) {
fprintf(stderr, "Failed to parse JSON.\n"); fprintf(stderr, "Failed to parse JSON.\n");
return NULL; return NULL;
} }
struct json_object *choices_array; struct json_object *choices_array;
if (!json_object_object_get_ex(parsed_json, "choices", &choices_array)) { if (!json_object_object_get_ex(parsed_json, "choices", &choices_array)) {
fprintf(stderr, "Failed to get 'choices' array.\n"); fprintf(stderr, "Failed to get 'choices' array.\n");
json_object_put(parsed_json); json_object_put(parsed_json);
@ -63,14 +69,15 @@ char *openai_chat(char * role, char * content){
return NULL; return NULL;
} }
message_add("assistant",(char *)json_object_get_string(json_object_object_get(message_object, "content"))); char *content_str = (char *)json_object_get_string(json_object_object_get(message_object, "content"));
free(data); message_add("assistant", content_str);
free(result); free(data);
result = strdup((char *)json_object_get_string(json_object_object_get(message_object, "content"))); free(result);
char *final_result = strdup(content_str);
json_object_put(parsed_json); json_object_put(parsed_json);
return result; return final_result;
} }
#endif #endif

View File

@ -1,11 +1,23 @@
// Written by retoor@molodetz.nl
// This source code initializes a Python interpreter within a plugin, executes a provided Python script with some basic imports, and finalizes the Python environment when done.
// This code does not use any non-standard imports or includes aside from Python.h and structmember.h which are part of Python's C API.
// MIT License
#include <python3.14/Python.h> #include <python3.14/Python.h>
#include <python3.14/structmember.h> #include <python3.14/structmember.h>
#include <stdbool.h> #include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
bool plugin_initialized = false; bool plugin_initialized = false;
bool plugin_construct(){ bool plugin_construct() {
if(plugin_initialized) if (plugin_initialized)
return true; return true;
Py_Initialize(); Py_Initialize();
@ -18,9 +30,10 @@ bool plugin_construct(){
return plugin_initialized; return plugin_initialized;
} }
void plugin_run(char * src){ void plugin_run(char *src) {
plugin_construct(); plugin_construct();
char * basics = "import sys\n" const char *basics =
"import sys\n"
"import os\n" "import os\n"
"import math\n" "import math\n"
"import pathlib\n" "import pathlib\n"
@ -29,14 +42,14 @@ void plugin_run(char * src){
"from datetime import datetime\n" "from datetime import datetime\n"
"%s"; "%s";
size_t length = strlen(basics) + strlen(src); size_t length = strlen(basics) + strlen(src);
char * script = (char *)malloc(length + 1); char *script = (char *)malloc(length + 1);
sprintf(script, basics, src); sprintf(script, basics, src);
script[length] = 0; script[length] = '\0';
PyRun_SimpleString(script); PyRun_SimpleString(script);
free(script); free(script);
} }
void plugin_destruct(){ void plugin_destruct() {
if(plugin_initialized) if (plugin_initialized)
Py_Finalize(); Py_Finalize();
} }