CertSafari
    Databricks Certified Generative AI Engineer Associate· Lessons

    Domain 3 · Lesson 25/56

    Building agents with MLflow ResponsesAgent, tracing and the improvement loop

    Utilize MLflow and Agent Framework for developing agentic systems

    16 min read
    2.31% of exam
    11 sources
    Published 22 Oct 2026
    Docs as of 17 Oct 2026

    What you will be able to do

    • Wrap an agent from any authoring library in the ResponsesAgent interface with predict and predict_stream
    • Attach Unity Catalog function tools and vector search retriever tools to an agent
    • Turn on MLflow Tracing with one autolog call for the framework in use, and add manual spans where autolog does not reach
    • Run the agent improvement loop: trace, find an issue, build a dataset, score, fix, re-evaluate, monitor

    Key concept

    The trace as the agent's evidence — A trace records every intermediate step of one agent run (model calls, tool calls, retrieval), with the inputs and outputs of each. Debugging, evaluation datasets, scorers and production monitoring all read from that record. Without it, you can only see the final answer.

    1.One interface for agents from any framework

    Custom agents on Databricks can be written in LangGraph, LangChain, the OpenAI SDK, LlamaIndex or plain Python. Whatever is inside, the agent has to look the same from outside. Serving, the chat UI and evaluation all need one request shape and one response shape. MLflow's ResponsesAgent provides that contract. You subclass it, put your framework code inside its methods, and everything downstream calls the class instead of your framework.

    The contract has two methods. predict takes a ResponsesAgentRequest and returns a ResponsesAgentResponse whose output is a list of output items. predict_stream takes the same request but is a generator: it yields ResponsesAgentStreamEvent objects as the work proceeds, so a client can show progress before the answer is finished.

    The class-based ResponsesAgent: a synchronous predict and a streaming predict_streampython
    from mlflow.pyfunc import ResponsesAgent, ResponsesAgentRequest, ResponsesAgentResponse
    
    class MyAgent(ResponsesAgent):
      def predict(self, request: ResponsesAgentRequest, params=None) -> ResponsesAgentResponse:
        # Synchronous implementation
        ...
        return ResponsesAgentResponse(output=outputs)
    
      def predict_stream(self, request: ResponsesAgentRequest, params=None):
        # Synchronous generator
        for chunk in ...:
          yield ResponsesAgentStreamEvent(...)

    Write the logic once, in the streaming path. A streamed event whose type is response.output_item.done carries a finished output item. The non-streaming response is just those finished items collected into the output list. Keeping two separate implementations invites drift. A fix lands in one path and not the other, and the streamed and non-streamed answers stop matching.

    The tool-calling loop fits inside this streaming method. The tool-calling loop is the cycle where the model asks for a tool, the tool runs, and its result goes back to the model until the model gives a final answer. Inside predict_stream, each turn of that loop yields its items as they complete. The client sees the agent's steps arrive in order and does not wait silently for the final message.

    Newer Databricks Apps agents use the same request, response and event types. The difference is that the logic sits in module-level functions decorated with @invoke() and @stream() from mlflow.genai.agent_server, not in class methods. Moving from the class form is mostly mechanical: each method becomes a decorated function. The server in front of the agent handles the plumbing every agent needs, including routing, logging and error handling, so your code does not have to.

    Checkpoint 1 of 7· Check yourself

    One team built its agent in LangGraph and another used the OpenAI SDK. Both teams subclass MLflow's ResponsesAgent and put their framework code inside its methods. What does this give them?

    Sources123

    2.Attaching governed tools to the agent

    Tools are added to an agent the same way whichever framework runs it. Tool types for LangChain agents (local, UC function, retriever) explains the three kinds of tool. The point here is that the same two Databricks tool objects plug into whatever runs inside your ResponsesAgent.

    Unity Catalog functions are added through UCFunctionToolkit. You pass the registered function's full name in function_names, and the toolkit's tools property becomes the tool list you give the model or the agent constructor. When the model asks for a call, a helper runs the registered Unity Catalog function. The function stays the governed object in Unity Catalog. Copying its body into a local @tool would create an ungoverned duplicate that drifts from the registered version. Wrapping it in a PyFunc model or reaching it through a Genie Space adds machinery that does not make it a tool.

    Three names in the example below come from setup that is not repeated in the snippet. function_name is the registered function's full name, such as my_catalog.my_schema.add_numbers. client is a DatabricksFunctionClient() from unitycatalog.ai.core.databricks, the object the toolkit and the helper use to reach Unity Catalog. generate_tool_call_messages, imported from unitycatalog.ai.anthropic.utils for this Anthropic example, is the helper that runs the functions the model requested and formats their results as messages. Append those messages to the conversation before the next model call.

    UCFunctionToolkit exposes a registered function as a tool. Here an Anthropic client runs the tool-calling loop for up to 10 turnspython
    toolkit = UCFunctionToolkit(function_names=[function_name], client=client)
    model_client = Anthropic()
    messages = [{"role": "user", "content": question}]
    
    for _ in range(10):
        response = model_client.messages.create(
            model=os.environ["ANTHROPIC_MODEL"],
            max_tokens=1024,
            tools=toolkit.tools,
            messages=messages,
        )
        if response.stop_reason != "tool_use":
            print("\n".join(block.text for block in response.content if block.type == "text"))
            break
        messages.extend(
            generate_tool_call_messages(
                response=response, client=client, conversation_history=[],
            )
        )

    Retrieval over a vector index is added through VectorSearchRetrieverTool, which ships in both databricks-langchain and databricks-openai. For a LangChain or LangGraph agent, install databricks-langchain and create the tool with the index's three-part name and a description. The description tells the model when to search. If the index uses Databricks managed embeddings, you pass no embedding model and write no retrieval function. The result is a ready LangChain tool to drop into the agent's tool list. Two common wrong answers miss this. DatabricksEmbeddings only turns text into vectors and is not a tool. Standing up an MCP server first is extra setup that a notebook prototype does not need.

    Checkpoint 2 of 7· Match them up

    An agent builder is weighing four ways to give a LangChain agent access to governed data. Match each option to what it actually does.

    Tap a term, then the definition that fits it.

    Checkpoint 3 of 7· Exam question

    A team is building a tool-calling LangChain agent on Databricks that must invoke a Python function already registered and governed in Unity Catalog. They want the function's permissions to remain enforced by Unity Catalog while exposing it as a callable tool to the agent. Which approach should they use?

    Checkpoint 4 of 7· Exam question

    A developer is prototyping a retrieval tool locally in a notebook before deploying an agent that queries a Databricks-managed vector search index built with Databricks-managed embeddings. They want a LangChain-compatible tool object they can pass directly to their agent with minimal setup. Which option fits this stage of development?

    Sources45

    3.Recording every step: autolog and manual spans

    A trace records one agent run as a tree of spans: agent, then model call, then tool call. Each span has its own inputs, outputs, latency and token usage. That tree is what makes a multi-step agent debuggable. If you only have the question and the final answer, you cannot tell whether the retriever returned nothing, the model ignored the tool result, or the tool itself failed.

    For a supported framework, one call does the instrumenting. mlflow.<framework>.autolog() patches the library so every LLM call, tool call and agent step becomes a span without decorators. Call it once at the top of the notebook, before the agent runs. It is not something you put inside a class definition, and it does not replace mlflow.start_run() or metric logging. Runs and metrics record training experiments, not the steps of an agent. LangGraph has no autolog of its own and uses LangChain's.

    On serverless compute, autologging is not enabled by default. Nothing is patched until you call mlflow.<library>.autolog() yourself, once for each integration you want traced, so a serverless notebook that skips the call records no spans.

    A LangGraph agent traced with one autolog call. The trace appears in the experiment's Traces tabpython
    import mlflow
    from langchain_core.tools import tool
    from langchain_openai import ChatOpenAI
    from langgraph.prebuilt import create_react_agent
    
    mlflow.langchain.autolog()  # LangGraph uses LangChain's autolog
    mlflow.set_tracking_uri("databricks")
    mlflow.set_experiment("/Shared/langgraph-tracing-demo")
    
    @tool
    def get_weather(city: str):
        """Get weather for a city."""
        return f"It might be cloudy in {city}"
    
    graph = create_react_agent(ChatOpenAI(model="gpt-4o-mini"), [get_weather])
    graph.invoke({"messages": [("user", "What is the weather in SF?")]})

    Autolog needs an explicit call for each library, and it can be switched off the same way. mlflow.openai.autolog(disable=True) stops one integration, and mlflow.autolog(disable=True) stops them all. An agent that uses both an OpenAI client and LangChain needs both autolog calls. Leave one out and the trace silently loses that half of the work.

    Manual spans cover the code autolog cannot see: your own routing logic, a proprietary client, or a step you want to name precisely. Both high-level methods nest automatically under whatever span is already open, so manual spans and autologged spans form one tree.

    Manual tracing methods and when each fits
    MethodUse whenParent-child links
    @mlflow.trace decoratorTracing an entire Python functionAutomatic
    mlflow.start_span() context managerTracing a code block within a functionAutomatic
    Low-level MlflowClient APICustom trace IDs, integration with an external observability systemManual

    Span types matter as well as span boundaries. Decorating a retrieval function with @mlflow.trace(span_type="RETRIEVER") tells MLflow which span holds the retrieved documents. The retrieval-specific judges, such as RetrievalGroundedness, look for that span. Mark the retriever as a generic function span and those judges have nothing to read.

    Checkpoint 5 of 7· Check yourself

    A RAG agent runs on LangChain with mlflow.langchain.autolog() called at the top of the notebook. It also has a custom retrieval function, decorated with a plain @mlflow.trace, that calls a proprietary search client. The traces show every step. Even so, the RetrievalGroundedness judge has nothing to assess. What should change?

    Checkpoint 6 of 7· Exam question

    An engineering team is iterating on a multi-step LangChain agent that calls several tools before producing a final answer. They want every LLM call and tool invocation automatically captured as MLflow trace spans during local development, without adding manual @mlflow.trace decorators to each function. What should they do?

    Sources6789

    4.The improvement loop from first trace to production

    Agent quality improves in repeated cycles, not in one test before launch. Each pass of the loop fixes one problem, and the next problem shows up in the traces:

    The steps run in this order:

    1. Trace the agent so every run is captured.
    2. Find an issue in development traces, or catch a regression in production.
    3. Collect feedback on the failing traces and curate them, with known-good examples, into an evaluation dataset.
    4. Write a scorer, either an LLM judge or a code check, that catches the issue automatically.
    5. Fix the prompt or the agent code at the root cause.
    6. Re-run evaluation against the dataset to confirm the fix and check that nothing else broke.
    7. Monitor production by running the same scorers on live traffic.

    The agent code usually lives in a scaffold. Custom agents iterate fastest on Databricks Apps, and the agent template comes with the server, tracing and a chat UI already connected. Databricks Apps agent template and chat UI covers the template itself. In this loop it is simply where you edit the code during step 5 and chat with the result.

    Steps 3 and 6 rest on traces. You can save selected traces from the experiment's Traces tab into an evaluation dataset in Unity Catalog. Evaluation results are then linked to that dataset, so you can see whether a version scores better on the same cases. The re-evaluation in step 6 uses mlflow.genai.evaluate() harness, which runs the agent on the dataset and applies your scorers. When the harness calls the agent directly, the traces it produces match production traces. That is why the scorers from step 4 can run unchanged in step 7.

    Checkpoint 7 of 7· Put it in order

    A support agent is already traced, and its development traces show it quoting an outdated refund policy. Arrange the rest of this improvement pass, starting from the issue you have just found.

    1. 1.Fix the prompt or the agent code at the root cause
    2. 2.Write a scorer, either an LLM judge or a code check, that catches the outdated-policy answers automatically
    3. 3.Run the same scorers on live production traffic so the issue does not come back
    4. 4.Re-run evaluation against the dataset to confirm the fix and check that nothing else broke
    5. 5.Collect feedback on the failing traces and curate them, with known-good examples, into an evaluation dataset

    Sources61910

    Sources

    (11)

    Every claim above is drawn from one of these pages, quoted as it was written on the date shown.

    1. 1.
      “Supports agents written with any authoring library, including LangGraph, LangChain, OpenAI, and LlamaIndex.”
      ↩︎ One interface for agents from any framework
      “Iterate quickly using Databricks Apps.”
      ↩︎ The improvement loop from first trace to production
      “Author, deploy, and evaluate agents using Python. Supports agents written with any authoring library, including LangGraph, LangChain, OpenAI, and LlamaIndex.”
      ↩︎ Checkpoint
      “Create agent tools to query structured and unstructured data, run code, or connect to external service APIs.”
      ↩︎ Checkpoint
    2. 2.
      “The non_streaming() function collects its output and returns it as a single response.”
      ↩︎ One interface for agents from any framework
      “Extract the class methods into decorated module-level functions with minimal structural changes.”
      ↩︎ One interface for agents from any framework
    3. 3.
      “automatically manages request routing, logging, and error handling”
      ↩︎ One interface for agents from any framework
    4. 4.
      “UCFunctionToolkit(function_names=[function_name], client=client)”
      ↩︎ Attaching governed tools to the agent
      “The helper runs the requested functions. Append its messages to the conversation before the next model call.”
      ↩︎ Attaching governed tools to the agent
      “function_name = "my_catalog.my_schema.add_numbers"”
      ↩︎ Attaching governed tools to the agent
    5. 5.
      “Use VectorSearchRetrieverTool from databricks-langchain or databricks-openai to expose an index as an agent tool.”
      ↩︎ Attaching governed tools to the agent
      “Create a retriever tool and give it a description that tells the agent when to search.”
      ↩︎ Attaching governed tools to the agent
      “The first examples use Databricks managed embeddings and a model endpoint that supports tool calling.”
      ↩︎ Attaching governed tools to the agent
      “Use VectorSearchRetrieverTool from databricks-langchain or databricks-openai to expose an index as an agent tool.”
      ↩︎ Exam trap 3
    6. 6.
      “With only an input and final response, you cannot tell which intermediate decision caused a failure.”
      ↩︎ Recording every step: autolog and manual spans
      “Each pass fixes one issue and surfaces the next.”
      ↩︎ The improvement loop from first trace to production
      “Write a scorer. Define a scorer (an LLM judge or code-based check) that catches the issue automatically.”
      ↩︎ The improvement loop from first trace to production
      “Improving an agent isn't a one-time step — it's a loop you run continuously.”
      ↩︎ Exam trap 4
      “Improving an agent isn't a one-time step — it's a loop you run continuously. Each pass fixes one issue and surfaces the next.”
      ↩︎ Checkpoint
    7. 7.
      “patches the library at import time so every LLM invocation, tool call, and agent step is captured as a span”
      ↩︎ Recording every step: autolog and manual spans
      “You must call mlflow.<library>.autolog() explicitly for each integration you want to trace.”
      ↩︎ Recording every step: autolog and manual spans
      “On serverless compute clusters, autologging is not enabled by default.”
      ↩︎ Exam trap 1
      “On serverless compute clusters, autologging is not enabled by default.”
      ↩︎ Prediction
    8. 8.
      “The @mlflow.trace decorator creates a span for any Python function.”
      ↩︎ Recording every step: autolog and manual spans
      “Use manual tracing when you need to instrument code that autolog doesn't cover”
      ↩︎ Exam trap 2
    9. 9.
      “to enable MLflow's retrieval-specific LLM judges”
      ↩︎ Recording every step: autolog and manual spans
      “Storing the traces in an evaluation dataset allows you to link evaluation results to the dataset”
      ↩︎ The improvement loop from first trace to production
      “The retrieval component is marked with span_type="RETRIEVER" to enable MLflow's retrieval-specific LLM judges.”
      ↩︎ Checkpoint
    10. 10.
      “the same evaluation logic you use in development can also run in production”
      ↩︎ The improvement loop from first trace to production

    Also cited

    Spotted a mistake, or was something unclear? Tell us.