uncloseai.com/public/languages/c/curl/index.html

412 lines
14 KiB
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>C Language - uncloseai.com API Examples</title>
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
line-height: 1.6;
max-width: 900px;
margin: 0 auto;
padding: 20px;
color: #333;
}
h1, h2, h3 { color: #2c3e50; }
code {
background: #f4f4f4;
padding: 2px 6px;
border-radius: 3px;
font-family: "Courier New", monospace;
}
pre {
background: #f4f4f4;
padding: 15px;
border-radius: 5px;
overflow-x: auto;
border-left: 4px solid #3498db;
}
pre code {
background: none;
padding: 0;
}
.section {
margin: 30px 0;
}
.note {
background: #fff3cd;
border-left: 4px solid #ffc107;
padding: 12px;
margin: 15px 0;
}
.success {
background: #d4edda;
border-left: 4px solid #28a745;
padding: 12px;
margin: 15px 0;
}
.info {
background: #d1ecf1;
border-left: 4px solid #17a2b8;
padding: 12px;
margin: 15px 0;
}
.endpoint {
background: #e7f3ff;
padding: 10px;
margin: 10px 0;
border-radius: 4px;
}
</style>
</head>
<body>
<h1>C Language Examples - uncloseai.com API</h1>
<div class="section">
<h2>Overview</h2>
<p>This example demonstrates how to interact with uncloseai.com API endpoints using C and libcurl. It covers three core functionalities:</p>
<ul>
<li><strong>Hermes AI</strong> - General purpose conversational AI</li>
<li><strong>Qwen 3 Coder</strong> - Specialized coding model</li>
<li><strong>Text-to-Speech</strong> - Audio generation from text</li>
</ul>
<div class="info">
<strong>Why C?</strong> C provides direct control over memory and network operations, making it ideal for understanding low-level HTTP communication and building high-performance API clients.
</div>
</div>
<div class="section">
<h2>Prerequisites</h2>
<p>The implementation uses <code>libcurl</code> for HTTP requests. In Alpine Linux:</p>
<pre><code>apk add gcc musl-dev curl-dev make</code></pre>
<div class="note">
<strong>Docker Image:</strong> alpine:3.21 (checked 2025-10-12)<br>
<strong>libcurl:</strong> System package via apk (8.14.1-r2 in Alpine 3.21)
</div>
</div>
<div class="section">
<h2>Code Examples</h2>
<h3>Example 1: Hermes AI Chat</h3>
<div class="endpoint">
<strong>Endpoint:</strong> https://hermes.ai.unturf.com/v1/chat/completions<br>
<strong>Model:</strong> adamo1139/Hermes-3-Llama-3.1-8B-FP8-Dynamic
</div>
<pre><code>// Construct JSON request payload
const char *hermes_json = "{"
"\"model\":\"adamo1139/Hermes-3-Llama-3.1-8B-FP8-Dynamic\","
"\"messages\":[{\"role\":\"user\",\"content\":\"Give a C function to check if a number is prime\"}],"
"\"temperature\":0.5,"
"\"max_tokens\":150"
"}";
// Make POST request with libcurl
struct MemoryStruct chunk = {NULL, 0};
chunk.memory = malloc(1);
chunk.size = 0;
if(post_request("https://hermes.ai.unturf.com/v1/chat/completions",
hermes_json, &chunk) == 0) {
printf("Response received (%zu bytes)\n", chunk.size);
}
free(chunk.memory);</code></pre>
<h3>Example 2: Qwen 3 Coder</h3>
<div class="endpoint">
<strong>Endpoint:</strong> https://qwen.ai.unturf.com/v1/chat/completions<br>
<strong>Model:</strong> hf.co/unsloth/Qwen3-Coder-30B-A3B-Instruct-GGUF:Q4_K_M
</div>
<pre><code>const char *qwen_json = "{"
"\"model\":\"hf.co/unsloth/Qwen3-Coder-30B-A3B-Instruct-GGUF:Q4_K_M\","
"\"messages\":[{\"role\":\"user\",\"content\":\"Write a C function to reverse a string in place\"}],"
"\"temperature\":0.5,"
"\"max_tokens\":200"
"}";
struct MemoryStruct chunk = {NULL, 0};
chunk.memory = malloc(1);
chunk.size = 0;
if(post_request("https://qwen.ai.unturf.com/v1/chat/completions",
qwen_json, &chunk) == 0) {
printf("Response received (%zu bytes)\n", chunk.size);
}
free(chunk.memory);</code></pre>
<h3>Example 3: Text-to-Speech</h3>
<div class="endpoint">
<strong>Endpoint:</strong> https://speech.ai.unturf.com/v1/audio/speech<br>
<strong>Model:</strong> tts-1
</div>
<pre><code>const char *tts_json = "{"
"\"model\":\"tts-1\","
"\"voice\":\"alloy\","
"\"input\":\"Hello from C with libcurl!\""
"}";
CURL *curl = curl_easy_init();
if(curl) {
struct curl_slist *headers = NULL;
headers = curl_slist_append(headers, "Content-Type: application/json");
headers = curl_slist_append(headers, "Authorization: Bearer YOLO");
struct MemoryStruct chunk = {NULL, 0};
chunk.memory = malloc(1);
chunk.size = 0;
curl_easy_setopt(curl, CURLOPT_URL, "https://speech.ai.unturf.com/v1/audio/speech");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, tts_json);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);
CURLcode res = curl_easy_perform(curl);
if(res == CURLE_OK) {
FILE *fp = fopen("speech.mp3", "wb");
if(fp) {
fwrite(chunk.memory, 1, chunk.size, fp);
fclose(fp);
printf("Speech file created: speech.mp3\n");
}
}
curl_slist_free_all(headers);
curl_easy_cleanup(curl);
free(chunk.memory);
}</code></pre>
</div>
<div class="section">
<h2>Code Walkthrough</h2>
<h3>Memory Management for HTTP Responses</h3>
<pre><code>struct MemoryStruct {
char *memory;
size_t size;
};
static size_t WriteMemoryCallback(void *contents, size_t size,
size_t nmemb, void *userp) {
size_t realsize = size * nmemb;
struct MemoryStruct *mem = (struct MemoryStruct *)userp;
char *ptr = realloc(mem->memory, mem->size + realsize + 1);
if(!ptr) {
printf("Not enough memory\n");
return 0;
}
mem->memory = ptr;
memcpy(&(mem->memory[mem->size]), contents, realsize);
mem->size += realsize;
mem->memory[mem->size] = 0;
return realsize;
}</code></pre>
<p><strong>Key points:</strong></p>
<ul>
<li><code>WriteMemoryCallback</code> is called by libcurl as data arrives</li>
<li>Uses <code>realloc</code> to grow the buffer dynamically</li>
<li>Returns the number of bytes processed (libcurl requirement)</li>
<li>Null-terminates the buffer for string operations</li>
</ul>
<h3>Reusable POST Request Function</h3>
<pre><code>int post_request(const char *url, const char *json_data,
struct MemoryStruct *chunk) {
CURL *curl;
CURLcode res;
struct curl_slist *headers = NULL;
curl = curl_easy_init();
if(!curl) return -1;
// Set Content-Type and Authorization headers
headers = curl_slist_append(headers, "Content-Type: application/json");
headers = curl_slist_append(headers, "Authorization: Bearer dummy-key");
// Configure curl options
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, json_data);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)chunk);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 30L);
res = curl_easy_perform(curl);
curl_slist_free_all(headers);
curl_easy_cleanup(curl);
return (res == CURLE_OK) ? 0 : -1;
}</code></pre>
<p><strong>Key points:</strong></p>
<ul>
<li><code>CURLOPT_URL</code> - Target endpoint</li>
<li><code>CURLOPT_HTTPHEADER</code> - Custom headers (Content-Type, Authorization)</li>
<li><code>CURLOPT_POSTFIELDS</code> - JSON request body</li>
<li><code>CURLOPT_WRITEFUNCTION</code> - Callback for response data</li>
<li><code>CURLOPT_TIMEOUT</code> - 30-second timeout</li>
<li>Always cleanup headers and curl handle to prevent memory leaks</li>
</ul>
<h3>Global libcurl Initialization</h3>
<pre><code>int main(void) {
// Initialize libcurl globally (once per process)
curl_global_init(CURL_GLOBAL_ALL);
// ... make API calls ...
// Cleanup libcurl globally before exit
curl_global_cleanup();
return 0;
}</code></pre>
<p><strong>Key points:</strong></p>
<ul>
<li><code>curl_global_init()</code> must be called before any curl operations</li>
<li><code>curl_global_cleanup()</code> should be called before program exit</li>
<li>Thread-safe after initialization (can use multiple easy handles)</li>
</ul>
</div>
<div class="section">
<h2>Running the Examples</h2>
<h3>Build with Docker</h3>
<pre><code>docker build -t ai-unturf-c languages/c/
docker run --rm ai-unturf-c</code></pre>
<h3>Build Locally</h3>
<pre><code># Install dependencies (Alpine Linux)
apk add gcc musl-dev curl-dev make
# Compile
make
# Run
./examples</code></pre>
<div class="success">
<strong>Expected Output:</strong><br>
- Hermes AI: ~1158 bytes JSON response<br>
- Qwen Coder: ~1180 bytes JSON response<br>
- TTS: speech.mp3 file (~30KB MP3 audio)
</div>
</div>
<div class="section">
<h2>Common Issues</h2>
<h3>Missing libcurl</h3>
<pre><code># Alpine Linux
apk add curl-dev
# Debian/Ubuntu
apt-get install libcurl4-openssl-dev
# macOS
brew install curl</code></pre>
<h3>SSL/TLS Certificate Errors</h3>
<div class="note">
If you see SSL verification errors, ensure <code>ca-certificates</code> is installed:
<pre><code>apk add ca-certificates</code></pre>
</div>
<h3>Compilation Errors</h3>
<p>Ensure you're linking against libcurl:</p>
<pre><code>gcc -o examples examples.c -lcurl</code></pre>
<p>The <code>-lcurl</code> flag must come <em>after</em> the source file.</p>
<h3>Memory Leaks</h3>
<p>Always free allocated memory:</p>
<ul>
<li>Free <code>chunk.memory</code> after each request</li>
<li>Call <code>curl_slist_free_all()</code> on header lists</li>
<li>Call <code>curl_easy_cleanup()</code> on curl handles</li>
<li>Call <code>curl_global_cleanup()</code> before program exit</li>
</ul>
</div>
<div class="section">
<h2>JSON Parsing (Advanced)</h2>
<p>This example demonstrates raw HTTP communication. For production use, add JSON parsing:</p>
<div class="info">
<strong>Recommended JSON libraries for C:</strong>
<ul>
<li><strong>cJSON</strong> - Lightweight, easy to use</li>
<li><strong>json-c</strong> - Mature, full-featured</li>
<li><strong>jansson</strong> - Clean API, good documentation</li>
</ul>
</div>
<p>Example with cJSON:</p>
<pre><code>#include &lt;cjson/cJSON.h&gt;
// After receiving response in chunk.memory:
cJSON *json = cJSON_Parse(chunk.memory);
if(json) {
cJSON *choices = cJSON_GetObjectItem(json, "choices");
cJSON *first_choice = cJSON_GetArrayItem(choices, 0);
cJSON *message = cJSON_GetObjectItem(first_choice, "message");
cJSON *content = cJSON_GetObjectItem(message, "content");
printf("AI Response: %s\n", content->valuestring);
cJSON_Delete(json);
}</code></pre>
</div>
<div class="section">
<h2>Implementation Notes</h2>
<h3>Why This Approach?</h3>
<ul>
<li><strong>Direct control</strong> - No abstraction layers, full visibility into HTTP operations</li>
<li><strong>Performance</strong> - libcurl is highly optimized and widely used</li>
<li><strong>Portability</strong> - Works on any platform with libcurl (Linux, macOS, Windows, embedded)</li>
<li><strong>Educational</strong> - Demonstrates low-level API interaction patterns</li>
</ul>
<h3>Production Considerations</h3>
<ul>
<li>Add JSON parsing library for structured response handling</li>
<li>Implement retry logic with exponential backoff</li>
<li>Add comprehensive error handling and logging</li>
<li>Consider connection pooling for multiple requests</li>
<li>Use <code>CURLOPT_SSL_VERIFYPEER</code> for production HTTPS</li>
<li>Implement proper timeout handling</li>
</ul>
<h3>Docker Image Choice</h3>
<div class="note">
<strong>Base Image:</strong> alpine:3.21<br>
We use Alpine Linux for minimal size and security. The apk package manager provides all necessary build tools and libcurl development files.
</div>
</div>
<div class="section">
<h2>Related Examples</h2>
<ul>
<li><a href="../cpp/">C++</a> - Object-oriented approach with libcurl</li>
<li><a href="../go/">Go</a> - Native HTTP client, concurrent requests</li>
<li><a href="../rust/">Rust</a> - Memory-safe systems programming</li>
<li><a href="../python/">Python</a> - High-level API interaction</li>
</ul>
</div>
<footer style="margin-top: 50px; padding-top: 20px; border-top: 1px solid #ddd; color: #666; text-align: center;">
<p>Part of the <a href="https://ai.unturf.com">uncloseai.com</a> language examples collection</p>
<p>Built by Hermes Staff for the carnival hackers</p>
</footer>
</body>
</html>