Sitemap
fab

fab

Hi, I am a Software Developer passionate about think the world.

Connect Sinatra with OpenAI API

3 min readMar 7, 2023

--

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

Code in the app.rb

Where the code into the form in the view is the following:

Press enter or click to view image in full size
Code for index.erb file

Showing this:

Press enter or click to view image in full size
index view of the project

Integrate OpenAI into the project

The first step for this phase is to get the secret API key from the OpenAI page

Press enter or click to view image in full size
Page to get API keys

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.

Press enter or click to view image in full size
code with client configuration

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.

POST method to send the request to the API and process the response

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

--

--

fab
fab

Written by fab

Hi, I am a Software Developer passionate about think the world.