> ## Documentation Index
> Fetch the complete documentation index at: https://apidoc.cometapi.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Використання LiteLLM з CometAPI

> Скористайтеся цим посібником, щоб налаштувати LiteLLM з CometAPI, вказавши base URL, API key, а також параметри model або provider.

LiteLLM надає уніфікований Python API для 100+ постачальників LLM. CometAPI підтримується нативно — використовуйте префікс `cometapi/`, щоб маршрутизувати запити через каталог моделей CometAPI.

## Передумови

* Python 3.6+
* Обліковий запис CometAPI з активним API key — [отримайте його тут](https://www.cometapi.com/console/token)

<Steps>
  <Step title="Встановіть LiteLLM">
    ```bash theme={null}
    pip install litellm
    ```
  </Step>

  <Step title="Установіть свій API key">
    Установіть API key як змінну середовища (рекомендовано) або передайте його inline:

    ```python theme={null}
    import os
    from litellm import completion

    # Recommended: environment variable
    os.environ["COMETAPI_KEY"] = "<COMETAPI_KEY>"

    # Alternative: pass inline
    api_key = "<COMETAPI_KEY>"
    ```

    <Note>
      Використовуйте змінні середовища, щоб уникнути жорсткого кодування конфіденційних облікових даних у ваших скриптах.
    </Note>
  </Step>

  <Step title="Зробіть виклик completion">
    Використовуйте формат `cometapi/<model-name>` для вказання моделей. Ви можете передати ключ через змінну середовища або явно:

    ```python theme={null}
    messages = [{"content": "Hello, how are you?", "role": "user"}]

    # Method 1: environment variable (recommended)
    response = completion(model="cometapi/your-model-id", messages=messages)

    # Method 2: explicit API key
    response = completion(model="cometapi/your-model-id", messages=messages, api_key=api_key)

    print(response.choices[0].message.content)
    ```
  </Step>

  <Step title="Асинхронні та Streaming виклики">
    Використовуйте `acompletion` з `stream=True` для неблокувальних відповідей у реальному часі:

    ```python theme={null}
    from litellm import acompletion
    import asyncio, traceback

    async def stream_call():
        try:
            response = await acompletion(
          model="cometapi/your-model-id",
                messages=[{"content": "Hello, how are you?", "role": "user"}],
                stream=True,
            )
            async for chunk in response:
                print(chunk)
        except Exception:
            print(f"Error: {traceback.format_exc()}")

    asyncio.run(stream_call())
    ```
  </Step>
</Steps>

<AccordionGroup>
  <Accordion title="Поради та усунення несправностей">
    * **Формат моделі**: Моделі CometAPI використовують префікс `cometapi/<model-name>`, наприклад `cometapi/your-model-id`. Перегляньте [сторінку моделей CometAPI](/uk/overview/models), щоб побачити доступні моделі.
    * **Відповіді Fine-tuning**: LiteLLM підтримує `temperature`, `max_tokens` і `top_p` — додайте їх до будь-якого виклику `completion()`, наприклад `completion(..., temperature=0.7)`.
    * **Обробка помилок**: Обгорніть виклики в `try/except`, щоб перехоплювати помилки недійсного ключа або проблеми з мережею.
    * **Безпека**: Ніколи не комітьте API key у систему контролю версій. Використовуйте змінні середовища або менеджер секретів.
    * **Ліміти швидкості**: Відстежуйте використання в [консолі CometAPI](https://www.cometapi.com/console).
    * **Більше документації**: [документація LiteLLM](https://docs.litellm.ai/docs/) — [швидкий старт CometAPI](/uk/overview/quick-start)
  </Accordion>
</AccordionGroup>

<script type="application/ld+json">
  {`
    {
    "@context": "https://schema.org",
    "@graph": [
      {
        "@type": "HowTo",
        "@id": "https://apidoc.cometapi.com/integrations/litellm#howto",
        "name": "Використання LiteLLM з CometAPI",
        "description": "Використовуйте цей посібник, щоб налаштувати LiteLLM з CometAPI, указавши base URL, API key і параметри моделі або провайдера.",
        "step": [
          {
            "@type": "HowToStep",
            "@id": "https://apidoc.cometapi.com/integrations/litellm#step-1",
            "position": 1,
            "name": "Встановіть LiteLLM",
            "text": "Виконайте крок «Встановіть LiteLLM» у посібнику «Використання LiteLLM з CometAPI»."
          },
          {
            "@type": "HowToStep",
            "@id": "https://apidoc.cometapi.com/integrations/litellm#step-2",
            "position": 2,
            "name": "Установіть свій API key",
            "text": "Збережіть свій API key CometAPI у змінній середовища або в полі налаштувань, яке використовує інтеграція."
          },
          {
            "@type": "HowToStep",
            "@id": "https://apidoc.cometapi.com/integrations/litellm#step-3",
            "position": 3,
            "name": "Зробіть виклик completion",
            "text": "Виконайте крок «Зробіть виклик completion» у посібнику «Використання LiteLLM з CometAPI»."
          },
          {
            "@type": "HowToStep",
            "@id": "https://apidoc.cometapi.com/integrations/litellm#step-4",
            "position": 4,
            "name": "Асинхронні та Streaming виклики",
            "text": "Виконайте крок «Асинхронні та Streaming виклики» у посібнику «Використання LiteLLM з CometAPI»."
          }
        ]
      },
      {
        "@type": "BreadcrumbList",
        "itemListElement": [
          {
            "@type": "ListItem",
            "position": 1,
            "name": "Документація CometAPI",
            "item": "https://apidoc.cometapi.com/"
          },
          {
            "@type": "ListItem",
            "position": 2,
            "name": "Інтеграції",
            "item": "https://apidoc.cometapi.com/integrations"
          },
          {
            "@type": "ListItem",
            "position": 3,
            "name": "Використання LiteLLM з CometAPI",
            "item": "https://apidoc.cometapi.com/integrations/litellm"
          }
        ]
      }
    ]
    }
    `}
</script>
