Настройка ключей API для OpenAI

:bookmark: Это руководство объясняет, как настроить API-ключи для OpenAI, чтобы включить функции Discourse AI, требующие ключей сторонних LLM.

:person_raising_hand: Требуемый уровень пользователя: Администратор

В этом примере мы используем OpenAI для генерации ключей.

Примечание: Скорее всего, вам потребуется платный тариф, и оплата будет производиться за использование. Актуальную информацию о тарифах и ценах см. здесь: ссылка.

Платформы постоянно меняются, поэтому данное руководство может не на 100% точно отражать весь процесс.

:information_source: Для использования определённых модулей ИИ пользователи должны иметь API-ключ от стороннего провайдера, такого как OpenAI (ChatGPT), Anthropic (Claude), Google (Gemini) и т. д.

Пожалуйста, проверьте каждый модуль ИИ, чтобы узнать, какие сторонние провайдеры для него поддерживаются.

Генерация API-ключа

  1. Войдите в OpenAI. API-ключ можно получить здесь: OpenAI Platform
  2. Сгенерируйте API-ключ.
  3. После генерации ключа сохраните его в надёжном и безопасном месте и скопируйте.

Использование API-ключа для Discourse AI

Discourse AI использует систему Secrets (Секреты) для управления API-ключами. Вместо того чтобы вставлять ключи напрямую в конфигурации отдельных LLM, вы создаёте именованный секрет, а затем ссылаетесь на него из одного или нескольких LLM.

Создание секрета (опционально, можно сделать inline)

  1. Перейдите в AdminPluginsAI → вкладка Secrets.
  2. Нажмите New Secret.
  3. Введите имя для секрета (например, “OpenAI API Key”).
  4. Вставьте ваш API-ключ в поле Secret.
  5. Сохраните секрет.

Настройка LLM

  1. Перейдите в AdminPluginsAI → вкладка LLMs.
  2. Выберите шаблон предварительно настроенной модели (например, модель OpenAI) и нажмите кнопку Configure, либо нажмите Edit на уже настроенном LLM.
  3. В поле API Key выберите из выпадающего списка созданный вами секрет. Вы также можете создать новый секрет inline, нажав кнопку + рядом с выпадающим списком.
  4. Сохраните LLM.
6 лайков

no matter what we do, it always says openai gpt-4 not configured.

what am i missing?

2 лайка

Where is this popping up for you and I’m assuming you have inputted in the OpenAI key? where there any other settings you have changed? have you tried a refresh on the browser post inputting in the key - does that help?

we have three valid openai keys we use for other things so i know they work.

no matter what we do, this is an example of the rror we get:

What’s the output of running

curl https://api.openai.com/v1/chat/completions   -H "Content-Type: application/json"   -H "Authorization: Bearer $OPENAI_API_KEY"   -d '{
    "model": "gpt-4",
    "messages": [
      {
        "role": "system",
        "content": "You are a poetic assistant, skilled in explaining complex programming concepts with creative flair."
      },
      {
        "role": "user",
        "content": "Compose a poem that explains the concept of recursion in programming."
      }
    ]
  }'

in your Discourse server? Don’t forget to place your API key on the command.

3 лайка

will login to our server and check this out.

{
“id”: “chatcmpl-8vT2UYe6i5m9EO0N4KdG6klcO4dVJ”,
“object”: “chat.completion”,
“created”: 1708707014,
“model”: “gpt-4-0613”,
“choices”: [
{
“index”: 0,
“message”: {
“role”: “assistant”,
“content”: “A tale within a tale untold,\nAn echo of a mirrored call,\nSuch is used in software’s sprawl,\nA concept called recursion, all.\n\nImagine a box within a box,\nEach pregnant with the one before,\nEach step to the origin restores,\nInfinite layers, like paradox.\n\nLike Russian dolls, a dream within,\nEach smaller than the one outside,\nYet hiding life within they reside,\nA patterned approach to chaos, therein.\n\nFrom problem to sub-problem, there,\nEach atom is an image proud,\nOf the larger form that’s to be found,\nTwisted whirls of logic’s flare.\n\nConjuring functions that call their own,\nIt tumbles down, a spiral vast,\nBut in the base case, it rests at last,\nThe seeds of recursion thus are sown.\n\nIn every loop’s heart you’ll find,\nA recursion lightly spinning, twined.\nWith every thread of question lined,\nIt folds back on itself, yet unconfined.\n\nBut dear programmers, mind your step,\nInfinite loops are hell’s gateway,\nKeep thy base case in the array,\nThe art of recursion, now adept.\n\nRepeating tasks, yet ever smaller,\nWith each pass, yet closer to end,\nDecomposing problems, our trusted friend,\nRecursion in code, the infinite caller.”
},
“logprobs”: null,
“finish_reason”: “stop”
}
],
“usage”: {
“prompt_tokens”: 39,
“completion_tokens”: 265,
“total_tokens”: 304
},
“system_fingerprint”: null
}

claude-v2 does not return an error.

I’ve been prompted to use another model as they are moving away from GPT-3.5 Turbo from OpenAI. However, I’m getting this error message when I “Run Test,” and for the life of me, I can’t remember if I’m missing anything.

2 лайка

This is now fixed. I removed all of the LLMs and restarted again. Most of the settings took a while to start again, especially having to undo them and then enable them again. But after a few attempts, it is all up and running using 4 Mini.

3 лайка

It’s possible to use third-party OpenAI API services like https://api.aimlapi.com/v1/embeddings?

I get 500 errors when trying.

Did you debug using: