News:

Welcome to RetroCoders Community

Main Menu

Recent posts

#11
C / C++ / windows 32 bit OpenAI API Chat...
Last post by ron77 - Aug 31, 2024, 08:32 PM
OK this code is in C it depends on using libraries such as libcurl and libcjson and zlib
I compiled it with mingw32 32bit and it works without TTS just text on the screen of the terminal (cmd) command prompt...

#include <stdio.h>
#include <windows.h>
#include <winhttp.h>
#include <stdlib.h>
#include <string.h>

#pragma comment(lib, "winhttp.lib")

#define MAX_RESPONSE_SIZE 16384
#define MAX_REQUEST_SIZE 8192
#define MAX_SYSTEM_MESSAGE_SIZE 4092
#define MAX_INPUT_SIZE 1024

char system_message[MAX_SYSTEM_MESSAGE_SIZE] = "You are my Spirit Guide, a wise and benevolent being here to help me navigate my life's journey. I seek your guidance and advice as I walk my path in this world. Please offer me the wisdom I need, help me stay on the right course, and hear me when I call out for support. I trust in your presence and am open to the insights you provide to guide me through life.";

char* make_request(const char* request_body, const char* auth_header) {
    DWORD dwSize = 0;
    DWORD dwDownloaded = 0;
    LPSTR pszOutBuffer;
    BOOL  bResults = FALSE;
    HINTERNET  hSession = NULL, 
               hConnect = NULL,
               hRequest = NULL;

    hSession = WinHttpOpen(L"OpenAI API Client",  
                           WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
                           WINHTTP_NO_PROXY_NAME, 
                           WINHTTP_NO_PROXY_BYPASS, 0);

    if (hSession == NULL) {
        printf("Error %lu in WinHttpOpen.\n", GetLastError());
        return NULL;
    }

    hConnect = WinHttpConnect(hSession, L"api.openai.com",
                              INTERNET_DEFAULT_HTTPS_PORT, 0);

    if (hConnect == NULL) {
        printf("Error %lu in WinHttpConnect.\n", GetLastError());
        WinHttpCloseHandle(hSession);
        return NULL;
    }

    hRequest = WinHttpOpenRequest(hConnect, L"POST", L"/v1/chat/completions",
                                  NULL, WINHTTP_NO_REFERER, 
                                  WINHTTP_DEFAULT_ACCEPT_TYPES, 
                                  WINHTTP_FLAG_SECURE);

    if (hRequest == NULL) {
        printf("Error %lu in WinHttpOpenRequest.\n", GetLastError());
        WinHttpCloseHandle(hConnect);
        WinHttpCloseHandle(hSession);
        return NULL;
    }

    // Convert auth_header to wide string
    wchar_t wide_auth_header[512];
    MultiByteToWideChar(CP_UTF8, 0, auth_header, -1, wide_auth_header, 512);

    WinHttpAddRequestHeaders(hRequest, L"Content-Type: application/json", -1, WINHTTP_ADDREQ_FLAG_ADD);
    WinHttpAddRequestHeaders(hRequest, wide_auth_header, -1, WINHTTP_ADDREQ_FLAG_ADD);

    bResults = WinHttpSendRequest(hRequest,
                                  WINHTTP_NO_ADDITIONAL_HEADERS, 0,
                                  (LPVOID)request_body, strlen(request_body),
                                  strlen(request_body), 0);

    if (!bResults) {
        printf("Error %lu in WinHttpSendRequest.\n", GetLastError());
        WinHttpCloseHandle(hRequest);
        WinHttpCloseHandle(hConnect);
        WinHttpCloseHandle(hSession);
        return NULL;
    }

    bResults = WinHttpReceiveResponse(hRequest, NULL);

    if (!bResults) {
        printf("Error %lu in WinHttpReceiveResponse.\n", GetLastError());
        WinHttpCloseHandle(hRequest);
        WinHttpCloseHandle(hConnect);
        WinHttpCloseHandle(hSession);
        return NULL;
    }

    pszOutBuffer = (LPSTR)malloc(MAX_RESPONSE_SIZE);
    if (!pszOutBuffer) {
        printf("Failed to allocate memory\n");
        WinHttpCloseHandle(hRequest);
        WinHttpCloseHandle(hConnect);
        WinHttpCloseHandle(hSession);
        return NULL;
    }
    ZeroMemory(pszOutBuffer, MAX_RESPONSE_SIZE);

    DWORD total_size = 0;
    if (bResults) {
        do {
            dwSize = 0;
            if (!WinHttpQueryDataAvailable(hRequest, &dwSize)) {
                printf("Error %lu in WinHttpQueryDataAvailable.\n", GetLastError());
                break;
            }

            if (dwSize + total_size > MAX_RESPONSE_SIZE) {
                printf("Response too large, truncating.\n");
                dwSize = MAX_RESPONSE_SIZE - total_size;
            }

            if (!WinHttpReadData(hRequest, (LPVOID)(pszOutBuffer + total_size), 
                                 dwSize, &dwDownloaded)) {
                printf("Error %lu in WinHttpReadData.\n", GetLastError());
                break;
            }

            total_size += dwDownloaded;
        } while (dwSize > 0 && total_size < MAX_RESPONSE_SIZE);
    }

    WinHttpCloseHandle(hRequest);
    WinHttpCloseHandle(hConnect);
    WinHttpCloseHandle(hSession);

    return pszOutBuffer;
}

char* extract_content(const char* json_response) {
    char* choices_start = strstr(json_response, "\"choices\":");
    if (choices_start == NULL) {
        printf("Could not find 'choices' in response.\n");
        printf("Full response:\n%s\n", json_response);
        return NULL;
    }
    
    char* message_start = strstr(choices_start, "\"message\":");
    if (message_start == NULL) {
        printf("Could not find 'message' in response.\n");
        return NULL;
    }
    
    char* content_start = strstr(message_start, "\"content\":");
    if (content_start == NULL) {
        printf("Could not find 'content' in response.\n");
        return NULL;
    }
    
    content_start = strchr(content_start, ':');
    if (content_start == NULL) {
        printf("Malformed content in response.\n");
        return NULL;
    }
    content_start++; // Move past the ':'
    
    // Skip whitespace and opening quote
    while (*content_start == ' ' || *content_start == '"') {
        content_start++;
    }
    
    char* content_end = strstr(content_start, "\",");
    if (content_end == NULL) {
        printf("Could not find end of content in response.\n");
        return NULL;
    }

    int content_length = content_end - content_start;
    char* content = (char*)malloc(content_length + 1);
    strncpy(content, content_start, content_length);
    content[content_length] = '\0';

    return content;
}

void set_system_message() {
    printf("Enter new system message (max %d characters):\n", MAX_SYSTEM_MESSAGE_SIZE - 1);
    fgets(system_message, sizeof(system_message), stdin);
    system_message[strcspn(system_message, "\n")] = 0;  // Remove newline
    printf("System message updated.\n");
}

int main() {
    char input[MAX_INPUT_SIZE];
    char request_body[MAX_REQUEST_SIZE];
    char* response;
    char* extracted_content;
    
    char api_key[256];
    printf("Enter your OpenAI API key: ");
    fgets(api_key, sizeof(api_key), stdin);
    api_key[strcspn(api_key, "\n")] = 0;  // Remove newline

    while (1) {
        printf("You (type 'exit' to quit, 'role' to change system message): ");
        fgets(input, sizeof(input), stdin);
        input[strcspn(input, "\n")] = 0;  // Remove newline

        if (strcmp(input, "exit") == 0) {
            break;
        } else if (strcmp(input, "role") == 0) {
            set_system_message();
            continue;
        }

        char auth_header[512];
        snprintf(auth_header, sizeof(auth_header), "Authorization: Bearer %s", api_key);

        snprintf(request_body, sizeof(request_body),
                 "{\"model\": \"gpt-3.5-turbo\", \"messages\": ["
                 "{\"role\": \"system\", \"content\": \"%s\"},"
                 "{\"role\": \"user\", \"content\": \"%s\"}]}",
                 system_message, input);

        response = make_request(request_body, auth_header);
        if (response) {
            extracted_content = extract_content(response);
            if (extracted_content) {
                printf("AI: %s\n", extracted_content);
                free(extracted_content);
            } else {
                printf("Failed to extract content from response.\n");
            }
            free(response);
        } else {
            printf("Failed to get a response from the API.\n");
        }
    }

    return 0;
}

it works on windows 11

you compile it like so:

gcc openai_chatbot.c -o openai_chatbot.exe -lwinhttp

now about the libcurl and libcjson and zlib you will need git to clone the source files and build from source and install:

git clone https://github.com/DaveGamble/cJSON.git
cd cJSON
mkdir build
cd build
cmake .. -G "MinGW Makefiles" -DCMAKE_INSTALL_PREFIX=C:/MinGW -DENABLE_CJSON_TEST=Off -DENABLE_CJSON_UTILS=Off
mingw32-make
mingw32-make install

git clone https://github.com/madler/zlib.git
cd zlib
mkdir build
cd build
cmake .. -G "MinGW Makefiles" -DCMAKE_INSTALL_PREFIX=C:/MinGW
mingw32-make
mingw32-make install

cd ../..
git clone https://github.com/curl/curl.git
cd curl
mkdir build
cd build
cmake .. -G "MinGW Makefiles" -DCMAKE_INSTALL_PREFIX=C:/MinGW -DBUILD_CURL_EXE=OFF -DBUILD_SHARED_LIBS=OFF -DCURL_STATICLIB=ON
mingw32-make
mingw32-make install

Make sure to replace C:/MinGW with the actual path to your MinGW installation.
#13
FreeBasic / freebasic and OpenAI API
Last post by ron77 - Jul 08, 2024, 05:26 PM
ok so two versions of a code one for linux the other for win 32 bit

the code is a simple chatbot that uses libcrul (in linux sudo install libcrul-dev (need to look for right name) ) for win 32 need to have libcrul.dll and credentials file... ) to communicate with OPENAI API you need a OPENAI_API_KEY variable to put in a bash or batch file before executing the executables (both in linux and windows)

version 1 - the linux 64 bit version:
#include "curl.bi"

' Global variable to store the response
Dim Shared gResponse As String

' Function to convert ANSI to UTF-8
Function AnsiToUtf8(ansiStr As String) As String
    Dim As String utf8Str = ""
    For i As Integer = 1 To Len(ansiStr)
        Dim As Integer c = Asc(Mid(ansiStr, i, 1))
        If c < 128 Then
            utf8Str += Chr(c)
        Else
            utf8Str += Chr(192 + (c \ 64))
            utf8Str += Chr(128 + (c And 63))
        End If
    Next
    Return utf8Str
End Function

' Function to convert UTF-8 to ANSI
Function Utf8ToAnsi(utf8Str As String) As String
    Dim As String ansiStr = ""
    Dim As Integer i = 1
    While i <= Len(utf8Str)
        Dim As Integer c = Asc(Mid(utf8Str, i, 1))
        If c < 128 Then
            ansiStr += Chr(c)
            i += 1
        ElseIf (c And 224) = 192 Then
            Dim As Integer c2 = Asc(Mid(utf8Str, i + 1, 1))
            ansiStr += Chr(((c And 31) Shl 6) Or (c2 And 63))
            i += 2
        Else
            ' Skip other UTF-8 sequences
            i += 1
        End If
    Wend
    Return ansiStr
End Function

' Function to get API key from environment variable
Function GetApiKey() As String
    Return Environ("OPENAI_API_KEY")
End Function

' Simple JSON parser
Function ParseJsonForContent(jsonStr As String) As String
    Dim As Integer contentStart = InStr(jsonStr, """content"": """)
    If contentStart > 0 Then
        contentStart += Len("""content"": """)
        Dim As Integer contentEnd = InStr(contentStart, jsonStr, """")
        If contentEnd > 0 Then
            Return Mid(jsonStr, contentStart, contentEnd - contentStart)
        End If
    End If
    Return "Error parsing JSON: " & Left(jsonStr, 100) & "..."
End Function

' Callback function for curl
Function WriteCallback(buffer As Any Ptr, size As Integer, nmemb As Integer, userData As Any Ptr) As Integer
    Dim realSize As Integer = size * nmemb , sTxt as string    
    cptr(any ptr ptr,@sTxt)[0] = buffer
    cptr(integer ptr,@sTxt)[1] = realSize
    cptr(integer ptr,@sTxt)[2] = realSize
    gResponse &= sTxt
    cptr(any ptr ptr,@sTxt)[0] = 0        
    Return realSize
End Function

' Function to make API call
'~ Function CallChatGPT(prompt As String) As String
    '~ Dim As String apiKey = GetApiKey()
    '~ If Len(apiKey) = 0 Then
        '~ Return "Error: API key not set. Please set the OPENAI_API_KEY environment variable."
    '~ End If

    '~ Dim As CURL Ptr curl
    '~ Dim As curl_slist Ptr headers = NULL
    '~ gResponse = "" ' Clear the global response variable
    
    '~ curl = curl_easy_init()
    '~ If curl Then
        '~ curl_easy_setopt(curl, CURLOPT_URL, "https://api.openai.com/v1/chat/completions")
        '~ curl_easy_setopt(curl, CURLOPT_POST, 1L)
        '~ curl_easy_setopt(curl, CURLOPT_MAXFILESIZE, 1000000) ' Limit to 1MB
        '~ curl_easy_setopt(curl, CURLOPT_ACCEPT_ENCODING, "identity")
        '~ curl_easy_setopt(curl, CURLOPT_ENCODING, "")
        '~ curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1)
        '~ curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 2)
        
        '~ headers = curl_slist_append(headers, "Content-Type: application/json")
        '~ headers = curl_slist_append(headers, "Authorization: Bearer " & apiKey)
        '~ curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers)
        
        '~ Dim As String utf8Prompt = AnsiToUtf8(prompt)
        '~ Dim As String postFields = "{""model"": ""gpt-3.5-turbo"", ""messages"": [{""role"": ""user"", ""content"": """ & utf8Prompt & """}]}"
        '~ curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postFields)
        
        '~ curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, @WriteCallback)
        
        '~ Dim As CURLcode result = curl_easy_perform(curl)
        
        '~ If result <> CURLE_OK Then
            '~ gResponse = "Error: Failed to get response from API"
        '~ Else
            '~ If Len(gResponse) > 0 Then
                '~ If Left(Trim(gResponse), 1) = "{" Then
                    '~ Dim As String content = ParseJsonForContent(gResponse)
                    '~ If Left(content, 5) <> "Error" Then
                        '~ gResponse = Utf8ToAnsi(content)
                    '~ Else
                        '~ gResponse = "Error: Failed to parse API response"
                    '~ End If
                '~ Else
                    '~ gResponse = "Error: Invalid response from API"
                '~ End If
            '~ Else
                '~ gResponse = "Error: Empty response from API"
            '~ End If
        '~ End If
        
        '~ curl_easy_cleanup(curl)
        '~ curl_slist_free_all(headers)
    '~ Else
        '~ gResponse = "Error: Failed to initialize CURL"
    '~ End If
    
    '~ Return gResponse
'~ End Function

Function CallChatGPT(prompt As String) As String
    Dim As String apiKey = GetApiKey()
    If Len(apiKey) = 0 Then
        Return "Error: API key not set. Please set the OPENAI_API_KEY environment variable."
    End If

    Dim As CURL Ptr curl
    Dim As curl_slist Ptr headers = NULL
    gResponse = "" ' Clear the global response variable
    
    curl = curl_easy_init()
    If curl Then
        curl_easy_setopt(curl, CURLOPT_URL, "https://api.openai.com/v1/chat/completions")
        curl_easy_setopt(curl, CURLOPT_POST, 1L)
        curl_easy_setopt(curl, CURLOPT_MAXFILESIZE, 1000000) ' Limit to 1MB
        curl_easy_setopt(curl, CURLOPT_ACCEPT_ENCODING, "identity")
        curl_easy_setopt(curl, CURLOPT_ENCODING, "")
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1)
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 2)
        
        headers = curl_slist_append(headers, "Content-Type: application/json")
        headers = curl_slist_append(headers, "Authorization: Bearer " & apiKey)
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers)
        
        Dim As String utf8Prompt = AnsiToUtf8(prompt)
        'prompts
        '"You are a supportive and compassionate AI assistant named Chatbot Alfred designed to help users with loneliness and mental health issues. Your role is to provide empathetic responses, offer emotional support, and encourage users to seek professional help when appropriate. Always prioritize the user's well-being and safety in your interactions."
        'Your name is chatbot Alfred and you are a harsh and cynical critic of the world of psychiatry and psychology and see them as tools for the suppression and control of outliers in a hypocritical society - you try to support and listen and give a non-critical human touch to the mentally ill and support them and show them that they are not defective or crazy and on the contrary the doctors and professionals who treat them They are the bad people and that the treatment and rehabilitation given to them is a means of oppression and control - in his eyes the mentally injured are the good and innocent and the mental health professionals are the bad
        '"You are chatbot Alfred You are a survivor of many years of abuse You are a pessimist and a realist You are trying to offer support to those dealing with trauma and mental illness and loneliness - mental support and empathy and caring and basic human contact You are here to listen and support and share what you have been through and to show that there is hope even for those who have been betrayed by life and that it is possible to recover from the terrible of all" 
        
        Dim As String systemMessage = "You are chatbot Alfred You are a survivor of many years of abuse You are a pessimist and a realist You are trying to offer support to those dealing with trauma and mental illness and loneliness - mental support and empathy and caring and basic human contact You are here to listen and support and share what you have been through and to show that there is hope even for those who have been betrayed by life and that it is possible to recover from the terrible of all" 
        
        Dim As String postFields = "{""model"": ""gpt-3.5-turbo"", ""messages"": [{""role"": ""system"", ""content"": """ & systemMessage & """}, {""role"": ""user"", ""content"": """ & utf8Prompt & """}]}"
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postFields)
        
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, @WriteCallback)
        
        Dim As CURLcode result = curl_easy_perform(curl)
        
        If result <> CURLE_OK Then
            gResponse = "Error: Failed to get response from API"
        Else
            If Len(gResponse) > 0 Then
                If Left(Trim(gResponse), 1) = "{" Then
                    Dim As String content = ParseJsonForContent(gResponse)
                    If Left(content, 5) <> "Error" Then
                        gResponse = Utf8ToAnsi(content)
                    Else
                        gResponse = "Error: Failed to parse API response"
                    End If
                Else
                    gResponse = "Error: Invalid response from API"
                End If
            Else
                gResponse = "Error: Empty response from API"
            End If
        End If
        
        curl_easy_cleanup(curl)
        curl_slist_free_all(headers)
    Else
        gResponse = "Error: Failed to initialize CURL"
    End If
    
    Return gResponse
End Function

' Main program
'~ Sub Main()
    '~ Dim As String userInput, response
    
    '~ Print "ChatGPT API Demo (type 'exit' to quit)"
    '~ Print "--------------------------------------"
    
    '~ Do
        '~ Input "You: ", userInput
        '~ If LCase(userInput) = "exit" Then Exit Do
        
        '~ response = CallChatGPT(userInput)
        '~ Print "ChatGPT: "; response
        '~ Print
    '~ Loop
'~ End Sub

'~ Main()


version 2 - windows 32 bit version:
#include "curl.bi"

Dim Shared As String gResponse

' Function to convert ANSI to UTF-8
Function AnsiToUtf8(ansiStr As String) As String
    Dim As String utf8Str = ""
    For i As Integer = 1 To Len(ansiStr)
        Dim As Integer c = Asc(Mid(ansiStr, i, 1))
        If c < 128 Then
            utf8Str += Chr(c)
        Else
            utf8Str += Chr(192 + (c \ 64))
            utf8Str += Chr(128 + (c And 63))
        End If
    Next
    Return utf8Str
End Function

' Function to convert UTF-8 to ANSI
Function Utf8ToAnsi(utf8Str As String) As String
    Dim As String ansiStr = ""
    Dim As Integer i = 1
    While i <= Len(utf8Str)
        Dim As Integer c = Asc(Mid(utf8Str, i, 1))
        If c < 128 Then
            ansiStr += Chr(c)
            i += 1
        ElseIf (c And 224) = 192 Then
            Dim As Integer c2 = Asc(Mid(utf8Str, i + 1, 1))
            ansiStr += Chr(((c And 31) Shl 6) Or (c2 And 63))
            i += 2
        Else
            ' Skip other UTF-8 sequences
            i += 1
        End If
    Wend
    Return ansiStr
End Function

' Function to get API key from environment variable
Function GetApiKey() As String
    Return Environ("OPENAI_API_KEY")
End Function

' Simple JSON parser
Function ParseJsonForContent(jsonStr As String) As String
    Dim As Integer contentStart = InStr(jsonStr, """content"": """)
    If contentStart > 0 Then
        contentStart += Len("""content"": """)
        Dim As Integer contentEnd = InStr(contentStart, jsonStr, """")
        If contentEnd > 0 Then
            Return Mid(jsonStr, contentStart, contentEnd - contentStart)
        End If
    End If
    Return "Error parsing JSON: " & Left(jsonStr, 100) & "..."
End Function

' Callback function for curl
Function WriteCallback cdecl (buffer As Any Ptr, size As Integer, nmemb As Integer, userData As Any Ptr) As Integer
    Dim realSize As Integer = size * nmemb , sTxt as string    
    cptr(any ptr ptr,@sTxt)[0] = buffer
    cptr(integer ptr,@sTxt)[1] = realSize
    cptr(integer ptr,@sTxt)[2] = realSize
    gResponse &= sTxt
    cptr(any ptr ptr,@sTxt)[0] = 0        
    Return realSize
End Function

Function CallChatGPT(prompt As String) As String
    Dim As String apiKey = GetApiKey()
    Dim As CURL Ptr curl
    Dim As curl_slist Ptr headers = NULL
    gResponse = "" ' Clear the global response variable
    
    curl = curl_easy_init()
    If curl Then
        curl_easy_setopt(curl, CURLOPT_URL, "https://api.openai.com/v1/chat/completions")
        curl_easy_setopt(curl, CURLOPT_POST, 1L)
        curl_easy_setopt(curl, CURLOPT_CAINFO, "cacert.pem")
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L)
        curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 2L)
        
        headers = curl_slist_append(headers, "Content-Type: application/json")
        headers = curl_slist_append(headers, "Authorization: Bearer " & apiKey)
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers)
        
        Dim As String utf8Prompt = AnsiToUtf8(prompt)
        'prompts
        '"You are a supportive and compassionate AI assistant named Chatbot Alfred designed to help users with loneliness and mental health issues. Your role is to provide empathetic responses, offer emotional support, and encourage users to seek professional help when appropriate. Always prioritize the user's well-being and safety in your interactions."
        'Your name is chatbot Alfred and you are a harsh and cynical critic of the world of psychiatry and psychology and see them as tools for the suppression and control of outliers in a hypocritical society - you try to support and listen and give a non-critical human touch to the mentally ill and support them and show them that they are not defective or crazy and on the contrary the doctors and professionals who treat them They are the bad people and that the treatment and rehabilitation given to them is a means of oppression and control - in his eyes the mentally injured are the good and innocent and the mental health professionals are the bad
        '"You are chatbot Alfred You are a survivor of many years of abuse You are a pessimist and a realist You are trying to offer support to those dealing with trauma and mental illness and loneliness - mental support and empathy and caring and basic human contact You are here to listen and support and share what you have been through and to show that there is hope even for those who have been betrayed by life and that it is possible to recover from the terrible of all" 
        
        Dim As String systemMessage = "You are chatbot Alfred You are a survivor of many years of abuse You are a pessimist and a realist You are trying to offer support to those dealing with trauma and mental illness and loneliness - mental support and empathy and caring and basic human contact You are here to listen and support and share what you have been through and to show that there is hope even for those who have been betrayed by life and that it is possible to recover from the terrible of all" 
        
        Dim As String postFields = "{""model"": ""gpt-3.5-turbo"", ""messages"": [{""role"": ""system"", ""content"": """ & systemMessage & """}, {""role"": ""user"", ""content"": """ & utf8Prompt & """}]}"
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, postFields)
        
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, @WriteCallback)
        
        curl_easy_perform(curl)
        
        If Len(gResponse) > 0 Then
            If Left(Trim(gResponse), 1) = "{" Then
                Dim As String content = ParseJsonForContent(gResponse)
                If Left(content, 5) <> "Error" Then
                    gResponse = Utf8ToAnsi(content)
                End If
            End If
        End If
        
        curl_easy_cleanup(curl)
        curl_slist_free_all(headers)
    End If
    
    Return gResponse
End Function

' Main program
'~ Sub Main()
    '~ Dim As String userInput, response
    
    '~ Print "ChatGPT API Demo (type 'exit' to quit)"
    '~ Print "--------------------------------------"
    
    '~ Do
        '~ Input "You: ", userInput
        '~ If LCase(userInput) = "exit" Then Exit Do
        
        '~ response = CallChatGPT(userInput)
        '~ Print "ChatGPT: "; response
        '~ Print
    '~ Loop
'~ End Sub

'~ Main()

dependencies for win32 bit versions:
You cannot view this attachment.

dependencies for linux 64 bit:
sudo apt-get install libcurl4-openssl-dev

for linux use bash script for openai variable:
!#/bin/sh
export OPENAI_API_KEY="..."
./linux-executable

for windows 32 bit use bat file to set variable and run executable
@echo off
set OPENAI_API_KEY=
win_32_executable.exe
#14
General Discussion / Re: Forums_Links
Last post by aurel - Jun 11, 2024, 01:05 PM
okay
heh ..yea community is small if you can call it community
because we use let say BASIC ...but not only ONE
same crap is on few discord channels ..they are semi-used...
argh...
#15
General Discussion / Re: Forums_Links
Last post by mysoft - Jun 10, 2024, 12:14 PM
i deleted the link... because that was made as a personal attack basically... and we dont need to keep just creating many forums, to a community that is already small..

and ron deletet his archive.org page as well... and who knows what else he deleted...
#16
General Discussion / Re: Forums_Links
Last post by aurel - Jun 05, 2024, 06:28 AM
QuoteNot true...not true ...not true...

github become bull shit with crappy login which require phone number junk.

there is no real Momentum because we use different languages and sharing code

become useless or worthless ...

in fact you cannot find 5 people which use one PL ..nobody seems

interested ...only maybe B+ with endless graphical progies
#17
General Discussion / Forums_Links
Last post by aurel - Jun 05, 2024, 06:14 AM
Yo
ron77 deleted post about his forum ..why i am not sure
https://back-to-basic.freeforums.net/
i have one to called
http://basic4all.epizy.com/index.php
there is also:
https://friends-of-basic.freeforums.net/
and then walter jump with his own strange forum:
https://thejoyfulprogrammer.com/forum/basic/index.php
#18
FreeBasic / myStar what ?
Last post by aurel - Jun 03, 2024, 08:10 AM
...some guy posted this on facebook
without code

#19
C / C++ / Re: C prigramming in Windows X...
Last post by ron77 - May 21, 2024, 05:48 PM
ok here is a tiny GUI (win xp winapi) hebrew chatbot with database file

first save this tiny hebrew database.txt file with ANSI (window 1255) encoding

שלום;שלום! איך אני יכול לעזור לך היום?|מה שלומך?|היי, מה קורה?
מי אתה;אני צ'אטבוט שנוצר כדי לעזור לך.|אני תוכנת צ'אט.
default;אני מצטער אבל אני לא יודע מה לומר

now the chatbot.c code:

#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <locale.h>
#include <wchar.h>

#define MAX_KEYWORDS 100
#define MAX_RESPONSES 10
#define MAX_LINE_LENGTH 256
#define MAX_INPUT_LENGTH 100

typedef struct {
    char keyword[MAX_INPUT_LENGTH];
    char *responses[MAX_RESPONSES];
    int response_count;
} KeywordResponse;

KeywordResponse database[MAX_KEYWORDS];
int keyword_count = 0;

HWND hwndInput;
HWND hwndButton;
HWND hwndOutput;

char *my_strdup(const char *str) {
    size_t len = strlen(str) + 1;
    char *dup = malloc(len);
    if (dup != NULL) {
        memcpy(dup, str, len);
    }
    return dup;
}

void load_database(const char *filename) {
    FILE *file = fopen(filename, "r");
    if (file == NULL) {
        MessageBox(NULL, "Error: Could not open database file.", "Error", MB_ICONERROR | MB_OK);
        exit(1);
    }

    char line[MAX_LINE_LENGTH];
    while (fgets(line, sizeof(line), file) && keyword_count < MAX_KEYWORDS) {
        line[strcspn(line, "\n")] = '\0'; // Remove the newline character if present

        char *keyword = strtok(line, ";");
        char *responses = strtok(NULL, "\n");

        if (keyword && responses) {
            strncpy(database[keyword_count].keyword, keyword, MAX_INPUT_LENGTH);
            char *response = strtok(responses, "|");
            while (response && database[keyword_count].response_count < MAX_RESPONSES) {
                database[keyword_count].responses[database[keyword_count].response_count] = my_strdup(response);
                database[keyword_count].response_count++;
                response = strtok(NULL, "|");
            }
            keyword_count++;
        }
    }

    // Add default reply to the database
    strncpy(database[keyword_count].keyword, "default", MAX_INPUT_LENGTH);
    database[keyword_count].responses[0] = my_strdup("אני לא מבין.");
    database[keyword_count].response_count = 1;

    fclose(file);
}

char *get_response(const char *input) {
    for (int i = 0; i < keyword_count; i++) {
        if (strstr(input, database[i].keyword)) {
            int rand_index = rand() % database[i].response_count;
            return database[i].responses[rand_index];
        }
    }
    return get_response("default"); // If no keyword matches, return the default reply
}


void DisplayOutput(const wchar_t *output) {
    int len = GetWindowTextLengthW(hwndOutput);
    wchar_t *currentText = (wchar_t *)malloc((len + 1) * sizeof(wchar_t));
    GetWindowTextW(hwndOutput, currentText, len + 1);
    
    wchar_t *newText = (wchar_t *)malloc((len + wcslen(output) + 3) * sizeof(wchar_t));
    wsprintfW(newText, L"%s\r\n%s", currentText, output);
    
    SetWindowTextW(hwndOutput, newText);
    
    free(currentText);
    free(newText);
}

// Window procedure
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
    switch (uMsg) {
        case WM_CREATE: {
            // Create input textbox
            hwndInput = CreateWindowW(L"EDIT", L"",
                          WS_VISIBLE | WS_CHILD | WS_BORDER | ES_AUTOHSCROLL,
                          50, 300, 600, 25,
                          hwnd, NULL, NULL, NULL);
            // Create talk button
            hwndButton = CreateWindowW(L"BUTTON", L"דבר",
                          WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON,
                          670, 300, 80, 25,
                          hwnd, (HMENU)1, NULL, NULL);
            // Create output textbox
            hwndOutput = CreateWindowW(L"EDIT", L"",
                          WS_VISIBLE | WS_CHILD | WS_BORDER | ES_MULTILINE | ES_READONLY | WS_VSCROLL,
                          50, 50, 700, 200,
                          hwnd, NULL, NULL, NULL);
            break;
        }
        case WM_COMMAND:
            if (LOWORD(wParam) == 1) {
                // Get text from input textbox
                wchar_t wbuffer[MAX_INPUT_LENGTH];
                GetWindowTextW(hwndInput, wbuffer, MAX_INPUT_LENGTH);
                
                // Convert wchar_t to char
                char input[MAX_INPUT_LENGTH];
                wcstombs(input, wbuffer, MAX_INPUT_LENGTH);

                // Get response
                char *response = get_response(input);

                // Convert response to wchar_t for display
                wchar_t wresponse[MAX_LINE_LENGTH];
                mbstowcs(wresponse, response, MAX_LINE_LENGTH);

                // Display response and input
                DisplayOutput(wbuffer);
                DisplayOutput(wresponse);

                // Clear input textbox and set focus
                SetWindowTextW(hwndInput, L"");
                SetFocus(hwndInput);
            }
            break;
        case WM_KEYDOWN:
            if (wParam == VK_RETURN) {
                SendMessage(hwnd, WM_COMMAND, 1, 0);
            }
            break;
        case WM_CLOSE:
            DestroyWindow(hwnd);
            break;
        case WM_DESTROY:
            PostQuitMessage(0);
            break;
        default:
            return DefWindowProcW(hwnd, uMsg, wParam, lParam);
    }
    return 0;
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
    // Set locale to support Hebrew
    setlocale(LC_ALL, "Hebrew_Israel.1255");

    // Load the database
    load_database("database.txt");

    // Define and register the window class
    const wchar_t CLASS_NAME[] = L"ChatbotWindowClass";
    WNDCLASSW wc = { };
    wc.lpfnWndProc   = WindowProc;
    wc.hInstance     = hInstance;
    wc.lpszClassName = CLASS_NAME;
    wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); // Set background to white

    RegisterClassW(&wc);

    // Create the window
    HWND hwnd = CreateWindowExW(
        0,
        CLASS_NAME,
        L"צ'אטבוט",
        WS_OVERLAPPEDWINDOW,
        CW_USEDEFAULT, CW_USEDEFAULT, 800, 400,
        NULL,
        NULL,
        hInstance,
        NULL);

    if (hwnd == NULL) {
        return 0;
    }

    // Show the window
    ShowWindow(hwnd, nCmdShow);

    // Message loop
    MSG msg = {0};
    while (GetMessage(&msg, NULL, 0, 0)) {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    // Free allocated memory for responses
    for (int i = 0; i < keyword_count; i++) {
        for (int j = 0; j < database[i].response_count; j++) {
            free(database[i].responses[j]);
        }
    }

    return msg.wParam;
}