openai-cpp

repository·main·Indexed 43 days ago

https://github.com/olrea/openai-cpp

A lightweight, header-only C++ library for the OpenAI API. Requires libcurl and a C++11 compatible compiler. Provides high-level interfaces for completions and image generation, as well as low-level HTTP methods for custom requests.

Tokens
1.2K
Snippets
4
Records
8
Agent score
6%

What's inside openai-cpp

  1. Handle errors and exceptions in OpenAI-CPP

    main

    By default, OpenAI-CPP throws a runtime error exception if a libcurl request fails.

    To prevent exceptions and instead receive a warning when a request fails, call setThrowException(false) on the instance. This is useful for applications that prefer manual error checking or want to avoid try-catch blocks.

  2. Manage multiple OpenAI instances and secret keys

    main

    Depending on your use case, you can manage the OpenAI session in two ways:

    1. Using the Global Singleton (Default)

    Use openai::start() to initialize the global instance and openai::instance() to retrieve it from different scopes. This is convenient if your application only uses one API key.

    2. Passing Instances by Reference (Multi-key support)

    If you need to manage multiple secret keys simultaneously, instantiate openai::OpenAI objects manually and pass them by reference to your functions. This avoids reliance on the global state.

    void bar(openai::OpenAI& openai) {
        openai.completion.create({
            {"model", "text-davinci-003"},
            {"prompt", "Say bar() function called"}
        });
    }
    
    int main() {
        openai::OpenAI openai_instance{"your_api_key"};
        bar(openai_instance);
    }
  3. Configure OpenAI-CPP requirements

    main

    Before using the library, ensure your environment meets the following requirements:

    • Compiler: A C++11, C++14, C++17, or C++20 compatible compiler.
    • Dependency: libcurl must be installed on your system. Ensure you have the development package (headers and libraries) available.
  4. Initialize OpenAI-CPP with an API Key

    main

    The library requires an OpenAI API key. You can provide it in two ways:

    1. Environment Variable: Set the OPENAI_API_KEY environment variable. This is the recommended approach.
      export OPENAI_API_KEY='sk-...'
    2. Directly in Code: Pass the key to the openai::start() function.
      openai::start("your_API_key", "optional_organization");

    Calling openai::start() without arguments will automatically attempt to use the OPENAI_API_KEY environment variable.

    #include "openai.hpp"
    
    int main() {
        openai::start(); // Uses OPENAI_API_KEY env var
        // ...
    }
  5. Install OpenAI-CPP

    main

    OpenAI-CPP is a header-only library. To install it, copy the include/openai folder from the repository into your project's include directory. You can then use #include "openai.hpp" in your C++ code.

    Note: The library includes a copy of nlohmann/json.hpp. If you already use Nlohmann Json in your project, you can omit the library's internal JSON header to improve compile times.

    #include "openai.hpp"
  6. Use OpenAI-CPP for Completions and Images

    main

    The library provides high-level interfaces for various OpenAI endpoints. It uses nlohmann::json (aliased as openai::Json) for data handling, allowing you to pass parameters using JSON literals or initializer lists.

    Create a Completion

    Use openai::completion().create() with a JSON object containing model and prompt.

    Create an Image

    Use openai::image().create() with an initializer list containing prompt, n, and size.

    #include "openai.hpp"
    #include <iostream>
    
    int main() {
        openai::start();
    
        // Completion using raw string literal JSON
        auto completion = openai::completion().create(R"({
            "model": "text-davinci-003",
            "prompt": "Say this is a test",
            "max_tokens": 7,
            "temperature": 0
        })"_json);
        std::cout << "Response is:\n" << completion.dump(2) << '\n';
    
        // Image using initializer lists
        auto image = openai::image().create({
            { "prompt", "A cute koala playing the violin"},
            { "n", 1 },
            { "size", "512x512" }
        });
        std::cout << "Image URL is: " << image["data"][0]["url"] << '\n';
    }
  7. Use low-level HTTP methods for full control

    main
    If you need to access OpenAI API features that are not yet implemented in the library's high-level wrappers, you can use the openai::post() or openai::get() methods to send custom requests directly.