Sample code for 30+ languages & platforms
Zig

OpenAI (ChatGPT) Simple Request

See more OpenAI ChatGPT Examples

Demonstrate a simple ChatGPT request with authentication using your OPENAI_API_KEY.

Chilkat Zig Downloads

Zig
const std = @import("std");
const chilkat = @import("chilkat");

pub fn main(init: std.process.Init) !void {
    const alloc = init.arena.allocator();

    // This example assumes the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    const http = try chilkat.Http.init();
    defer http.deinit();

    // Implements the following CURL command:

    // curl https://api.openai.com/v1/chat/completions \
    //   -H "Content-Type: application/json" \
    //   -H "Authorization: Bearer $OPENAI_API_KEY" \
    //   -d '{
    //      "model": "gpt-3.5-turbo",
    //      "messages": [{"role": "user", "content": "Say this is a test!"}],
    //      "temperature": 0.7
    //    }'

    // Use the following online tool to generate HTTP code from a CURL command
    // Convert a cURL Command to HTTP Source Code

    // Use this online tool to generate code from sample JSON:
    // Generate Code to Create JSON

    // The following JSON is sent in the request body.

    // {
    //   "model": "gpt-3.5-turbo",
    //   "messages": [
    //     {
    //       "role": "user",
    //       "content": "Say this is a test!"
    //     }
    //   ],
    //   "temperature": 0.7
    // }

    const json = try chilkat.JsonObject.init();
    defer json.deinit();
    json.updateString("model", "gpt-3.5-turbo") catch {};
    json.updateString("messages[0].role", "user") catch {};
    json.updateString("messages[0].content", "Say this is a test!") catch {};
    json.updateNumber("temperature", "0.7") catch {};

    // Adds the "Authorization: Bearer $OPENAI_API_KEY" header.
    // This is NOT a real key.  Change the "sk-vi...." to your own key.
    http.setAuthToken("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");

    const resp = try chilkat.HttpResponse.init();
    defer resp.deinit();
    http.httpJson("POST", "https://api.openai.com/v1/chat/completions", json, "application/json", resp) catch {
        std.debug.print("{s}\n", .{try http.getLastErrorText(alloc)});
        return;
    };

    const sb_response_body = try chilkat.StringBuilder.init();
    defer sb_response_body.deinit();
    resp.getBodySb(sb_response_body) catch {};

    const j_resp = try chilkat.JsonObject.init();
    defer j_resp.deinit();
    j_resp.loadSb(sb_response_body) catch {};
    j_resp.setEmitCompact(false);

    std.debug.print("Response Body:\n", .{});
    std.debug.print("{s}\n", .{try j_resp.emit(alloc)});

    const resp_status_code = resp.getStatusCode();
    std.debug.print("Response Status Code = {d}\n", .{resp_status_code});
    if (resp_status_code >= 400) {
        std.debug.print("Response Header:\n", .{});
        std.debug.print("{s}\n", .{try resp.getHeader(alloc)});
        std.debug.print("Failed.\n", .{});
        return;
    }

    // Sample JSON response:
    // (Sample code for parsing the JSON response is shown below)

    // {
    //   "id": "chatcmpl-abc123",
    //   "object": "chat.completion",
    //   "created": 1677858242,
    //   "model": "gpt-3.5-turbo-0301",
    //   "usage": {
    //     "prompt_tokens": 13,
    //     "completion_tokens": 7,
    //     "total_tokens": 20
    //   },
    //   "choices": [
    //     {
    //       "message": {
    //         "role": "assistant",
    //         "content": "\n\nThis is a test!"
    //       },
    //       "finish_reason": "stop",
    //       "index": 0
    //     }
    //   ]
    // }

    // Sample code for parsing the JSON response...
    // Use the following online tool to generate parsing code from sample JSON:
    // Generate Parsing Code from JSON

    var role: [:0]const u8 = "";
    var content: [:0]const u8 = "";
    var finish_reason: [:0]const u8 = "";
    var index: i32 = 0;

    _ = try j_resp.stringOf(alloc, "id");
    _ = try j_resp.stringOf(alloc, "object");
    _ = j_resp.intOf("created");
    _ = try j_resp.stringOf(alloc, "model");
    _ = j_resp.intOf("usage.prompt_tokens");
    _ = j_resp.intOf("usage.completion_tokens");
    _ = j_resp.intOf("usage.total_tokens");
    var i: i32 = 0;
    const count_i = j_resp.sizeOfArray("choices");
    while (i < count_i) {
        j_resp.setI(i);
        role = try j_resp.stringOf(alloc, "choices[i].message.role");
        content = try j_resp.stringOf(alloc, "choices[i].message.content");
        finish_reason = try j_resp.stringOf(alloc, "choices[i].finish_reason");
        index = j_resp.intOf("choices[i].index");
        i = i + 1;
    }
}