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

35
chat.h
View File

@ -1,8 +1,40 @@
// 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
#define CALPACA_PROMPT_H
#include <json-c/json.h>
#include "messages.h"
#include "http.h"
char *prompt_model = "gpt-4o-mini";
int prompt_max_tokens = 100;
double prompt_temperature = 0.5;
@ -12,6 +44,7 @@ json_object * _prompt =NULL;
void chat_free() {
if (_prompt == NULL)
return;
json_object_put(_prompt);
_prompt = NULL;
}
@ -19,11 +52,13 @@ void chat_free(){
char *chat_json(char *role, char *message) {
chat_free();
message_add(role, message);
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, "messages", message_list());
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));
return (char *)json_object_to_json_string_ext(root_object, JSON_C_TO_STRING_PRETTY);
}

99
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
#define CALPACA_HTTP_H
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
@ -11,19 +20,16 @@
#include "auth.h"
#include <json-c/json.h>
void init_openssl()
{
void init_openssl() {
SSL_load_error_strings();
OpenSSL_add_ssl_algorithms();
}
void cleanup_openssl()
{
void cleanup_openssl() {
EVP_cleanup();
}
SSL_CTX *create_context()
{
SSL_CTX *create_context() {
const SSL_METHOD *method = TLS_method();
SSL_CTX *ctx = SSL_CTX_new(method);
SSL_CTX_load_verify_locations(ctx, "/etc/ssl/certs/ca-certificates.crt", NULL);
@ -31,15 +37,10 @@ SSL_CTX *create_context()
return ctx;
}
SSL_CTX *create_context2()
{
const SSL_METHOD *method;
SSL_CTX *ctx;
method = TLS_client_method();
ctx = SSL_CTX_new(method);
if (!ctx)
{
SSL_CTX *create_context2() {
const SSL_METHOD *method = TLS_client_method();
SSL_CTX *ctx = SSL_CTX_new(method);
if (!ctx) {
perror("Unable to create SSL context");
ERR_print_errors_fp(stderr);
exit(EXIT_FAILURE);
@ -48,21 +49,18 @@ SSL_CTX *create_context2()
return ctx;
}
int create_socket(const char *hostname, int port)
{
int create_socket(const char *hostname, int port) {
struct hostent *host;
struct sockaddr_in addr;
host = gethostbyname(hostname);
if (!host)
{
if (!host) {
perror("Unable to resolve host");
exit(EXIT_FAILURE);
}
int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0)
{
if (sock < 0) {
perror("Unable to create socket");
exit(EXIT_FAILURE);
}
@ -71,8 +69,7 @@ int create_socket(const char *hostname, int port)
addr.sin_port = htons(port);
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");
close(sock);
exit(EXIT_FAILURE);
@ -81,35 +78,24 @@ int create_socket(const char *hostname, int port)
return sock;
}
char *http_post(const char *hostname, char *url, char *data)
{
char *http_post(const char *hostname, char *url, char *data) {
init_openssl();
int port = 443;
SSL_CTX *ctx = create_context();
int sock = create_socket(hostname, port);
SSL *ssl = SSL_new(ctx);
SSL_set_connect_state(ssl);
SSL_set_tlsext_host_name(ssl, hostname);
SSL_set_fd(ssl, sock);
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);
}
else
{
} else {
size_t len = strlen(data);
char *request = (char *)malloc(len + 4096);
request[0] = 0;
char *request = malloc(len + 4096);
sprintf(request,
"POST %s HTTP/1.1\r\n"
"Content-Length: %ld\r\n"
@ -122,20 +108,13 @@ char *http_post(const char *hostname, char *url, char *data)
SSL_write(ssl, request, strlen(request));
free(request);
int bytes;
int bytes_total = 0;
while ((bytes = SSL_read(ssl, buffer + bytes_total, buffer_size - 1)) > 0)
{
if (bytes <= 0)
{
break;
}
while ((bytes = SSL_read(ssl, buffer + bytes_total, buffer_size - 1)) > 0) {
bytes_total += bytes;
buffer = realloc(buffer, bytes_total + buffer_size);
buffer[bytes_total] = '\0';
}
buffer[bytes_total] = '\0';
}
SSL_free(ssl);
@ -146,34 +125,23 @@ char *http_post(const char *hostname, char *url, char *data)
return buffer;
}
char *http_get(const char *hostname, char *url)
{
char *http_get(const char *hostname, char *url) {
init_openssl();
int port = 443;
SSL_CTX *ctx = create_context();
int sock = create_socket(hostname, port);
SSL *ssl = SSL_new(ctx);
SSL_set_connect_state(ssl);
SSL_set_tlsext_host_name(ssl, hostname);
SSL_set_fd(ssl, sock);
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);
}
else
{
} else {
char request[buffer_size];
request[0] = 0;
sprintf(request,
"GET %s HTTP/1.1\r\n"
"Host: api.openai.com\r\n"
@ -185,12 +153,7 @@ char *http_get(const char *hostname, char *url)
int bytes;
int bytes_total = 0;
while ((bytes = SSL_read(ssl, buffer + bytes_total, buffer_size - 1)) > 0)
{
if (bytes <= 0)
{
break;
}
while ((bytes = SSL_read(ssl, buffer + bytes_total, buffer_size - 1)) > 0) {
bytes_total += bytes;
buffer = realloc(buffer, bytes_total + buffer_size);
buffer[bytes_total] = '\0';

19
line.h
View File

@ -1,3 +1,13 @@
// 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/history.h>
@ -7,7 +17,7 @@ bool line_initialized =false;
char* line_command_generator(const char* text, int state) {
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) {
list_index = 0;
@ -30,22 +40,21 @@ char **line_command_completion(const char *text, int start, int end) {
}
void line_init() {
if(!line_initialized)
{
if (!line_initialized) {
rl_attempted_completion_function = line_command_completion;
line_initialized = true;
read_history(HISTORY_FILE);
}
}
char* line_read(char* prefix) {
char* data = readline(prefix);
if(!(data || *data)){
if (!(data && *data)) {
return NULL;
}
return data;
}
void line_add_history(char* data) {
read_history(HISTORY_FILE);
add_history(data);

49
main.c
View File

@ -1,9 +1,42 @@
// 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 "markdown.h"
#include "plugin.h"
#include "line.h"
#include <locale.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
char *get_prompt_from_args(int c, char **argv) {
char *prompt = malloc(1024 * 1024 + 1);
@ -112,12 +145,12 @@ void help() {
char *template = "# Help\n"
"Written by retoor@molodetz.nl.\n\n"
"## Features\n"
" - navigate trough history using `arrows`.\n"
" - navigate trough history with **recursive search** using `ctrl+r`.\n"
" - **inception with python** for *incomming* and *outgoing* content.\n"
" - navigate through history using `arrows`.\n"
" - navigate through history with **recursive search** using `ctrl+r`.\n"
" - **inception with python** for *incoming* and *outgoing* content.\n"
" - markdown and **syntax highlighting**.\n"
" - **execute python commands** with prefixing `!`\n"
" - list files of current workdirectory using `ls`.\n"
" - **execute python commands** with prefix `!`\n"
" - list files of the current work directory using `ls`.\n"
" - type `serve` to start a web server with directory listing. Easy for network transfers.\n\n"
"## Configuration\n"
" - model temperature is %f.\n"
@ -160,13 +193,13 @@ void init() {
sprintf(payload, "User locale is %s. User lang is %s.\n"
"You are Retoor. Use a lot of markdown in response.\n"
"Be confident and short in answers.\n"
"You divide things by zero if you have to."
, locale, locale);
"You divide things by zero if you have to.",
locale, locale);
printf("%s", "Loading...");
openai_system(payload);
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[]) {

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 <string.h>
#include <stdbool.h>

View File

@ -1,6 +1,18 @@
// 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
#define CALPACA_MESSAGES_H
#include "json-c/json.h"
struct json_object *_message_array = NULL;
struct json_object *message_list() {

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
#define CALPACA_OPENAI_H
#include "http.h"
@ -5,25 +16,20 @@
#include <string.h>
#include <stdbool.h>
char *openai_get_models()
{
char *openai_get_models() {
const char *hostname = "api.openai.com";
char *url = "/v1/models";
char *result = http_get(hostname, url);
return result;
return http_get(hostname, url);
}
bool openai_system(char *content) {
bool is_done = false;
const char *hostname = "api.openai.com";
char *url = "/v1/chat/completions";
char *data = chat_json("system", content);
char *result = http_post(hostname, url, data);
if(result){
is_done = true;
bool is_done = result != NULL;
free(result);
}
return is_done;
}
@ -63,14 +69,15 @@ char *openai_chat(char * role, char * content){
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"));
message_add("assistant", content_str);
free(data);
free(result);
result = strdup((char *)json_object_get_string(json_object_object_get(message_object, "content")));
char *final_result = strdup(content_str);
json_object_put(parsed_json);
return result;
return final_result;
}
#endif

View File

@ -1,6 +1,18 @@
// 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/structmember.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
bool plugin_initialized = false;
@ -20,7 +32,8 @@ bool plugin_construct(){
void plugin_run(char *src) {
plugin_construct();
char * basics = "import sys\n"
const char *basics =
"import sys\n"
"import os\n"
"import math\n"
"import pathlib\n"
@ -31,7 +44,7 @@ void plugin_run(char * src){
size_t length = strlen(basics) + strlen(src);
char *script = (char *)malloc(length + 1);
sprintf(script, basics, src);
script[length] = 0;
script[length] = '\0';
PyRun_SimpleString(script);
free(script);
}