Skip to main content


Build resilient LLM workflows with Flyte 2 for orchestration & Weave for tracing
Building a local LLM pipeline using Flyte 2 for orchestration and W&B Weave for observability.
Last updated: May 6, 2026
Moving an LLM application from a local notebook to a reliable production environment is often where the real engineering begins. You quickly realize that standard scripts aren't enough: one API timeout crashes your entire ingestion, a lack of GPU orchestration wastes expensive resources, and when a model returns a poor response, you have no easy way to trace why.
In this guide, we’ll build a robust LLM system using Flyte 2 for resource-aware orchestration and W&B Weave for deep observability. By the end, you’ll learn how to build a RAG pipeline that is not only resilient and cached but also fully transparent, allowing you to inspect every prompt, latency, and model call in real-time.
Table of contents
Why Flyte for orchestration?Tutorial: Integrating Flyte with W&B WeaveInitial setupLoading your local LLM modelUse Case 1: Retrieval Augmented GenerationUse Case 2: Caching with Flyte.CacheConclusion
Why Flyte for orchestration?
When you build an ML or LLM pipeline, you quickly run into the same set of problems: a step crashes halfway through, and you rerun everything from scratch, two tasks need different GPU configurations that your script has no way to express, and the code that worked on your laptop silently breaks in production because the environment is different.
Flyte is an open-source workflow orchestrator that treats these as first-class problems. Each step in your pipeline is a typed, containerized task with its own declared resources (CPU, memory, GPU), and Flyte handles scheduling, retries, caching, and parallelism on top of Kubernetes without you writing any of that plumbing yourself. The reason it matters specifically for LLM work is that general-purpose orchestrators like Airflow were built for data pipelines, not for workloads where a single task might call a model ten times in a loop, need a GPU, and should checkpoint progress so a failure midway does not throw away everything already computed.
Tutorial: Integrating Flyte with W&B Weave
Flyte shows you what ran and in what order. W&B Weave shows you what the model actually did inside each step. When you decorate a function with @weave.op(), every call to it gets logged to Weights & Biases with its inputs, outputs, and latency, i.e., a nested trace tree that you can inspect per-run.
In practice, teams use Flyte to run pipelines reliably and Weave to inspect prompts, responses, and timing for each model call during debugging or evaluation. This is especially useful when a run finishes but quality is off, because you can trace exactly which step and which call produced the issue. So the integration is less about adding complexity and more about making LLM pipelines easier to run, inspect, and iterate within an orchestrated workflow.
Initial setup
First off, let's start with the installation.
pip install 'flyte[tui]' weave "qdrant-client[fastembed]" ollama python-dotenv
W&B Weave is an observability and evaluation platform that helps you track, evaluate, and improve your LLM application. To get started, you import Weave and initialize it with your project name. Then you add the @weave.op() decorator above any function you want to track. It captures inputs, outputs, costs, latency, and evaluation metrics without any manual setup. After running your code, you can open the Weave dashboard to view a full trace of what happened, making it much easier to debug problems and understand how your model behaves over time.
To start using the Weave library, create a Weights & Biases account and an API key at User Settings. The API key allows you to authenticate to your W&B account and start sending data to it.
- Ollama for the LLM inference
- Qdrant as a vector search engine for RAG example
- FastEmbed to convert the text into vectors in onnx runtime for the open weight embedding model.
.env:
WANDB_API_KEY=<replace-with-your-api-key>
Understanding Flyte Task Environment
Once you have initialized Weave with your project name, prepare a Task Environment for Flyte. What does this Task Environment do here?
Flyte Task Environment defines an execution environment for a set of tasks. Task configuration in Flyte has three levels (most general to most specific):
- TaskEnvironment: sets defaults for all tasks in the environment
- @env.task decorator: overrides per-task settings (we will use quite often in this article)
- task.override(): overrides at invocation time
My file name is: llm_inference.py
import weaveimport ollamaimport flytefrom dotenv import load_dotenvload_dotenv()weave.init("flyte-llm-tutorial")llm_env = flyte.TaskEnvironment(name="llm-inference")
TaskEnvironment is an important component. If you have multi-GPU support, refer to the documentation for more details: TaskEnvironment Flyte.
Loading your local LLM model
To run inference with the LLM model locally, we need to install Ollama and serve the open weights model on your own edge device.
curl -fsSL https://ollama.com/install.sh | sh
After downloading Ollama, you can choose any model from the library of supported models. In this tutorial, we will use Google Gemma 4, which is available in e2b, e4B, 26B, and 31B variants.
ollama run gemma4:e4b
Use Case 1: Retrieval Augmented Generation
If you are new to RAG, we have already covered multiple production-grade articles on Retrieval Augmented Generation. You can read them here: Building a production-ready Financial Agentic RAG pipeline.
To build RAG, we need 2 separate workflows:
- Document processing, i.e., Indexing your data into the Vector Database
- Answer generation using an LLM model and the right context for the given user query.
We will use the Flyte task environment in both implementations.
Part 1: Document ingestion
You can download the actual Financial Access Survey report from 2025 on Fintech, a Catalyst for Financial Services Access, Innovation, and Growth. Link, or:
!wget https://data.imf.org/-/media/iData/External-Storage/Documents/7FC05452C6C743D2BFB6188D2E248A38/en/2025-FAS-Annual-Report.pdf -O annual_report.pdf
After the data is downloaded, we need to extract the raw table, text and then chunk the data to ingest in the vector database.
ingest.py:
import uuidimport flyteimport pypdfium2 as pdfiumfrom fastembed import TextEmbeddingfrom qdrant_client import QdrantClient, modelsPDF_PATH = "annual_report.pdf"COLLECTION_NAME = "annual_report"DENSE_MODEL_NAME = "jinaai/jina-embeddings-v2-small-en"QDRANT_PATH = "db"
There are numerous PDF loaders available. However, one research paper stands out: "A Comparative Study of PDF Parsing Tools Across Diverse Document Categories." This study shows that for financial documents, PyPDFium2 yields better results, so we will use this loader for extraction.
As an alternative, you are free to use Unstructured.IO, remember this is offline document processing. This happens only once, after the data is indexed, you can directly inference and get the relevant information.
def extract_text(pdf_path: str) -> list[str]:doc = pdfium.PdfDocument(pdf_path)pages: list[str] = []for i in range(len(doc)):page = doc.get_page(i)text_page = page.get_textpage()pages.append(text_page.get_text_range())text_page.close()page.close()doc.close()return pagesdef chunk_text(pages: list[str], chunk_size: int = 1500) -> list[dict]:chunks: list[dict] = []for page_num, page_text in enumerate(pages, start=1):for i in range(0, len(page_text), chunk_size):content = page_text[i : i + chunk_size].strip()if content:chunks.append({"content": content, "page_number": page_num})return chunks
Now that parsing and chunking are complete, the next step is to index the document. For this, we initialize the embedding model, convert the raw data into vectors, and store them in the vector database.
Additionally, metadata is stored in the payload so it can later be used to filter user queries across multiple sources. In our case, the metadata includes the source and page_number of the PDF data.
ingest_env = flyte.TaskEnvironment(name="rag-ingest")@ingest_env.taskasync def ingest_pdf() -> int:raw_text = extract_text(PDF_PATH)chunks = chunk_text(raw_text)embedder = TextEmbedding(model_name=DENSE_MODEL_NAME)vectors = [v.tolist() for v in embedder.embed([c["content"] for c in chunks])]client = QdrantClient(path=QDRANT_PATH)if not client.collection_exists(COLLECTION_NAME):client.create_collection(collection_name=COLLECTION_NAME,vectors_config={"dense": models.VectorParams(size=len(vectors[0]), distance=models.Distance.COSINE)})points = [models.PointStruct(id=str(uuid.uuid4()),vector={"dense": vector},payload={"content": chunk["content"], "page_number": chunk["page_number"]},)for chunk, vector in zip(chunks, vectors)]client.upsert(collection_name=COLLECTION_NAME, points=points)return len(points)if __name__ == "__main__":run = flyte.run(ingest_pdf)run.wait()print(f"Indexed points: {run.outputs()[0]}")
Alright, the data is indexed and saved in the Vector database. We can now test this by using it in the Answer generation for the RAG pipeline.
NOTE: The above code is written inside ingest.py and now we create a new file and run app.py where actual logic of answer generation is written.
Part 2: Answer generation for your RAG pipeline
Part 1 is completed with the retrieved context logic in place. Part 2 picks up from this context and builds the core of an intelligent retrieval and answer generation.
app.py
import flytefrom fastembed import TextEmbeddingfrom qdrant_client import QdrantClientMODEL_NAME = "gemma4:e4b"COLLECTION_NAME = "annual_report"DENSE_MODEL_NAME = "jinaai/jina-embeddings-v2-small-en"QDRANT_PATH = "db"
For every request, W&B Weave captures traces of inputs, intermediate calls, outputs, latency, and, if provided, optional feedback. For answer generation, we need to trace the LLM inference Ollama using Weave and then build a RAG workflow within the Flyte Task Environment.
class GemmaModel(weave.Model):"""Wraps Ollama/Gemma as a versioned, observable Weave model."""model_name: str = "gemma4:e4b"temperature: float = 0.7@weave.op()def predict(self, prompt: str) -> str:response = ollama.chat(model=self.model_name,messages=[{"role": "user", "content": prompt}],options={"temperature": self.temperature},)return response["message"]["content"]
To build the rag_query logic, the input is the user query, which is first converted into a vector using TextEmbedding. Then, using Qdrant client query_points, we retrieve the top k relevant documents, in this case, limit=3. These documents are then passed to the GemmaModel for LLM inference with 2 input variables: the user query and the retrieved context.
rag_env = flyte.TaskEnvironment(name="rag-generation")@rag_env.taskasync def rag_query(query: str) -> dict:client = QdrantClient(path=QDRANT_PATH)if not client.collection_exists(COLLECTION_NAME):raise RuntimeError("Collection missing. Run: python ingest.py")embedder = TextEmbedding(model_name=DENSE_MODEL_NAME)query_vector = list(embedder.embed([query]))[0].tolist()hits = client.query_points(collection_name=COLLECTION_NAME,query=query_vector,using="dense",with_payload=True,limit=3,).pointscontext = "\n\n".join(hit.payload.get("content", "") for hit in hits if hit.payload)prompt = ("Answer only from this context. If not enough info, say 'insufficient context'.\n\n"f"Context:\n{context}\n\n"f"Question: {query}\n""Answer:")answer = GemmaModel(model_name=MODEL_NAME).predict(prompt)return {"query": query, "context": context, "answer": answer}
Finally, we have completed with the RAG pipeline, we can execute the rag_query logic within the Flyte environment.
if __name__ == "__main__":query = "what is the data about"run = flyte.run(rag_query, query=query)run.wait()print(run.outputs()[0]["answer"])

Use Case 2: Caching with Flyte.Cache
Flyte 2 provides a flyte.Cache object for fine-grained cache control. The cache key is composed of: task inputs + task name + interface hash + cache version. When all matches, the task body is skipped and the stored output returned immediately.
Reducing latency while using an open-source LLM from Ollama via caching is a pretty handy technique. Here is why this matters for LLM pipelines:
- No cache: prompt → [Gemma inference ~8s] → answer
- Cache hit: prompt → [cache lookup ~0.01s] → same answer
With Flyte cache enabled, W&B Weave still captures each request’s question, response, and latency at the outer request trace, so cache-hit runs clearly show reduced latency; only the inner in-task model trace is skipped because Flyte does not execute the task body on a cache hit.
Documentation: Caching in Flyte.
weave.init("flyte-llm-tutorial")llm_env = flyte.TaskEnvironment(name="llm-cache-inference")class GemmaModel(weave.Model):model_name: str = "gemma4:e4b"temperature: float = 0.0@weave.op()def predict(self, prompt: str) -> str:response = ollama.chat(model=self.model_name,messages=[{"role": "user", "content": prompt}],options={"temperature": self.temperature},)return response["message"]["content"]@llm_env.task(cache=flyte.Cache(behavior="auto"))async def cached_inference(prompt: str, model_name: str = "gemma4:e4b") -> str:model = GemmaModel(model_name=model_name, temperature=0.0)return str(await asyncio.to_thread(model.predict, prompt))@weave.op()def traced_cached_request(prompt: str, model_name: str = "gemma4:e4b") -> str:run = flyte.run(cached_inference, prompt=prompt, model_name=model_name)run.wait()return str(run.outputs()[0])def run_once(prompt: str, model_name: str = "gemma4:e4b") -> tuple[str, float]:started = time.perf_counter()output = traced_cached_request(prompt=prompt, model_name=model_name)latency_s = time.perf_counter() - startedreturn output, latency_s
Do notice that when we run the same prompt again, the latency is cached, and the response is processed in a fraction of a second. It is also traced in the W&B Weave latency column.
if __name__ == "__main__":prompt_a = "Explain RAG in one simple sentence."prompt_b = "Explain fine-tuning in one simple sentence."print("Input 1 - first run (expected cache miss)")out1_miss, t1_miss = run_once(prompt_a)print(f"Latency: {t1_miss:.2f}s")print(f"Output: {out1_miss}\n")print("Input 1 - second run (expected cache hit)")out1_hit, t1_hit = run_once(prompt_a)print(f"Latency: {t1_hit:.3f}s")print(f"Output: {out1_hit}\n")print("Input 2 - first run (new key, expected cache miss)")out2_miss, t2_miss = run_once(prompt_b)print(f"Latency: {t2_miss:.2f}s")print(f"Output: {out2_miss}\n")print("Summary")print(f"Input 1 speedup: {t1_miss / max(t1_hit, 1e-6):.1f}x faster on cache hit")print(f"Input 2 miss latency: {t2_miss:.2f}s")
In our Flyte + W&B Weave setup, every request is still traced with the full question, response, and latency, and cache hits are visibly faster in Weave (for example, ~34.45s on first run vs ~0.024s on cache hit.


Conclusion
Building LLM applications is easy; scaling them reliably is the hard part. By integrating Flyte 2 with W&B Weave, you move beyond brittle scripts into a world of self-healing observability.
Flyte provides the skeleton, ensuring that your tasks have the right GPUs, recover from failures, and never waste compute on steps that have already been cached. Weave provides the vision, letting you peer inside those tasks to see exactly why a model hallucinated or where latency is creeping in. Together, they turn your RAG pipeline from a black box into a transparent, production-ready system that is as easy to debug as it is to run.