Niki is a low-level API client for OpenAI. It features an intuitive interface that maps directly to the OpenAI API.
# Create a new client
client = Niki.new(api_key: "openai-api-key")-
Create a message (Uses the Responses API):
response = client.messages.create( model: "gpt-5.4", input: "Tell me a three sentence bedtime story about a unicorn." ) if response.error response.error.try do |error| puts error.code puts error.message # ... end else response.data.try do |message| puts message.id puts message.model message.output.try &.each do |output| puts output.type puts output.status puts output.role output.content.try &.each do |content| puts content.type puts content.text # ... end # ... end end # ... end
-
Create a chat completion:
response = client.completions.create( model: "gpt-5.4", messages: [ { role: Niki::Role::Developer, content: "You are a helpful assistant." }, { role: Niki::Role::User, content: "Hello!" } ] ) if response.error response.error.try do |error| puts error.code puts error.completion # ... end else response.data.try do |completion| puts completion.id puts completion.model completion.choices.try &.each do |choice| puts choice.finish_reason puts choice.index choice.message.try do |message| puts message.content puts message.refusal puts message.role # ... end # ... end end # ... end
-
List models:
response = client.models.list(limit: 10) if response.error response.error.try do |error| puts error.type puts error.message # ... end else response.data.try &.each do |model| puts model.id puts model.created puts model.owned_by # ... end end
Find the complete documentation in the docs/ directory of this repository.
Generate an API key from your OpenAI account.
Create a .env.sh file:
#!/usr/bin/env bash
#
export OPENAI_API_KEY='your-openai-api-key-here'Update the file with your own details. Then run tests with source .env.sh && crystal spec.
IMPORTANT: Remember to set permissions for your env file to 0600 or stricter: chmod 0600 .env*.
- Fork it
- Switch to the
masterbranch:git checkout master - Create your feature branch:
git checkout -b my-new-feature - Make your changes, updating changelog and documentation as appropriate.
- Commit your changes:
git commit - Push to the branch:
git push origin my-new-feature - Submit a new Pull Request against the
GrottoPress:masterbranch.