# LlamaIndex (https://inference.net/docs/integrations/llama-index)

Connect LlamaIndex in Python to Inference.net using `OpenAILike` from `llama-index-llms-openai-like` with `api_base="https://api.inference.net/v1"` and your `INFERENCE_API_KEY`. `OpenAILike` skips OpenAI's hardcoded model-name allowlist so you can run `deepseek-v4.1-flash-1017`, `glm-5.3`, and `moonshotai/kimi-k3.1-pro` across RAG query engines, streaming completions, and `AgentWorkflow` tool-calling loops.

## Quick start

Create an account at [/register](/register/?model=deepseek-v4-1-flash-1017), generate a project key in [API keys](/dashboard/api-keys/), install the LlamaIndex packages, and export your key:

```bash
pip install llama-index-core llama-index-llms-openai-like
export INFERENCE_API_KEY="inf_sk_..."
```

Initialize `OpenAILike` with `is_chat_model=True`, `is_function_calling_model=True`, and the model's live context window:

```python
import os
from llama_index.core.llms import ChatMessage
from llama_index.llms.openai_like import OpenAILike

llm = OpenAILike(
    model="deepseek-v4.1-flash-1017",
    api_base="https://api.inference.net/v1",
    api_key=os.environ["INFERENCE_API_KEY"],
    context_window=1_040_000,
    max_tokens=4096,
    is_chat_model=True,
    is_function_calling_model=True,
)

response = llm.chat(
    [
        ChatMessage(role="system", content="Answer concisely."),
        ChatMessage(role="user", content="Explain prefix caching in two sentences."),
    ]
)
print(response.message.content)
```

<Callout title="Use OpenAILike instead of llama_index.llms.openai.OpenAI" tone="info">

LlamaIndex's `OpenAI` class validates model names against OpenAI's built-in catalog and raises `ValueError: Unknown model` for open-weight IDs such as `deepseek-v4.1-flash-1017`, `glm-5.3`, or `moonshotai/kimi-k3.1-pro`. Use `OpenAILike` so any model from `GET https://api.inference.net/v1/models` works with the right `context_window` and tool-calling flags.

</Callout>

## Stream responses

`OpenAILike` streams Chat Completions directly from `https://api.inference.net/v1`:

```python
import os
from llama_index.core.llms import ChatMessage
from llama_index.llms.openai_like import OpenAILike

llm = OpenAILike(
    model="glm-5.3",
    api_base="https://api.inference.net/v1",
    api_key=os.environ["INFERENCE_API_KEY"],
    context_window=1_048_576,
    max_tokens=4096,
    is_chat_model=True,
    is_function_calling_model=True,
)

for chunk in llm.stream_chat(
    [ChatMessage(role="user", content="List three steps to lower RAG time to first token.")]
):
    print(chunk.delta, end="", flush=True)
```

## RAG query engine with `Settings.llm`

Assign `OpenAILike` to `Settings.llm` and configure `Settings.embed_model` explicitly before building a `VectorStoreIndex`. Without `Settings.embed_model`, LlamaIndex attempts to import `llama-index-embeddings-openai` and call OpenAI's default embeddings endpoint. The example below pairs Inference.net generation with a local Hugging Face embedding model so only `INFERENCE_API_KEY` is required (if your team has an embedding deployment enabled on Inference.net, you can point `OpenAIEmbedding` at `https://api.inference.net/v1` instead; see [Embeddings](/docs/api/embeddings/)):

```bash
pip install llama-index-embeddings-huggingface
```

```python
import os
from llama_index.core import Document, Settings, VectorStoreIndex
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
from llama_index.llms.openai_like import OpenAILike

Settings.llm = OpenAILike(
    model="deepseek-v4.1-flash-1017",
    api_base="https://api.inference.net/v1",
    api_key=os.environ["INFERENCE_API_KEY"],
    context_window=1_040_000,
    max_tokens=2048,
    is_chat_model=True,
    is_function_calling_model=True,
)
Settings.embed_model = HuggingFaceEmbedding(model_name="BAAI/bge-small-en-v1.5")

documents = [
    Document(
        text="Inference.net exposes an OpenAI-compatible API at https://api.inference.net/v1 and a US-only host at https://us.api.inference.net/v1."
    ),
    Document(
        text="DeepSeek V4.1 Flash (deepseek-v4.1-flash-1017) supports a 1,040,000 token context window and automatic implicit prefix caching."
    ),
]

index = VectorStoreIndex.from_documents(documents)
query_engine = index.as_query_engine(streaming=True)

streaming_response = query_engine.query("Which base URL enforces US-only routing?")
streaming_response.print_response_stream()
```

## Tool calling with `AgentWorkflow`

Pair `AgentWorkflow` with any Inference.net model that reports `supports_tools: true` in `GET https://api.inference.net/v1/models` (`deepseek-v4.1-flash-1017`, `glm-5.3`, `glm-5.3-flash`, or `moonshotai/kimi-k3.1-pro`):

```python
import asyncio
import os
from llama_index.core.agent.workflow import AgentWorkflow
from llama_index.llms.openai_like import OpenAILike


def lookup_deployment_status(service: str) -> str:
    """Return the current status of a production service."""
    statuses = {"api-gateway": "healthy", "indexer": "rebuilding"}
    return statuses.get(service, "unknown")


llm = OpenAILike(
    model="deepseek-v4.1-flash-1017",
    api_base="https://api.inference.net/v1",
    api_key=os.environ["INFERENCE_API_KEY"],
    context_window=1_040_000,
    max_tokens=4096,
    is_chat_model=True,
    is_function_calling_model=True,
)

agent = AgentWorkflow.from_tools_or_functions(
    [lookup_deployment_status],
    llm=llm,
    system_prompt="You are a concise infrastructure assistant. Use tools to check service health.",
)


async def main() -> None:
    response = await agent.run(user_msg="Is the indexer service healthy?")
    print(response)


asyncio.run(main())
```

## Prompt caching and request headers

RAG pipelines and multi-step agents repeatedly send the same system instructions, tool schemas, and shared document prefixes. Match caching parameters to your model family:

- **`deepseek-v4.1-flash-1017`:** Uses automatic implicit prefix caching (`$0.007/1M` cached input vs. `$0.08/1M` fresh input). Keep your system prompt, tool definitions, and static retrieved context at the start of the message list, and do **not** pass `prompt_cache_key`.
- **`moonshotai/kimi-k3.1-pro`:** Uses automatic implicit prefix caching (`$0.198/1M` cached input vs. `$1.80/1M` fresh input).
- **`glm-5.3` and `glm-5.3-flash`:** Pass a stable `prompt_cache_key` through `additional_kwargs={"extra_body": {"prompt_cache_key": "rag-prod-v1"}}` on `OpenAILike` to maintain cache affinity.
- **Usage tagging:** Pass `default_headers` to group LlamaIndex traffic in [Usage](/dashboard/usage/):

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

glm_llm = OpenAILike(
    model="glm-5.3",
    api_base="https://api.inference.net/v1",
    api_key=os.environ["INFERENCE_API_KEY"],
    context_window=1_048_576,
    is_chat_model=True,
    is_function_calling_model=True,
    default_headers={
        "x-inference-task-id": "rag-qa",
        "x-inference-environment": "production",
    },
    additional_kwargs={
        "extra_body": {"prompt_cache_key": "rag-prod-v1"},
    },
)
```

Estimate prompt-cache savings for your RAG chunk sizes in the [Prompt cache calculator](/tools/prompt-cache-calculator/).

## Verified models for LlamaIndex

All model IDs, limits, and per-1M-token rates below are verified against `GET https://api.inference.net/v1/models` (**2026-12-06**):

| Model ID | `context_window` | Max output | Input / cached / output (per 1M) | `is_function_calling_model` | Model page |
| --- | ---: | ---: | --- | --- | --- |
| `deepseek-v4.1-flash-1017` | 1,040,000 | 393,216 | `$0.08` / `$0.007` / `$0.635` | `True` | [DeepSeek V4.1 Flash](/models/deepseek-v4-1-flash-1017/) |
| `glm-5.3` | 1,048,576 | 943,718 | `$0.084` / `$0.079` / `$3.00` | `True` | [GLM-5.3](/models/glm-5-3/) |
| `glm-5.3-flash` | 1,048,576 | 262,144 | `$0.10` / `$0.03` / `$0.35` | `True` | [GLM-5.3 Flash](/models/glm-5-3-flash/) |
| `moonshotai/kimi-k3.1-pro` | 1,048,576 | 1,048,576 | `$1.80` / `$0.198` / `$9.00` | `True` | [Kimi K3.1 Pro](/models/kimi-k3-1-pro/) |
| `inference-net/schematron-v2-small` | 128,000 | 4,096 | `$0.05` / `$0.05` / `$0.23` | `False` | [Schematron V2 Small](/models/inference-net-schematron-v2-small/) |

Inference.net-hosted models listed above support default [Zero Data Retention](/docs/data-retention/) and US-only routing at `https://us.api.inference.net/v1`.

## Troubleshooting

- **`ValueError: Unknown model`:** Switch from `llama_index.llms.openai.OpenAI` to `llama_index.llms.openai_like.OpenAILike`.
- **Agent ignores tools:** Pass `is_chat_model=True` and `is_function_calling_model=True` to `OpenAILike`, and select a model with `supports_tools: true`.
- **`400 Bad Request` on DeepSeek with `prompt_cache_key`:** Omit `prompt_cache_key` when calling `deepseek-v4.1-flash-1017`; it caches prefixes implicitly.
- **`404 Not Found` or HTML response:** Confirm `api_base="https://api.inference.net/v1"` includes `/v1` and targets `api.inference.net`, not `inference.net`.
- **Model not found:** Keep exact owner prefixes from `GET https://api.inference.net/v1/models` (for example, `moonshotai/kimi-k3.1-pro`).

Explore all supported editors, workflow builders, gateways, and SDKs in the [Integrations hub](/docs/integrations/).