API Doc-CometAPI
Русский
  • English
  • Русский
HomeDashBoardModel Marketplace
HomeDashBoardModel Marketplace
Discord_Support
Русский
  • English
  • Русский
  1. 🧩 Integration Guides
  • 🚀 Overview
    • Быстрый старт
    • Важные рекомендации
    • Release Notes
    • Модели
  • 💬 Text Models-OpenAI Format
    • Anthropic Compatiable
      • Anthropic Claude
    • Chat
    • response
    • gpt-4o-image generates image
    • Images
    • Image Editing (gpt-image-1)
    • Recognizing Images
    • Embeddings
    • Realtime
    • Hunyuan3D
  • 🖼️ Midjourney(images)
    • Quick Tutorial - Complete Process in One Go
    • Task Fetching API
      • List by Condition
      • Fetch Single Task (most recommended)
    • Imagine
    • Submit Video
    • Submit Editor
    • Action (UPSCALE; VARIATION; REROLL; ZOOM, etc.)
    • Blend (image -> image)
    • Describe (image -> text)
    • Modal (Area Redesign & Zoom)
  • 🖼️ Image Models
    • Flux(images)
      • Generate image (replicate format)
      • Create Task - General
      • flux fine-tune images(Temporarily unavailable)
      • flux generate image(Temporarily unavailable)
      • flux query
    • seededit/seedream
      • bytedance-image-generation(seedream)
      • bytedance-Image Editing (seededit)
    • Replicate(image)
      • Create Task - General
      • Create Task -flux-kontext-pro、max
      • Create Task -flux-1.1-pro
      • Create Task -flux-1.1-pro-ultra
      • replicate query
    • Recraft(Temporarily removed)
      • Appendix
      • Recraft Generate Image
      • Recraft Vectorize Image
      • Recraft Remove Background
      • Recraft Clarity Upscale
      • Recraft Create style
      • Recraft Generative Upscale
    • Ideogram(Temporarily removed)
      • Official documentation (updated in real time)
      • Generate 3.0 (text to image)
      • Remix 3.0 (hybrid image)
      • Reframe 3.0(Reconstruction)
      • Replace Background 3.0(Background replacement)
      • Edit 3.0(Editing images)
      • ideogram Text Raw Image
      • ideogram Hybrid image
      • ideogram enlargement HD
      • ideogram describes the image
      • ideogram Edit image((legacy))
    • Gemini
      • Guide to calling gemini-2.5-flash-image
      • Gemini generates image
      • Gemini text dialog
  • 🎵 Music Models
    • Suno
      • Setting suno Version
      • Suno API Scenario Application Guide
      • Generate lyrics
      • Generate music clip
      • Upload clip
      • Submit concatenation
      • Full Track Audio Separation
      • Single Track Audio Separation
      • Create New Persona
      • Single task query
      • Generate mp4 mv video
      • Timing: lyrics, audio timeline
      • Get wav format file
      • Batch query tasks
    • Udio(Temporarily unavailable)
      • Generate music
      • Task query
  • 📺 Video Models
    • veo3
      • veo3-chat format
      • Submit video generation task
      • Query video generation status
    • runway(video)
      • official format
        • runway images raw video
        • Generate a video from a video
        • Generate an image from text
        • Upscale a video
        • Control a character
        • runway to get task details
      • Reverse Format
        • generate(text)
        • generate(Reference images)
        • Video to Video Style Redraw
        • Act-one Expression Migration
        • feed-get task
    • kling (video)
      • callback_url
      • Multimodal Video Editing
        • Initialize Video for Editing
        • Add Video Selection
        • Delete Video Selection
        • Clear Video Selection
        • Preview Selected Video Area
        • Create Task
      • Generating images
      • Expanded
      • Text Generation Video
      • Image Generation Video
      • Multi-Image To Video
      • Multi-Image to Image
      • Video Extension
      • virtual try-on
      • lip sync
      • effects
      • Video to audio
      • Text to audio
      • Individual queries
    • bytedance
      • bytedance-video
      • bytedance-video get
    • MiniMax Conch(video)
      • MiniMax Conch Official Documentation
      • MiniMax Conch Generation
      • MiniMax Conch Query
      • MiniMax Conch Download
    • luma (video)(temporarily dismantle)
      • Official api interface format
        • luma generate
        • luma search
    • PIKA(temporarily dismantle)
      • pika feed
      • PIKA Reference Video Generation
      • PIKA Reference Image Generation
      • PIKA reference text generation
    • sora(temporarily dismantle)
      • Reverse Format
        • Create Video
        • Query Video Task
        • Create Video
  • 🔊 Audio Models
    • Create speech
    • Create transcription
    • Create translation
  • ⚠️ Errors
    • Коды ошибок и обработка
  • 📝 Code Examples
    • Text-to-Image Generation
    • Image-to-Image Generationèurl uploadé
    • Regular Post Text Conversation
    • OpenAI Official Library Usage Example
    • Streamed Output
    • Json Fixed Format Output Code Display
    • Embedding code example
    • o1-preview Model Code Example
    • LangChain Usage Example (Successful Test Date: 2024-11-25)
    • Openai dall-e-3 & flux series drawing model
    • gpt, claude, gemini multimodal network image parsing example
    • Multimodal PDF File Parsing Examples for GPT, Claude, and Gemini
    • Code example
  • 🧩 Integration Guides
    • continue
    • Chatbox
    • CherryStudio
    • COMET API API Call Testing
    • Lobe-Chat
    • Cursor
    • LangChain
    • AnythingLLM
    • gptme
    • Immersive Translation
    • Cline
    • Eudic Translation
    • ChatHub
    • OpenAI Translator
    • ChatAll Translation
    • Pot Translation
    • Zotero
    • NEXT CHAT (ChatGPT Next Web)
    • Obsidian's Text Generator Plugin
    • librechat
    • Lazy Customer Service
    • utools-ChatGPT Friend
    • avante.nvim
    • Open WebUI
    • GPT Academic Optimization (gpt_academic)
    • OpenManus
    • IntelliJ Translation Plugin
    • n8n
    • FastGPT
    • COZE
    • zapier
    • LiteLLM
    • MAKE
    • n8n Local Deployment
    • buildship
    • sillytavern
    • LlamaIndex
    • activepieces
    • FlowiseAI
    • Dify
  • 🏄🏼‍♀️ Best Practices
    • Midjourney Best Practices
    • Retry Logic Documentation for CometAPI and OpenAI Official API
    • Runway Best Practices
    • CometAPI Account Balance Query API Usage Instructions
    • Claude Code Installation and Usage Guide
    • Gemini CLI Installation and Usage Guide
    • Codex Usage Guide
  • 💳 Pricing & Billing
    • О ценообразовании
  • 🤝🏼 Support
    • Help Center
    • Interface Stability
    • Privacy policy
    • Terms of service
    • Common Misconceptions
    • Confusion about use
  1. 🧩 Integration Guides

LlamaIndex

1. Preparation#

• Log in to cometapi. Click "ADD API key" in the API keys to get your token key: sk-xxxxx
image.png
image.png
image.png

Prerequisites#

Python 3.8+ installed.
A CometAPI account. Generate an API key from the API Keys page.
Jupyter Notebook or Python environment (Google Colab recommended for interactive testing).

Step 1: Install LlamaIndex#

Install the LlamaIndex library and CometAPI integration using pip. This is a one-time setup.

Step 2: Set Up API Key#

You need the key obtained from CometAPI to authenticate requests. You can set it in environment variables or pass it in the class constructor.
Python example:
Note: Using environment variables is more secure to avoid hardcoding sensitive information in scripts.

Step 3: Perform Basic Completion Calls#

Initialize the model using LlamaIndex's CometLLM class and call the chat or complete methods. You can specify models like gpt-5-chat-latest or gpt-4o.
Example:
Expected Output:
Chat response: e.g., assistant: Hi
Completion response: e.g., a text description about Kaiming He, including information on ResNet.
This sends a simple message and retrieves the model response. You can customize messages for more complex interactions.

Step 4: Streaming Calls#

For real-time applications, use the stream_chat or stream_complete methods for streaming responses.
Example:
Explanation:
stream_chat and stream_complete generate responses chunk by chunk, suitable for real-time output.
If an error occurs, it will be displayed in the console.
Expected Output:
Streaming printed response content, e.g., an explanation of ResNet or an overview of large language models, appearing in chunks.

Additional Tips#

Supported Models: CometAPI supports various models such as gpt-5-chat-latest, gpt-4o, claude-3-7-sonnet-latest, etc. Check the CometAPI documentation for the latest list.
Error Handling: Always wrap calls in try-except blocks to handle invalid keys or network errors.
Advanced Features: LlamaIndex supports parameters like max_tokens and temperature for fine-tuning responses. Add them during CometLLM initialization.
Security: Never commit API keys to version control. Use environment variables or secret managers.
Troubleshooting: If issues arise, ensure the API key is valid and check LlamaIndex logs. For more details, refer to the LlamaIndex documentation or CometAPI documentation or Colab Example.
Other Models: For example, using a Claude model: claude_llm = CometLLM(api_key=api_key, model="claude-3-7-sonnet-latest", max_tokens=1024).
Rate Limits and Costs: Monitor usage in the CometAPI console.

Code Example
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "initial-install",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install llama-index-llms-cometapi\n",
    "%pip install llama-index"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "setup-api-key",
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.llms.cometapi import CometLLM\n",
    "import os\n",
    "\n",
    "# Set API key\n",
    "\n",
    "# Open the [API Keys](https://api.cometapi.com/console/token) page in CometAPI.\n",
    "# Create a new key or copy an existing one,\n",
    "# then paste it here.\n",
    "os.environ[\"COMETAPI_KEY\"] = ''\n",
    "api_key = os.getenv(\"COMETAPI_KEY\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "basic-calls",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Initialize LLM\n",
    "llm = CometLLM(\n",
    "    api_key=api_key,\n",
    "    max_tokens=256,\n",
    "    context_window=4096,\n",
    "    model=\"gpt-5-chat-latest\",\n",
    ")\n",
    "\n",
    "# Chat call using ChatMessage\n",
    "from llama_index.core.llms import ChatMessage\n",
    "\n",
    "messages = [\n",
    "    ChatMessage(role=\"system\", content=\"You are a helpful assistant\"),\n",
    "    ChatMessage(role=\"user\", content=\"Say 'Hi' only!\"),\n",
    "]\n",
    "resp = llm.chat(messages)\n",
    "print(resp)\n",
    "\n",
    "# Use complete method\n",
    "resp = llm.complete(\"Who is Kaiming He\")\n",
    "print(resp)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "streaming-calls",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Streaming chat\n",
    "message = ChatMessage(role=\"user\", content=\"Tell me what ResNet is\")\n",
    "resp = llm.stream_chat([message])\n",
    "for r in resp:\n",
    "    print(r.delta, end=\"\")\n",
    "\n",
    "# Streaming completion\n",
    "resp = llm.stream_complete(\"Tell me about Large Language Models\")\n",
    "for r in resp:\n",
    "    print(r.delta, end=\"\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "different-model",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Use Claude model\n",
    "claude_llm = CometLLM(\n",
    "    api_key=api_key, model=\"claude-3-7-sonnet-latest\", max_tokens=200\n",
    ")\n",
    "\n",
    "resp = claude_llm.complete(\"Explain deep learning briefly\")\n",
    "print(resp)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8+"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
Modified at 2025-09-08 08:03:29
Previous
sillytavern
Next
activepieces
Built with