3: Application Development

    Select Langchain/similar tools for use in a Generative AI application.

    A generative AI application on Databricks is built as a graph of model tasks, retrievers, tools, parsers, and memory. The orchestration framework is the layer that lets you express that graph in code, log it to MLflow, deploy it to Mosaic AI Model Serving, and trace every step. Picking the wrong framework forces rewrites later; picking the right one keeps the agent shape stable from prototype to production.

    Key points

    The supported authoring styles on Databricks are:

    • LangChain and LangGraph for graph and chain composition
    • LlamaIndex for retrieval-heavy applications where the index is the spine of the app
    • DSPy for declarative prompt-program optimization
    • AutoGen and OpenAI Agents SDK for multi-agent conversation patterns
    • raw Python calling Foundation Model APIs directly

    All of these can be wrapped in a ChatAgent or ResponsesAgent subclass and logged with mlflow.pyfunc.log_model, which keeps the deployment surface uniform regardless of the inner library.

    LangChain remains the default choice when you need a linear or DAG-shaped chain with prompts, retrievers, LLM calls, and output parsers, and when you want first-class integration with Mosaic AI Vector Search and Databricks Model Serving. LangChain Runnables compose with | operators, expose .invoke, .batch, .stream, and .astream, and are auto-traced by mlflow.langchain.autolog().

    LangGraph extends LangChain to stateful graphs with cycles and conditional edges, which is the right tool when an agent must loop tool calls until a stopping condition, or when human-in-the-loop interrupts are part of the design.

    LlamaIndex is the right pick when retrieval dominates and the application is mostly a question-answering interface over a fixed corpus. Its VectorStoreIndex, QueryEngine, and ResponseSynthesizer abstractions favor the index-centric mental model. On Databricks it integrates with Mosaic AI Vector Search through DatabricksVectorSearch.

    DSPy turns prompts into compiled programs whose few-shot exemplars are learned from data, and is appropriate when prompt quality dominates accuracy and you have an eval set to compile against.

    AutoGen and the OpenAI Agents SDK target multi-agent supervisor patterns where roles converse, which on Databricks is more often expressed through Agent Bricks Multiagent Supervisor.

    💡 Exam Trap: Questions sometimes ask whether to "use LangChain or MLflow" as if they were alternatives. They are not. MLflow is the experiment tracking, registry, and serving layer. LangChain is the orchestration library. Every LangChain chain on Databricks gets logged through mlflow.langchain.log_model. The right answer almost always combines the two.

    The decision rule is anchored to the agent shape.

    • A simple RAG pipeline with one retriever and one LLM call is a LangChain Runnable.
    • An agent that loops tool calls until it answers a question is LangGraph or the Mosaic AI Agent Framework's tool-calling pattern.
    • A retrieval-heavy app where every question hits the same index is LlamaIndex.
    • A prompt-program with measurable accuracy is DSPy.
    • A multi-role conversation is Agent Bricks Multiagent Supervisor or a hand-rolled supervisor in LangGraph.

    Selecting LangChain components for a chain

    LangChain components map one-to-one onto the chain pieces defined in Chapter 1. A ChatPromptTemplate is the prompt template. A DatabricksVectorSearch instance returns a retriever via .as_retriever(). A ChatDatabricks instance is the LLM call against a Foundation Model API or Provisioned Throughput endpoint. A PydanticOutputParser or JsonOutputParser is the output parser. RunnableLambda and RunnablePassthrough are the glue. ConversationBufferMemory or a persistent store in Lakebase is the memory.

    from langchain_core.prompts import ChatPromptTemplate
    from langchain_core.output_parsers import StrOutputParser
    from langchain_databricks import ChatDatabricks, DatabricksVectorSearch
    from langchain_core.runnables import RunnablePassthrough
    
    retriever = DatabricksVectorSearch(
     endpoint="vs_endpoint_prod",
     index_name="catalog_app.rag.policy_chunks_idx",
     columns=["chunk_id", "doc_title", "content"],
    ).as_retriever(search_kwargs={"k": 8})
    
    prompt = ChatPromptTemplate.from_messages([
     ("system", "Answer the question using only the provided context. "
     "If the context is insufficient, reply with 'I do not know.'"),
     ("human", "Context:\n{context}\n\nQuestion: {question}"),
    ])
    
    llm = ChatDatabricks(endpoint="databricks-meta-llama-3-3-70b-instruct",
     temperature=0.0, max_tokens=800)
    
    def format_docs(docs):
     return "\n\n".join(f"[{d.metadata['doc_title']}]\n{d.page_content}" for d in docs)
    
    chain = (
     {"context": retriever | format_docs, "question": RunnablePassthrough()}
     | prompt
     | llm
     | StrOutputParser()
    )
    

    The format_docs function is where you control how retrieved chunks enter the prompt. Including the title gives the model a citation handle. Joining with double newlines preserves chunk boundaries. The chain is a Runnable, which means it can be invoked, batched, streamed, traced, and logged without rewriting.

    Selecting a model from a model hub or marketplace based on model card metadata

    Before a model can be wired into a chain, it has to be chosen.

    How it works

    Databricks exposes models through three surfaces:

    • The Foundation Model APIs catalog (pay-per-token endpoints like databricks-meta-llama-3-3-70b-instruct, databricks-gte-large-en, databricks-claude-sonnet)
    • The Databricks Marketplace (curated third-party models published as Unity Catalog model assets)
    • External model integrations through Mosaic AI Gateway (OpenAI, Anthropic, Google, AWS Bedrock)

    Hugging Face Hub is the external hub that ships with model cards in the form the exam refers to. A model card has predictable fields.

    • Intended use lists the tasks the publisher tested.
    • Out-of-scope use lists tasks the publisher does not endorse.
    • Training data describes the corpus, which signals domain coverage.
    • Eval results report benchmark scores (MMLU, HellaSwag, HumanEval, GSM8K, MT-Bench, IFEval).
    • Bias and risk sections describe known failure modes.
    • License terms set commercial-use boundaries.
    • Architecture and parameter count describe the model's compute footprint.
    • Context length sets the maximum input plus output token budget.
    • Tokenizer notes affect cost estimation.

    Model card metadata in YAML front-matter on Hugging Face exposes tags like task, language, library_name, and license.

    📊 Limit: Hugging Face model cards expose a YAML metadata block at the top of the README. The fields parsed by the Hub include license, tags, pipeline_tag, language, datasets, base_model, and model-index. The model-index block carries evaluation results in a structured form that can be queried programmatically.

    Steps

    The selection algorithm against a model card is sequential.

    • First filter by license: any commercial application must reject licenses that prohibit commercial use or that have user thresholds the deployment cannot accept.
    • Second filter by intended use: if the card lists chat or instruction-following and you need code generation, the card is signaling a mismatch.
    • Third filter by context length against your worst-case prompt size including retrieved context.
    • Fourth read the eval table: pick benchmarks that resemble the task, not just the leaderboard average.
    • Fifth check the bias and safety sections for known refusal patterns that conflict with the application domain.
    • Last, run the surviving candidates through your own eval set; published benchmarks rarely predict in-domain performance.

    ⚠️ Anti-Pattern: Picking the model with the highest MMLU score and shipping. MMLU measures multiple-choice academic knowledge. It does not measure tool-calling accuracy, JSON adherence, refusal calibration, latency, or cost. Two models within one MMLU point can differ by an order of magnitude in cost-per-million-tokens.

    💡 Exam Trap: A question may describe a scenario where the team picks a model "because the model card lists chat as the intended use" but the task is structured extraction. Chat capability does not imply JSON-mode reliability. The right answer is to look for a model card whose intended use includes structured output or function calling, or to add a Pydantic output parser plus eval evidence before deciding.

    The Databricks Marketplace exposes models as Unity Catalog assets with their own listing pages. Listings include the publisher, license, model size, supported endpoints, and a link to the upstream model card.

    Installing a Marketplace model creates a model in your catalog that can be served behind a custom Mosaic AI Model Serving endpoint, which is the path to use when a Foundation Model API endpoint is not available for that model or when provisioned throughput is required.

    🎯 Scenario: A team needs a chat assistant that ingests support tickets averaging 6k tokens and writes a JSON triage record. The candidate models are Llama 3.3 70B (128k context, MMLU 86, instruction-tuned, native function calling), Mistral Large (32k context, MMLU 84, function calling, paid license), and a 7B open model (8k context, MMLU 65). The 8k-context model is rejected on context. Mistral Large is rejected on license against the application's budget. Llama 3.3 70B wins because the context fits the worst-case ticket, function calling supports the JSON contract, and the eval set on the team's labeled tickets confirms the choice.

    Decision Anchor

    Comparison

    • Choose LangChain Runnables when the chain is a DAG with at most one tool-call loop.
    • Choose LangGraph when the application needs cycles, branches, or interrupts.
    • Choose LlamaIndex when retrieval shape (multi-index, parent-child, summary index) is the dominant design concern.
    • Choose DSPy when you have an eval set and want exemplars compiled into the prompt.
    • Choose raw Foundation Model APIs only for one-shot inference or for ai_query batch workloads where chain overhead is not justified.

    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.