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

# LlamaIndex

> OpenAI互換インテグレーションを使用してTokenLabをLlamaIndexに統合する

## 概要

<Note>
  **タイプ**: フレームワークまたはプラットフォーム

  **推奨パス**: OpenAILike を介した OpenAI互換

  **サポートの信頼性**: OpenAILike を介してサポート
</Note>

TokenLabにおいて、より堅牢なLlamaIndexのセットアップ方法は、組み込みのOpenAIクラスではなく、**OpenAI互換インテグレーション**を使用することです。

現在のLlamaIndexのドキュメントでは、サードパーティのOpenAI互換エンドポイントに対して `OpenAILike` を明示的に推奨しています。これは、組み込みのOpenAIクラスが公式のモデル名からメタデータを推論するためです。

言い換えれば、ここでのTokenLabのサポートパスは、組み込みのOpenAIクラスではなく `OpenAILike` であると見なしてください。

## インストール

```bash theme={null}
pip install llama-index-core \
  llama-index-readers-file \
  llama-index-llms-openai-like \
  llama-index-embeddings-openai-like
```

## 基本設定

```python theme={null}
from llama_index.core import Settings
from llama_index.llms.openai_like import OpenAILike
from llama_index.embeddings.openai_like import OpenAILikeEmbedding

llm = OpenAILike(
    model="gpt-5.4",
    api_base="https://api.tokenlab.sh/v1",
    api_key="sk-your-tokenlab-key",
    is_chat_model=True,
)

embed_model = OpenAILikeEmbedding(
    model_name="text-embedding-3-small",
    api_base="https://api.tokenlab.sh/v1",
    api_key="sk-your-tokenlab-key",
)

Settings.llm = llm
Settings.embed_model = embed_model
```

## 基本的な使用方法

```python theme={null}
response = llm.complete("Explain TokenLab in one sentence.")
print(response.text)
```

## 最小限の OpenAILike LLM

```python theme={null}
from llama_index.llms.openai_like import OpenAILike

llm = OpenAILike(
    model="claude-sonnet-5",
    api_base="https://api.tokenlab.sh/v1",
    api_key="sk-your-tokenlab-key",
    context_window=200000,
    is_chat_model=True,
    is_function_calling_model=True,
)
```

## チャット

```python theme={null}
from llama_index.core.llms import ChatMessage

messages = [
    ChatMessage(role="system", content="You are a helpful assistant."),
    ChatMessage(role="user", content="What is the capital of France?")
]

response = llm.chat(messages)
print(response.message.content)
```

## ストリーミング

```python theme={null}
for chunk in llm.stream_complete("Write a short poem about AI."):
    print(chunk.delta, end="", flush=True)
```

## エンベディング

```python theme={null}
vector = embed_model.get_text_embedding("Hello, world!")
print(vector[:5])
```

## ドキュメントを使用したRAG

```python theme={null}
from llama_index.core import SimpleDirectoryReader, VectorStoreIndex

documents = SimpleDirectoryReader("./data").load_data()
index = VectorStoreIndex.from_documents(documents)

query_engine = index.as_query_engine()
response = query_engine.query("What is in my documents?")
print(response)
```

## チャットエンジン

```python theme={null}
chat_engine = index.as_chat_engine(chat_mode="condense_question")

response = chat_engine.chat("What is TokenLab?")
print(response)

response = chat_engine.chat("How many models does it support?")
print(response)
```

## 非同期（Async）の使用方法

```python theme={null}
import asyncio

async def main():
    response = await llm.acomplete("Hello!")
    print(response.text)

asyncio.run(main())
```

## ベストプラクティス

<AccordionGroup>
  <Accordion title="TokenLabにはOpenAILikeを使用する">
    TokenLabおよびその他のサードパーティ製OpenAI互換ゲートウェイには、`llama_index.llms.openai_like.OpenAILike` および `llama_index.embeddings.openai_like.OpenAILikeEmbedding` を優先的に使用してください。
  </Accordion>

  <Accordion title="api_baseを明示的に設定する">
    古いOpenAIの環境変数名に依存するのではなく、コード内で直接 `api_base="https://api.tokenlab.sh/v1"` を渡してください。
  </Accordion>

  <Accordion title="モデルの役割を分離する">
    合成（synthesis）にはチャット/推論モデルを使用し、検索（retrieval）には `text-embedding-3-small` または `text-embedding-3-large` を使用してください。
  </Accordion>
</AccordionGroup>
