Two Settings: putting LlamaIndex behind a gateway

2026-12-01来源 dev.toEnglish

LlamaIndex keeps every model it uses in one place: the global Settings object. Settings.llm generates, Settings.embed_model embeds. That single design choice decides how a gateway integrates — not through a plugin or a subclass, but through the two assignments the framework already asks you to make.

The two assignments

pip install llama-index-core llama-index-llms-openai llama-index-embeddings-openai nrouter-sdk 
import os from llama_index.core import Settings from llama_index.llms.openai import OpenAI from llama_index.embeddings.openai import OpenAIEmbedding Settings.llm = OpenAI( model="claude-sonnet-4-5-20250929", api_key=os.environ["NROUTER_API_KEY"], api_base="https://api.nrouter.ai/v1", timeout=60.0, max_retries=2, additional_kwargs={"nrouter_cache": True}, ) Settings.embed_model = OpenAIEmbedding( model_name="text-embedding-3-small", api_key=os.environ["NROUTER_API_KEY"], api_base="https://api.nrouter.ai/v1", ) 

Generation and embeddings now share one key and one base URL.

What doesn't change

Everything downstream. VectorStoreIndex.from_documents(...) builds the index the usual way, index.as_query_engine(streaming=True) answers the usual way, and response.response_gen streams the usual way. The gateway speaks through the OpenAI client classes LlamaIndex already uses, so retrieval code, node parsers and response handling are untouched.

What the gateway carries

  • Fallbacks in additional_kwargs. nrouter_fallbacks names the chain for a call; or use nrouter/auto with nrouter_optimize set to quality, balanced or cost (plus nrouter_cost_band under cost). Retry logic leaves the query path.
  • Exact-match caching. "nrouter_cache": True lets repeat queries be answered from edge cache. RAG systems get asked the same questions constantly — this is the workload caching was invented for.
  • One record per response. Generation and embedding calls return x-nr-request-id, x-nr-model, x-nr-cost-status and x-nr-request-cost. Two bills become one header set.
  • Errors you already catch. A guardrail block is openai.BadRequestError; a rate limit is openai.RateLimitError. Guardrails run server-side in the request path, so a blocked call stops before generation, and it arrives as an exception type your handlers already know.

The framework keeps its shape. The two settings carry the operations.

Full walkthrough: LlamaIndex guide

原文:https://www.a8q9.cn/en/article/two-settings-putting-llamaindex-behind-a-gateway-b64ad9.html

相关文章