# LlamaIndex

Source: https://aiand-docs-staging.pages.dev/ja/integrations/llamaindex/

LlamaIndex は `OpenAILike` LLM を介して ai& と接続できます — OpenAI のワイヤ形式に対応し、ベース URL のみカスタマイズします。

## セットアップ

```bash
pip install llama-index llama-index-llms-openai-like
```

```python
from llama_index.llms.openai_like import OpenAILike

llm = OpenAILike(
    model="google/gemma-4-31b-it",
    api_base="https://api.aiand.com/v1",
    api_key="sk-your-api-key",
    is_chat_model=True,
)

print(llm.complete("Hello").text)
```

## ドキュメントのインデックス化と検索

```python
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader, Settings

Settings.llm = llm
# ai& は埋め込みエンドポイントを提供しないため、埋め込みは別途用意:
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
Settings.embed_model = HuggingFaceEmbedding(model_name="BAAI/bge-small-en-v1.5")

docs = SimpleDirectoryReader("./data").load_data()
index = VectorStoreIndex.from_documents(docs)
query_engine = index.as_query_engine()

print(query_engine.query("What is this corpus about?"))
```

## ツール付きエージェント

```python
from llama_index.core.agent.workflow import FunctionAgent
from llama_index.core.tools import FunctionTool

def get_weather(city: str) -> str:
    """Get current weather for a city."""
    return f"Sunny in {city}, 22°C"

agent = FunctionAgent(
    tools=[FunctionTool.from_defaults(fn=get_weather)],
    llm=llm,
)

print(await agent.run("What's the weather in Tokyo?"))
```

<Aside type="note">
  ai& は現在 embeddings エンドポイントを提供していません。LlamaIndex と組み合わせる際はローカル埋め込みモデル (`HuggingFaceEmbedding`) か別の embeddings プロバイダを使用してください。
</Aside>
