LlamaIndex
Connect LlamaIndex Python to Inference.net with OpenAILike for RAG pipelines, AgentWorkflow tool calling, streaming, and prompt caching.
Last updated
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, generate a project key in API keys, install the LlamaIndex packages, and export your key:
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:
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)Stream responses
OpenAILike streams Chat Completions directly from https://api.inference.net/v1:
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):
pip install llama-index-embeddings-huggingfaceimport 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):
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/1Mcached input vs.$0.08/1Mfresh input). Keep your system prompt, tool definitions, and static retrieved context at the start of the message list, and do not passprompt_cache_key.moonshotai/kimi-k3.1-pro: Uses automatic implicit prefix caching ($0.198/1Mcached input vs.$1.80/1Mfresh input).glm-5.3andglm-5.3-flash: Pass a stableprompt_cache_keythroughadditional_kwargs={"extra_body": {"prompt_cache_key": "rag-prod-v1"}}onOpenAILiketo maintain cache affinity.- Usage tagging: Pass
default_headersto group LlamaIndex traffic in Usage:
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.
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 |
glm-5.3 | 1,048,576 | 943,718 | $0.084 / $0.079 / $3.00 | True | GLM-5.3 |
glm-5.3-flash | 1,048,576 | 262,144 | $0.10 / $0.03 / $0.35 | True | 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 |
inference-net/schematron-v2-small | 128,000 | 4,096 | $0.05 / $0.05 / $0.23 | False | Schematron V2 Small |
Inference.net-hosted models listed above support default Zero Data Retention and US-only routing at https://us.api.inference.net/v1.
Troubleshooting
ValueError: Unknown model: Switch fromllama_index.llms.openai.OpenAItollama_index.llms.openai_like.OpenAILike.- Agent ignores tools: Pass
is_chat_model=Trueandis_function_calling_model=TruetoOpenAILike, and select a model withsupports_tools: true. 400 Bad Requeston DeepSeek withprompt_cache_key: Omitprompt_cache_keywhen callingdeepseek-v4.1-flash-1017; it caches prefixes implicitly.404 Not Foundor HTML response: Confirmapi_base="https://api.inference.net/v1"includes/v1and targetsapi.inference.net, notinference.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.
Start building
One OpenAI-compatible API key for fast open-weight models.