Langsung ke konten utama
LiteLLM menyediakan API Python terpadu untuk 100+ penyedia LLM. CometAPI didukung secara native — gunakan prefix cometapi/ untuk merutekan request melalui katalog model CometAPI.

Prasyarat

1

Instal LiteLLM

pip install litellm
2

Set API key Anda

Set API key sebagai environment variable (disarankan) atau kirim secara inline:
import os
from litellm import completion

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

# Alternative: pass inline
api_key = "<COMETAPI_KEY>"
Gunakan environment variable untuk menghindari hardcoding kredensial sensitif di script Anda.
3

Buat panggilan completion

Gunakan format cometapi/<model-name> untuk menentukan model. Anda dapat mengirim key melalui environment variable atau secara eksplisit:
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)
4

Panggilan async dan streaming

Gunakan acompletion dengan stream=True untuk respons non-blocking dan real-time:
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())
  • Format model: Model CometAPI menggunakan prefix cometapi/<model-name>, misalnya cometapi/your-model-id. Lihat halaman Model CometAPI untuk model yang tersedia.
  • Respons Fine-tuning: LiteLLM mendukung temperature, max_tokens, dan top_p — tambahkan ke panggilan completion() apa pun, misalnya completion(..., temperature=0.7).
  • Penanganan error: Bungkus panggilan dalam try/except untuk menangkap error key tidak valid atau masalah jaringan.
  • Keamanan: Jangan pernah commit API key ke version control. Gunakan environment variable atau secrets manager.
  • Rate limit: Pantau penggunaan di console CometAPI.
  • Dokumentasi lebih lanjut: dokumentasi LiteLLMquick start CometAPI