Connect Sinatra with OpenAI API
I had been thinking about how to connect ruby apps with OpenAI API, so I decided to see it. First, I started with exploring and understanding the new ChatGPT launched by OpenAI, how it works, what can I do with it, etc.
To test this, I decided to divide this into two phases:
Define and create the Sinatra project
To start, I thought of creating a simple project in Sinatra that received a text and sent it to the API, so the response is processed by the project again, rendering it in the view.
I started creating a simple project with a form that received the information
Where the code into the form in the view is the following:
Showing this:
Integrate OpenAI into the project
The first step for this phase is to get the secret API key from the OpenAI page
Now is the moment to integrate the API into the project. According to the documentation available here, there are multiple options, in this case, I choose the ruby-openai gem.
Get fab’s stories in your inbox
Join Medium for free to get updates from this writer.
Now, according to the gem documentation, I added the configuration in the project using a gem to manage the API key, in this case, I’m using dotenv. I added a token named TOKEN_OPENAI and I call it from the project assigning this to the client.
After this, I added a POST method to process the text sent from the form, pass this to the client created, take the response object, and look for the answer text, to finalize returning it to the index page.
To render the text_response , I added a div to showing this
And this is the result:
What is the next step?
Now, the idea is played with the parameters sent to the API like the model , tokens , or other parameters. You can find more information at https://platform.openai.com/docs/introduction/overview
If you like to access the code, I have published this in the next link: https://github.com/developerfab/sinatra_ia







