4: Assembling and Deploying Applications

    Code a chain using a pyfunc model with pre- and post-processing

    A pyfunc model is the MLflow flavor that wraps arbitrary Python around a deterministic predict(context, model_input) method. Other flavors such as mlflow.langchain and mlflow.openai are convenience wrappers that ultimately log a pyfunc under the hood.

    The reason to author a pyfunc directly is when the chain needs anything the convenience flavors will not give you: input normalization, custom guardrails before the LLM call, response repair after the LLM call, structured output coercion, or a mix of pre-trained embedding inference with rule-based post-processing. If the chain is a pure LangChain Runnable graph with no custom logic, use mlflow.langchain.log_model; the moment a callable Python step appears in either side of the chain, drop down to mlflow.pyfunc.PythonModel.

    The pyfunc contract is small but strict. A class inherits from mlflow.pyfunc.PythonModel, optionally implements load_context(self, context) to materialize heavy artifacts once at startup, and implements predict(self, context, model_input, params=None).

    The model_input is a pandas DataFrame, dictionary, or list of dictionaries that matches the logged model signature, and predict returns a pandas DataFrame, dictionary, or list of the corresponding output schema. The optional params argument carries inference-time hyperparameters such as temperature or top_k that should not be baked into the model artifacts.

    Pre-processing hooks

    Pre-processing belongs inside the pyfunc when it must run on every inference, in the same Python process, with the same library versions as the LLM call. Typical pre-processing duties: trimming whitespace, lowercasing email addresses for PII tokenization, expanding chat-history dictionaries into prompt strings, redacting documents through a regex denylist, and rerouting empty inputs to a default response so the LLM never sees them.

    Pre-processing also enforces input-side guardrails by checking the prompt against an injection scanner before any LLM token is spent.

    Post-processing hooks

    How it works

    Post-processing is the mirror image: it runs after the LLM returns and before the response reaches the caller. Use it to:

    • validate JSON against a Pydantic schema
    • retry-once on parse failure
    • attach the retrieved citations array to the answer
    • strip chain-of-thought scratchpad
    • score the response against a toxicity model
    • convert internal entity IDs back into user-facing identifiers

    Post-processing is also where you implement length parity for chat history compaction, summarizing turns older than the recency window.

    A canonical pyfunc chain

    The example below logs a RAG chain that retrieves from Mosaic AI Vector Search, builds a prompt, calls a Foundation Model API endpoint, and validates the response.

    import mlflow
    import pandas as pd
    from pydantic import BaseModel, Field, ValidationError
    
    class Answer(BaseModel):
     answer: str
     citations: list[str] = Field(default_factory=list)
     confidence: float
    
    class RagChain(mlflow.pyfunc.PythonModel):
     def load_context(self, context):
     from databricks.vector_search.client import VectorSearchClient
     from databricks_langchain import ChatDatabricks
     self.vsc = VectorSearchClient(disable_notice=True)
     self.index = self.vsc.get_index(
     endpoint_name="vs_prod_endpoint",
     index_name="main.genai_prod.policy_chunks_idx",
     )
     self.llm = ChatDatabricks(
     endpoint="databricks-meta-llama-3-3-70b-instruct",
     temperature=0.0,
     max_tokens=512,
     )
    
     def _preprocess(self, row):
     question = (row.get("question") or "").strip()
     if len(question) < 3:
     return None
     return question[:2000]
    
     def _retrieve(self, question):
     hits = self.index.similarity_search(
     query_text=question,
     columns=["doc_id", "chunk_text", "source_url"],
     num_results=4,
     )
     rows = hits.get("result", {}).get("data_array", [])
     return [
     {"doc_id": r[0], "chunk_text": r[1], "source_url": r[2], "score": r[3]}
     for r in rows
     ]
    
     def _build_prompt(self, question, hits):
     ctx = "\n\n".join(f"[{h['doc_id']}] {h['chunk_text']}" for h in hits)
     return [
     {"role": "system", "content": "Answer using only the provided context. Cite doc_ids."},
     {"role": "user", "content": f"Question: {question}\n\nContext:\n{ctx}"},
     ]
    
     def _postprocess(self, raw, hits):
     try:
     parsed = Answer.model_validate_json(raw)
     except ValidationError:
     return Answer(
     answer="The system could not produce a structured answer.",
     citations=[h["doc_id"] for h in hits[:1]],
     confidence=0.0,
     ).model_dump()
     return parsed.model_dump()
    
     def predict(self, context, model_input, params=None):
     if isinstance(model_input, pd.DataFrame):
     rows = model_input.to_dict(orient="records")
     else:
     rows = model_input
     out = []
     for row in rows:
     q = self._preprocess(row)
     if q is None:
     out.append({"answer": "Empty question.", "citations": [], "confidence": 0.0})
     continue
     hits = self._retrieve(q)
     messages = self._build_prompt(q, hits)
     raw = self.llm.invoke(messages).content
     out.append(self._postprocess(raw, hits))
     return pd.DataFrame(out)
    

    The chain logs cleanly because every dependency is reproducible inside the model serving container: the Vector Search client reads the endpoint by name and the LLM reads the Foundation Model API endpoint by name.

    💡 Exam Trap: The pyfunc predict method must accept pandas DataFrame, dictionary, or list of dictionary input shapes. If you write def predict(self, context, model_input): without accepting any of those shapes, the serving endpoint returns a 400 error on the first request because the model-serving runtime always sends a DataFrame.

    💡 Exam Trap: load_context runs once per worker at startup, while predict runs on every request. Heavy artifacts such as embedding models, tokenizers, or vector search clients must be initialized in load_context, not in predict. Re-initializing inside predict adds tens of seconds of latency to every call.

    ⚠️ Anti-Pattern: Putting business validation rules inside the LLM prompt rather than the post-processor. The model will silently drop the rule under load. Validate JSON shape with Pydantic in _postprocess and retry on parse failure rather than hoping the model honors the format instruction.

    Identify batch inference workloads and apply ai_query() appropriately

    A batch inference workload is one where latency is measured in minutes or hours, the input is a column in a Delta table, the output is another column written back to Delta, and there is no end-user blocking on the response. The canonical examples:

    • classifying every support ticket from the previous reporting period
    • summarizing the customer-call transcripts written overnight
    • scoring every product review against a sentiment model

    For these workloads, a streaming serving endpoint is the wrong tool because each row pays cold-start, network, and per-request overhead. The right tool is ai_query().

    ai_query() is a SQL function that calls any Databricks Model Serving endpoint over a batch of rows, fanning out to multiple parallel connections and writing the result column inline.

    It supports:

    • Foundation Model APIs endpoints out of the box
    • custom pyfunc serving endpoints registered to Unity Catalog
    • external model endpoints proxied through AI Gateway
    SELECT
     ticket_id,
     ticket_text,
     ai_query(
     'databricks-meta-llama-3-3-70b-instruct',
     CONCAT(
     'Classify this ticket as one of {billing, technical, account, other}. ',
     'Return only the label. Ticket: ',
     ticket_text
     ),
     returnType => 'STRING',
     failOnError => false
     ) AS predicted_category
    FROM main.genai_prod.support_tickets_raw
    WHERE created_date = current_date() - INTERVAL 1 DAY;
    

    The optional failOnError => false setting routes parse failures into a null result rather than aborting the query, which matters when a single malformed row should not kill an overnight job. For provisioned-throughput endpoints, ai_query() automatically respects the endpoint's min_provisioned_throughput and max_provisioned_throughput, so the same SQL scales from 100 rows to 100 million rows without code changes.

    📊 Limit: ai_query() against a pay-per-token endpoint inherits the endpoint's queries-per-second limit. Provisioned-throughput endpoints scale to the configured maximum tokens-per-second. For multi-million-row batches, switch to provisioned throughput or ai_query() will throttle.

    🎯 Scenario: A team built a streaming Model Serving endpoint for ticket classification and a workflow calls it row by row from a notebook with requests.post. Throughput is 80 requests per second and the nightly batch of 4 million tickets takes 14 hours. Replacing the loop with SELECT ai_query(...) FROM tickets against the same endpoint cuts the run to 38 minutes because ai_query() parallelizes across the cluster.

    Decision Anchor

    Choose a pyfunc model with predict containing pre- and post-processing when any custom Python must run alongside the LLM call inside the same artifact. Choose mlflow.langchain.log_model for pure LangChain Runnable graphs with no custom logic. Choose ai_query() over a serving endpoint loop when the workload is bound to a Delta table and end-user latency is not in scope.


    Continue with the interactive course

    Track your progress, jump into practice questions and use the Shark AI tutor inside the Databricks - Gen AI Engineer Associate learning hub.