How to use OpenAI API with Python

Hello everyone, this article is written specifically for a video on getting access to GPT-3.

Before showing you how to get an api, I have to tell you a few very important things:

The first is an API that provides access to GPT-3, which performs a wide range of tasks in natural language, mainly in English. You can embed this api into your project, but there is one catch that I will tell you now.

And so the second. When you get access to the API, you will be given $ 18 to the account (this is your trial period), this amount will be in your account until you spend it or until the trial period expires, which is three months. Next, you will have to top up your account.

GETTING API KEY

To get access, go to the site openai.com/api / and press the sign up button. On the page that opens, enter your email and come up with a password, then confirm your email. After confirming the mail, we go back to the site openai.com/api / and now press the log in button. Enter the email and password of the newly created account, click the continue button, enter your first and last name here, the name of the organization is not required. Next, we confirm our phone number, enter the verification code. IMPORTANT The phone number can be used for several accounts, but the trial period will be credited only to one, the first account created. After verification, we choose how we will use the API and the account is created!

Now click on the icon of our account and select view api keys. On this page we can create a new api key, we will need it later, now that we have an api key, we can proceed to writing code to interact with the api.

CODE

Open the code editor or ide, in my case it’s pycharm, create a project. Immediately create a new python file in which the api key will be stored. Let’s call it config. And now we import config into the main file. And in the config itself we will put the api key. This is all necessary to make the code look better and more convenient, all important settings are in config.

Now we import and install the openai python module with the pip install openai command. Refer to the property of the openai module and pass our token from config.

Now let’s choose a ready-made example and test it. Go back to the site to the examples page and select the example ‘question-answer’ https://beta.openai.com/examples here we can see Prompt is an instruction for gpt3 so that he understands what needs to be done, I’ll tell you about the settings a little later. We need the request API. Copy this part of the code and go back to pycharm.

Creating a question function with a question argument that will accept our question. But you’d better call the argument something else, so as not to get confused, I’m just showing it as an example. We insert the code we just copied into this function and immediately change a couple of settings. We add the return operator that returns the result of our api request from the response variable, access the choices key with a zero index, and then the text key. Then we change Engine to davinci.

Now we turn to the function and pass the argument, that is, our question. What remains for us to do is to output the result. But now he won’t answer our question, because we need to change the instructions. In prompt, at the end, we replace the question with our attribute, write {question} and create an f string by writing f at the beginning. We are trying now and everything has worked for us. If we just write return response, then we will get a dictionary.

Now let’s ask the question who is Elon Musk. We see the answer, now we will change the value of tokens by 10, as you can see the answer has become shorter. Tokens are like fragments of words used for natural language processing. For English text, 1 token is equal to about four characters. I will leave a link to the site page where you can count the number of tokens in the text. 1000 tokens is 750 words, prices range from 0.0008 dollars for 1 thousand tokens if you use the Ada model, to 0.06 dollars for 1 thousand tokens if you use the Davinci model. I will make a separate video about the difference between all models and their advantages, so I advise you to subscribe to the channel.

One of the most important settings is called temperature. You may have noticed that if you submit the same question multiple times, the model will always return identical or very similar answers. This is because your temperature is set to 0. Now try to resend the same question multiple times with the temperature set to 1 or close to one. Lowering the temperature means there will be fewer risks, and completion will be more precise and deterministic. An increase in temperature will lead to a more diverse completion.

Engine, prompt, temperature, max_tokens are the most important settings. The rest is not necessary to change.

PRICES, ACCOUNT DEPOSITS

After we figured out how it all works, let me show you how to top up your balance. Go to the pricing tab https://openai.com/api/pricing /, here we can see all prices for all models, as well as prices for Fine-tuned models and Embedding models are custom models that you can create yourself, we’ll talk about them in other videos. To link the card, go to manage account, billing, setup paid account. When your trial period ends, you will be offered to buy tokens. In the meantime, you can test artificial intelligence for free.

The full code is here – https://github.com/itprosta/openai_api_py

Всем привет эта статья написана специально для видео по получению доступа к GPT-3.

Перед тем как показать как получить апи, я должен рассказать вам несколько очень важных вещей:

Первое – это апи которое предоставляет доступ к GPT-3, который выполняет широкий спектр задач на естественном языке, в основном на английском. Вы можете встроить это апи в ваш проект, но есть одна загвоздка, которую я сейчас расскажу.

И так второе. Когда вы получите доступ к апи, вам дадут 18 долларов на счет (это ваш пробный период), эта сумма будет у вас на счете пока вы их не потратите или пока не истечет пробный период, а это три месяца. Далее вам придется пополнять счет.

ПОЛУЧЕНИЕ АПИ КЛЮЧА

Чтобы получить доступ, переходим на сайт openai.com/api/ и нажимаем кнопку sign up. На открывшейся странице вводим свою почту и придумываем пароль, далее подтверждаем свою почту. После подтверждения почты переходим назад на сайт openai.com/api/ и теперь нажимаем кнопку log in. Вводим почту и пароль только что созданного аккаунта, нажимаем кнопку continue, здесь вводим ваше имя и фамилию, название организации не обязательно. Далее подтверждаем свой номер телефона, вводим проверочный код. ВАЖНО номер телефона может быть использован для нескольких аккаунтов, но пробный период будет начислен только на один, первый созданный аккаунт. После верификации выбираем как мы будем использовать апи и аккаунт создан!

Теперь нажимаем на иконку нашего аккаунта и выбираем view api keys. На этой странице мы можем создать новый апи ключ, он нам понадобится позже, теперь когда у нас есть апи ключ, мы можем перейти к написанию кода для взаимодействия с апи.

КОД

Открываем редактор кода или ide, в моем случае это pycharm, создаем проект. Сразу создадим новый пайтон файл в котором будет хранится апи ключ. Назовем его config. И теперь в основной файл импортируем config. А в сам config поместим апи ключ. Это все надо для того чтобы код выглядел лучше и удобнее, все важные настройки находятся в config.

Теперь импортируем и устанавливаем openai python модуль командой pip install openai. Обращаемся к свойству модуля openai и передаем наш токен из config.

Теперь давайте выберем готовый пример и протестируем. Переходим назад на сайт на страницу примеров и выберем пример ‘вопрос-ответ’ https://beta.openai.com/examples тут мы можем увидеть Prompt это инструкция для gpt3 чтобы он понял что надо сделать, про настройки я расскажу чуть позже. Нам нужен API request. Копируем эту часть кода и переходим назад в pycharm.

Создаем функцию question с аргументом question который будет принимать наш вопрос. Но вы лучше назовите аргумент как-то по другому, чтобы не путаться, я же просто показываю как пример. В эту функцию вставляем только что скопированный код и сразу изменим пару настроек. Добавляем оператор return который возвращает результат нашего апи запроса из переменной response, обращаемся к ключу choices с нулевым индексом, а затем к ключу text. Затем Engine меняем на davinci.

Теперь обращаемся к функции и передаем аргумент то есть наш вопрос. Что нам остается сделать это вывести результат. Но сейчас он нам не ответит на наш вопрос, потому что нам надо изменить инструкцию. В prompt в конце заменяем вопрос на наш атрибут, пишем {question} и создаем f строку написав f в начале. Пробуем теперь и у нас все заработало. Если же мы просто напишем return response тогда мы получим словарь.

Теперь зададим вопрос кто такой Elon Musk. Мы видим ответ, теперь изменим значение токенов на 10, как видите ответ стал короче. Токены это как фрагменты слов, используемые для обработки естественного языка. Для английского текста 1 токен равен примерно четырем символам. Я оставлю ссылку на страницу сайта где можно посчитать количество токенов в тексте. 1000 токенов это 750 слов, цены варьируются от 0.0008 долларов за 1 тысячу токенов если использовать модель Ada, до 0.06 долларов за 1 тысячу токенов если использовать модель Davinci. Я отдельно сниму видео про различие между всеми моделями и их преимуществами, поэтому советую подписаться на канал.

Одна из самых важных настроек называется температура. Вы, возможно, заметили, что если вы отправляете один и тот же вопрос несколько раз, модель всегда будет возвращать идентичные или очень похожие ответы. Это потому что ваша температура установлена на 0. Теперь попробуйте повторно отправить один и тот же вопрос несколько раз с температурой, установленной на 1 или близко к одному. Снижение температуры означает, что будет меньше рисков, а завершение будет более точным и детерминированным. Повышение температуры приведет к более разнообразному завершению.

Engine, prompt, temperature, max_tokens – это самые важные настройки. Остальное менять не обязательно.

ЦЕНЫ, ПОПОЛНЕНИЯ СЧЕТА

После того как мы разобрались как это все работает, давайте я вам покажу как пополнить свой баланс. Переходим на вкладку pricing https://openai.com/api/pricing/, тут мы можем увидеть все цены для всех моделей, так же цены для Fine-tuned models и Embedding models это кастомные модели которые вы сами можете создать, про них мы поговорим в других видео. Чтобы привязать карту, переходим в manage account, billing, setup paid account. Когда у вас закончится пробный период, вам предложат купить токены. А пока вы можете протестировать искусственный интеллект бесплатно.

Полный код тут – https://github.com/itprosta/openai_api_py

Leave a Reply