TOpenAI / TChatGPT

Fuente: source/classes/topenai.prg (TOpenAI), source/classes/chatgpt.prg (TChatGPT)

FiveWin provides two classes for integrating with the OpenAI API: TOpenAI (full-featured with vision, streaming, and image support) and TChatGPT (simpler wrapper for basic chat completions). Both use Harbour's hb_curl library for HTTPS communication.

Architecture

flowchart LR subgraph "FiveWin Application" A[TOpenAI] B[TChatGPT] end subgraph "libcurl" C[hb_curl
HTTPS] end subgraph "OpenAI API" D["/v1/chat/completions"] E[Vision API] end A --> C B --> C C --> D C --> E

TOpenAI Class

DATA Members

DATATypeDefaultDescription
cKeyCharacter""OpenAI API key
cModelCharacter"gpt-4o-mini"Model to use
cPromptCharacterLast prompt sent
cResponseCharacterRaw JSON response from API
cUrlCharacterAPI endpoint URL
hCurlHandlelibcurl easy handle
nErrorNumeric0curl error code (0 = success)
nHttpCodeNumeric0HTTP response status code
nTemperatureNumeric0.5Sampling temperature (0.0 - 2.0)

Methods

MethodDescription
New( cKey, cModel )Create instance. If cKey is empty, reads OPENAI_API_KEY env var.
Send( cPrompt )Send a text prompt, return raw JSON response
SendStream( cPrompt, bCallback )Send prompt with streaming; bCallback receives chunks
SendImage( cImageFileName, cPrompt )Send a local image file with a prompt (Vision API)
SendImageURL( cImageUrl, cPrompt )Send an image URL with a prompt (Vision API)
GetValue()Extract the text response from cResponse JSON
End()Clean up curl handle

TChatGPT Class

TChatGPT is a simpler alternative with fewer features, suitable for basic prompt/response interactions.

DATA Members

DATATypeDefaultDescription
cKeyCharacter""OpenAI API key
cModelCharacter"gpt-4o-mini"Model name
cUrlCharacter"https://api.openai.com/v1/chat/completions"API endpoint
cPromptCharacterPrompt text to send
cResponseCharacterRaw JSON response
hCurlHandlelibcurl handle
nErrorNumeric0curl error code
nHttpCodeNumericHTTP status code

Methods

MethodDescription
New( cKey )Create instance with API key
Send()Send cPrompt, store response in cResponse
GetValue( cKey1, cKey2, ... )Navigate JSON response by key path. Variable args.
Reset()Reset curl state for next request
End()Clean up curl handle

Example: Basic Prompt/Response (TOpenAI)

#include "FiveWin.ch"

function Main()

   local oAI, cAnswer

   // API key from environment variable OPENAI_API_KEY
   oAI := TOpenAI():New()

   // Or with explicit key and model:
   // oAI := TOpenAI():New( "sk-...", "gpt-4o" )

   oAI:Send( "What is the capital of France? Answer in one word." )

   if oAI:nError == 0 .and. oAI:nHttpCode == 200
      cAnswer := oAI:GetValue()
      MsgInfo( cAnswer )   // "Paris"
   else
      MsgStop( "Error: " + oAI:cResponse )
   endif

   oAI:End()

return nil

Example: Streaming Response

#include "FiveWin.ch"

function Main()

   local oAI, cBuffer := ""

   oAI := TOpenAI():New()
   oAI:cModel := "gpt-4o"

   // Stream callback receives chunks of data as they arrive
   oAI:SendStream( "Write a short poem about coding.", ;
      { |cChunk| cBuffer += cChunk, QOut( cChunk ) } )

   if oAI:nError == 0
      MsgInfo( "Complete response:" + CRLF + cBuffer )
   endif

   oAI:End()

return nil

Example: Vision (Analyze an Image)

#include "FiveWin.ch"

function Main()

   local oAI

   oAI := TOpenAI():New( , "gpt-4o" )

   // Send a local image file
   oAI:SendImage( "C:\photos\chart.png", "Describe what you see in this image." )

   if oAI:nError == 0
      MsgInfo( oAI:GetValue() )
   endif

   // Send an image by URL
   oAI:SendImageURL( ;
      "https://example.com/photo.jpg", ;
      "What objects are in this photo?" )

   if oAI:nError == 0
      MsgInfo( oAI:GetValue() )
   endif

   oAI:End()

return nil

Example: TChatGPT (Simple Wrapper)

#include "FiveWin.ch"

function Main()

   local oChat

   oChat := TChatGPT():New( "sk-your-api-key-here" )

   // Set the prompt and send
   oChat:cPrompt := "Translate 'Hello, how are you?' to Spanish"
   oChat:Send()

   if oChat:nError == 0
      // Navigate the JSON response
      ? oChat:GetValue( "choices", "message", "content" )
      // Output: "Hola, como estas?"
   endif

   // Send another prompt (reset first)
   oChat:Reset()
   oChat:cPrompt := "Now translate it to French"
   oChat:Send()

   if oChat:nError == 0
      ? oChat:GetValue( "choices", "message", "content" )
   endif

   oChat:End()

return nil

Example: Adjusting Temperature

#include "FiveWin.ch"

function Main()

   local oAI

   oAI := TOpenAI():New()

   // Low temperature = more deterministic
   oAI:nTemperature := 0.1
   oAI:Send( "What is 2 + 2?" )
   ? "Precise:", oAI:GetValue()

   // High temperature = more creative
   oAI:nTemperature := 1.5
   oAI:Send( "Write a creative product name for a new coffee brand" )
   ? "Creative:", oAI:GetValue()

   oAI:End()

return nil

Supported Models

ModelDescription
gpt-4oMost capable model, supports text + vision
gpt-4o-miniFast, cost-effective (default in FWH)
gpt-4-turboGPT-4 Turbo with large context window
gpt-3.5-turboLegacy fast model

Tips

TOLlama (Local AI)

Fuente: source/classes/tollama.prg

Local AI Connects to a local Ollama server. No API key needed - runs AI models on your own machine.

DATADefaultDescription
cModelModel name (e.g. "llama3", "mistral", "codellama")
cUrl"http://localhost:11434"Ollama server URL
cPromptCurrent prompt
cResponseAPI response
aAgentsArray of agent definitions
MethodParametersDescription
New()cModelConstructor. Sets model name.
Send()cPromptSend prompt and wait for full response
SendStream()cPrompt, bCallbackSend with streaming - bCallback receives chunks in real-time
SendImage()cImageFile, cPromptSend image + prompt (for vision models like llava)
GetValue()Extract response text from JSON
End()Cleanup CURL handle
local oAI := TOLlama():New( "llama3" )

oAI:Send( "Explain what FiveWin is in one paragraph" )
MsgInfo( oAI:GetValue() )

// Streaming response
oAI:SendStream( "Write a Harbour function", ;
   {| cChunk | QOut( cChunk ) } )

oAI:End()

TDeepSeek

Fuente: source/classes/tdeepseek.prg

Cloud AI DeepSeek API client. Known for strong coding and reasoning capabilities.

DATADefaultDescription
cKey""API key from DeepSeek
cModel"deepseek-chat"Model: "deepseek-chat" or "deepseek-reasoner"
cUrlAPI endpoint
local oAI := TDeepSeek():New( "your-api-key" )
oAI:Send( "Write a Harbour function to calculate factorial" )
MsgInfo( oAI:GetValue() )
oAI:End()

TGemini (Google)

Fuente: source/classes/tgemini.prg

Cloud AI Google Gemini API client. Supports text, images, and file uploads.

DATADefaultDescription
cKey""Google API key
cModel"gemini-2.0-flash"Model name
cUrlgoogleapis.com/v1beta/modelsAPI endpoint
cUploadUrlgoogleapis.com/upload/v1beta/filesFile upload endpoint
nTemperature0Response creativity (0-2)
MethodParametersDescription
New()cKey, cModelConstructor
Send()uContent, cPrompt, bCallbackSend text, image or file with prompt
UploadFile()cFileName, lDeleteAfterUpload file to Gemini for analysis
GetTokens()cBufferCount tokens in text
GetValue()Extract response text
local oAI := TGemini():New( "your-google-api-key" )
oAI:Send( "Analyze this image", "photo.jpg" )
MsgInfo( oAI:GetValue() )
oAI:End()

TGrok (xAI)

Fuente: source/classes/tgrok.prg

Cloud AI xAI Grok API client. Supports text, images, and streaming.

DATADefaultDescription
cKey""xAI API key
cModel"grok-3-latest"Model name
nTemperature0.5Response creativity
MethodParametersDescription
Send()cPromptSend text prompt
SendStream()cPrompt, bCallbackStreaming response
SendImage()cImageFile, cPromptSend image file + prompt
SendImageURL()cImageUrl, cPromptSend image URL + prompt
local oAI := TGrok():New( "your-xai-key" )
oAI:Send( "What are the benefits of Harbour language?" )
MsgInfo( oAI:GetValue() )
oAI:End()

TKimi (Moonshot)

Fuente: source/classes/tkimi.prg

Cloud AI Moonshot Kimi API client. Strong multilingual capabilities.

DATADefaultDescription
cKey""Moonshot API key
cModel"moonshot-v1-8k"Model: moonshot-v1-8k, -32k, -128k
nTemperature0.5Response creativity
local oAI := TKimi():New( "your-moonshot-key" )
oAI:Send( "Translate this to Chinese: Hello World" )
MsgInfo( oAI:GetValue() )
oAI:End()

AI Classes Comparison

ClassProviderLocal/CloudVisionStreamingDefault Model
TOpenAIOpenAICloudYesYesgpt-4o-mini
TChatGPTOpenAICloudNoNogpt-4o-mini
TOLlamaLocal (Ollama)LocalYesYes(user choice)
TDeepSeekDeepSeekCloudNoNodeepseek-chat
TGeminiGoogleCloudYesYesgemini-2.0-flash
TGrokxAICloudYesYesgrok-3-latest
TKimiMoonshotCloudNoNomoonshot-v1-8k
graph TD A[Your FWH Application] --> B{Choose AI Provider} B -->|Local, Free| C[TOLlama
llama3, mistral, codellama] B -->|OpenAI| D[TOpenAI / TChatGPT
gpt-4o, gpt-4o-mini] B -->|Google| E[TGemini
gemini-2.0-flash] B -->|xAI| F[TGrok
grok-3] B -->|DeepSeek| G[TDeepSeek
deepseek-chat] B -->|Moonshot| H[TKimi
moonshot-v1] style C fill:#238636,stroke:#3fb950,color:#fff style D fill:#1f6feb,stroke:#58a6ff,color:#fff style E fill:#d29922,stroke:#e3b341,color:#000 style F fill:#6e40c9,stroke:#bc8cff,color:#fff style G fill:#da3633,stroke:#f85149,color:#fff style H fill:#bf8700,stroke:#d29922,color:#fff

Transformer (Neural Network in Harbour)

Fuente: source/classes/transformer.prg

Advanced A full Transformer neural network implemented in pure Harbour. Supports training, forward/backward propagation, multi-head attention, and text prediction.

DATADescription
d_modelModel dimension (embedding size)
n_headsNumber of attention heads
num_layersNumber of transformer layers
vocab_sizeVocabulary size
max_seq_lenMaximum sequence length
aVocabVocabulary array (words)
Embedding, PositionalEmbedding and positional encoding matrices
MethodDescription
New()Constructor: num_layers, d_model, n_heads, vocab_size, max_seq_len, hEmbeddings, aVocab
Forward()Forward pass: src_indices, pos_indices → output
Backward()Backward pass: compute gradients for training
zero_grad()Reset all gradients to zero

Example: Next Word Prediction (transf1.prg)

local vocab := { "hola", "mundo", "adios", "gato", "perro" }
local oT := Transformer():New( 1, 6, 2, Len(vocab), 8,, vocab )

// Train on sequences
for e = 1 to 60
   for i = 1 to Len(train_src)
      output := oT:Forward( train_src[i], train_pos[i] )
      oT:Backward( output, train_tgt[i], train_src[i], train_pos[i] )
   next
next

// Predict next word
output := oT:Forward( { 1, 2 }, { 1, 2 } )  // "hola mundo" -> ?

Example: Sentiment Classification (transf2.prg)

// Classify phrases as Positive or Negative
local vocab := { "buen", "dia", "malo", "trabajo", "feliz", "triste", "excelente", "horrible" }
local oT := TransformerClassifier():New( 1, 6, 2, 2, vocab )

// Train: "buen dia" -> Positive, "malo trabajo" -> Negative
// After training, classify new phrases

TNeuralNetwork (Classic Neural Network)

Fuente: source/classes/tneuralnet.prg

Classic feedforward neural network with backpropagation. Good for simple pattern recognition.

// XOR training example
local oNN := TNeuralNetwork():New( 2, { 2 }, 1 )  // 2 inputs, 1 hidden layer with 2 neurons, 1 output

for n = 1 to 30000
   oNN:Learn( { 0, 0 }, { 0 }, .F. )
   oNN:Learn( { 1, 0 }, { 1 }, .F. )
   oNN:Learn( { 0, 1 }, { 1 }, .F. )
   oNN:Learn( { 1, 1 }, { 0 }, .F. )
next

? oNN:Predict( { 1, 0 } )  // -> ~1.0
? oNN:Predict( { 1, 1 } )  // -> ~0.0

TEmbeddings (Semantic Similarity)

Fuente: source/classes/tembeddings.prg

Text embeddings for semantic similarity comparison. Uses HuggingFace or OpenAI APIs.

local oE1 := TEmbeddings():New()
local oE2 := TEmbeddings():New()
local oE3 := TEmbeddings():New()

oE1:GetEmbeddings( "I feel very well" )
oE2:GetEmbeddings( "How are you?" )
oE3:GetEmbeddings( "I saw Peter" )

? oE1 - oE2   // High similarity (both about feelings)
? oE1 - oE3   // Low similarity (different topics)

AI Agents (TOLlama + TAgent)

AI agents combine LLMs with tools (Funciones) that the AI can call. The AI decides which tool to use based on the user's request.

local oLlama := TOLlama():New()
local oAgent

// Agent for date/time
oAgent := TAgent():New( "datetime", { ;
   { "get_time", {|hParams| GetCurrentTime(hParams) } }, ;
   { "get_date", {|hParams| GetDate(hParams) } } } )
AAdd( oLlama:aAgents, oAgent )

// Agent for filesystem
oAgent := TAgent():New( "filesystem", { ;
   { "create_folder", {|hParams| CreateFolder(hParams) } }, ;
   { "create_file",   {|hParams| CreateFile(hParams) } } } )
AAdd( oLlama:aAgents, oAgent )

// AI decides which tool to use
oLlama:Send( "What time is it?" )       // -> calls get_time
oLlama:Send( "Create a folder test" )   // -> calls create_folder

AI Samples Reference

All AI samples are in the samples/ai/ folder:

SampleDescriptionAI Class
ollama1.prg - ollama5.prgLocal AI: basic chat, streaming, image analysisTOLlama
openai1.prg, openai2.prgOpenAI: text and image promptsTOpenAI
chatgpt.prgInteractive ChatGPT dialog with voiceTChatGPT
deepseek1.prgDeepSeek: SQL code generationTDeepSeek
gemini1.prg - gemini6.prgGoogle Gemini: text, images, files, tokensTGemini
grok1.prgxAI Grok: basic promptTGrok
kimi1.prgMoonshot Kimi: multilingualTKimi
ai.prgInteractive AI dialog with voice synthesis (64-bit)TOpenAI
vision.prgVisual forms IDE with AIMultiple
agents.prgAI agents with tool callingTOLlama + TAgent
agentdb.prg, agentdb2.prgAI agents for database operationsTOLlama + TAgent
agentdoc.prg, agentdoc2.prgAI agents for document creationTOLlama + TAgent
agentweb.prgAI agent for web operationsTOLlama + TAgent
autogpt.prgAutonomous AI task executionTOpenAI
transf1.prg - transf5.prgTransformer: next word, sentiment, trainingTransformer
transformer.prgComplete transformer demoTransformer
neural.prgNeural network: XOR trainingTNeuralNetwork
neuralnet.prgNeural network visualizationTNet
nn.prg - nn4c.prgVarious neural network examplesTNeuralNetwork
perceptron.prgBasic perceptronCustom
embeddings1.prg, embeddings2.prgText similarity with embeddingsTEmbeddings
llm.prgLLM integration exampleTOLlama
llama3.prgLlama 3 specific featuresTOLlama
llava.prgLLaVA vision modelTOLlama
phi4.prgMicrosoft Phi-4 modelTOLlama

Ver También