Two Settings: putting LlamaIndex behind a gateway
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…
LlamaIndex maintains all utilized models within a central Settings object. Settings.llm handles model generation, while Settings.embed_model manages embeddings. This singular design decision dictates how a gateway integrates, rather than through a plugin or subclass, but rather by completing two assignments the framework requests.
These assignments involve installing specific packages, importing necessary modules, and assigning the OpenAI and OpenAIEmbedding classes to Settings.llm and Settings.embed_model, respectively. The API key for NRouter is obtained from environment variables, along with the base URL and timeout settings. Notably, generation and embeddings now share the same key and base URL.
The interface remains unchanged for all downstream components. VectorStoreIndex.from_documents(...) constructs the index conventionally, index.as_query_engine(streaming=True) responds in the usual manner, and response.response_gen streams as expected. The gateway communicates using the OpenAI client classes LlamaIndex already employs, leaving retrieval code, node parsers, and response handling untouched.
What the gateway handles includes fallbacks specified in additional_kwargs.nrouter_fallbacks, or the default nrouter/auto with nrouter_optimize set to quality, balanced, or cost (plus nrouter_cost_band under cost). Retry logic remains separate from the query path. Exact-match caching is enabled via "nrouter_cache": True, enabling repeat queries to be answered from the edge cache.
RAG systems will receive the same questions repeatedly, making caching essential for workload efficiency. Each response bears one record with specific headers: x-nr-request-id, x-nr-model, x-nr-cost-status, and x-nr-request-cost. Generation and embedding calls now return these headers, consolidating two bills into a single header set.
Errors are handled as before, with openai.BadRequestError and openai.RateLimitError as guardrails, running server-side in the request path to prevent calls from progressing beyond generation. The framework maintains its structure, with the two settings driving the operations. The complete walkthrough can be found in the LlamaIndex guide.
Rewritten by urgent.news; may contain errors — check the original.
Source: dev.to