Day2:Get Started with Text Analysis in Azure

Text processing and analysis are possible through natural language processing (NLP). NLP enables machines to understand, interpret, and respond to human language. The goal of NLP is to analyze and extract meaning or structure from existing text.

Text analysis is the process of automatically examining written text to extract useful information—such as sentiment, keywords, entities, or topics. Text analysis relies on NLP to turn unstructured text into meaningful insights.

Understand text analysis in Foundry

Foundry portal offers two approaches to text analysis: general-purpose AI models that handle a broad range of tasks through natural language prompts, and purpose-built language tools that return structured, deterministic results for specific tasks.

Using general-purpose AI models for text analysis

A general-purpose model can follow natural language instructions to analyze sentiment, extract entities, summarize text, translate content, answer questions, and much more — all without any configuration or training on your part.

You can use a general-purpose AI model to handle text analysis tasks such as:

  • Key phrase extraction lists the main concepts from unstructured text.
  • Entity linking identifies known entities together with a link to Wikipedia.
  • Sentiment analysis and opinion mining identifies whether text is positive or negative.
  • Summarization summarizes text by identifying the most important information.

Using Azure Language in Foundry tools

Azure Language in Foundry tools is a natural language processing service with purpose-built analyzers for specific text analysis tasks. These analyzers use statistical techniques to return structured, deterministic output — making them well-suited for automated pipelines where consistent results matter.

Use Azure Language with an agent

AI agents use tools and models to perform tasks such as reasoning, planning, retrieval, and calling external services. While an agent can use a generative AI model to understand and generate language, that model alone can’t perform text analysis tasks that require deterministic, structured analysis. Adding Azure Language in Foundry Tools to an agent gives it consistent and predictable text analysis functionality.

Understand MCP

The Model Context Protocol (MCP) is an open standard that defines how AI agents connect to external tools and data sources.

MCP uses a client-server architecture:

  • The MCP client is the AI agent (or the host application running the agent). It sends requests and receives responses.
  • The MCP server is the service that exposes tools, data, or actions. It listens for requests, executes the appropriate capability, and returns a structured result.

The Azure Language MCP server is a managed service that exposes Azure Language in Foundry Tools capabilities through MCP. It acts as the bridge between your agent and the full suite of Azure Language features—named entity recognition, sentiment analysis, language detection, and more.

You can add the Azure Language MCP server as a tool in the Foundry playground by searching tools for Azure Language in Foundry Tools.

To connect to the Azure Language MCP server, configure your connection with your Foundry resource name. Once you’ve connected the MCP server to your agent, use prompts to instruct the agent to analyze text using the tool.

With the MCP server connected, your agent can combine the reasoning capability of the language model with the precision of Azure Language’s text analysis features—making it well suited for tasks like routing support tickets by detected language or identifying and redacting personally identifiable information (PII).

Get started with speech in Azure

AI speech capabilities enable us to manage systems with voice instructions, get answers from computers for spoken questions, generate captions from audio, and much more.

To enable this kind of interaction, the AI system must support at least two capabilities:

  • Speech recognition: the ability to detect and interpret spoken input
  • Speech synthesis: the ability to generate spoken output

Speech recognition, often called speech-to-text (STT), is an AI capability that enables apps and agents to respond to spoken input.  Speech-to-text software typically uses multiple models, including:

  • A language model that maps phonemes to words.
  • An acoustic model that converts the audio into phonemes (representations of specific sounds).

In the new Microsoft Foundry portal, we can explore Azure Speech’s speech-to-text capabilities in the Foundry playground.

double click, open playground

Day 1: Get started with AI applications and agents on Azure

Microsoft Foundry for AI

What is Microsoft Foundry

Microsoft Foundry is a unified, enterprise-grade platform-as-a-service (PaaS) for building, deploying, and managing AI applications and agents. It consolidates models, agent orchestration, monitoring, and governance tools in one platform, offering production-grade infrastructure and security.

Foundry offers powerful capabilities for developers, including the ability to choose from a wide range of models, use those models to build agents, connect those agents to tools, and integrate knowledge by using Foundry IQ, the centralized connection point for data sources.

Models

Users can browse thousands of models—ranging from massive foundation models to lightweight, domain-specific variants—evaluate them via built-in leaderboards and playgrounds, and manage deployments directly in Foundry

Agents

At the core of Microsoft Foundry is an agent‑first approach that lets developers build intelligent, task‑oriented agents directly within their Foundry projects. These agents can reason over inputs, call tools, interact with data, and automate workflows using the platform’s built‑in orchestration. Foundry handles the underlying coordination—including message threading, tool execution, safety controls, and observability—so developers can focus on designing the agent’s goals and capabilities. Using either low‑code or code‑first workflows, teams can create multi‑agent systems that work with project resources such as documents, datasets, search indexes, and connections to external systems, including integrations like Azure Functions or Microsoft Fabric.

Tools

Foundry offers a comprehensive suite of Azure services—such as speech, vision, language, document intelligence, and more. These Foundry Tools provide AI capabilities that can be built into web or mobile applications in a way that’s straightforward to implement.

Knowledge

Foundry IQ provides a permission‑aware, multi‑source knowledge layer that gives agents accurate, grounded answers using an organization’s own data. It lets you create a configurable knowledge base made up of internal and external knowledge sources—such as Azure Blob Storage, SharePoint, OneLake, or public web data—and automatically handles indexing, document chunking, vector embeddings, and metadata extraction. When an agent queries the knowledge base, Foundry IQ uses agentic retrieval to break the question into subqueries, search multiple sources in parallel, and return relevant, citation‑backed information while enforcing user permissions and Microsoft Purview sensitivity labels. This ensures that agents can draw from trusted, up‑to‑date content and only return information the user is authorized to see, providing a reliable knowledge foundation for enterprise AI workflows.

Foundry resources and projects

Azure resource

A Foundry resource is the Azure resource that provides the platform capabilities. A Foundry resource provides access to:

  • Models (Microsoft, partner, and OpenAI‑compatible)
  • Foundry’s agent service
  • Deployment governance
  • Monitoring & observability
  • Security boundaries
  • Quotas and operational controls

Foundry project

A Foundry project is a workspace inside that resource where you build AI apps, agents, and evaluations. A Foundry Project lets you build and manage:

  • Agents
  • Evaluations
  • Files and datasets
  • Vector indexes
  • Flows (AI logic)
  • Connections
  • Project‑specific settings

You might have one Foundry resource for a team or department, and many Foundry projects inside it, each focused on a separate AI use case.

Foundry portal

The Foundry portal provides a modern web-based interface for developing, testing, and operating AI solutions.

Consider the following workflow for using Foundry portal to develop an AI application.

Create an Agent in Foundry portal

Sign in Foundry portal using your Azure subscription and create a Foundry project. https://ai.azure.com

To create an agent in Foundry, you can start by exploring a model or just go straight to agent development. In Foundry portal, creating an agent looks similar at first to testing a model in the playground.

  1. Choose the model your agent uses.
  2. Write the system instructions, such as “You’re a helpful scheduling assistant who returns answers in concise bullet points.”

Key configuration parameters

  • Temperature: controls creativity vs. determinism.
  • Max output tokens – caps response length; affects token consumption and throttling behavior.
  • System instructions – sets behavior and role of the model.

In Foundry, pick a model from the Model Catalog and deploy it.

use the Playground to write prompts, test model responses, configure parameters.

In this module, we’ve introduced Azure, Microsoft’s cloud service for global scale software applications, and learned about Microsoft Foundry, a platform for building AI apps and agents on Azure. With this foundational knowledge, you can start to explore how to use Foundry to deploy and work with generative AI models, develop agents, and integrate AI capabilities like speech and computer vision.

Add Tools

Tools in Foundry allow a model to perform actions by calling external systems. They represent callable capabilities such as searching the web, querying a database, or using an MCP server.

create a tool box

Toolbox provides a centralized way to manage and share tools in Microsoft Foundry. Toolbox helps simplify tool integration while enabling centralized credential management, governance, observability, and access control. Instead of configuring tools independently for every agent, teams can manage tools in one place, reuse them across multiple agents, and update tool implementations without requiring changes to agent code. 

add tools into the tools box

Add Knowledge

Knowledge allows the model to access and retrieve external content (your documents, datasets, internal sites) through retrieval-augmented generation (RAG).

In the playground, Foundry uses retrieval pipelines to:

  1. Ingest + index your content
  2. Search + ground responses
  3. Make answers more accurate, traceable, and domain‑specific

Using an agent

You can use an agent from a client application by using the Foundry Projects SDK to connect to the project and call it from a client using the Project API.

The Project API enables you to:

  • Integrate agents into web apps, bots, or backend workflows
  • Orchestrate multi‑step tasks
  • Pass structured inputs or tool calls
  • Run agents at scale with your Foundry deployments
# Before running the sample:
#    pip install "azure-ai-projects>=2.1.0"

from azure.identity import DefaultAzureCredential
from azure.ai.projects import AIProjectClient

endpoint = "https://erjunchen-2531-resource.services.ai.azure.com/api/projects/erjunchen-2531"
agent_name = "WC-agent-2531"
user_message = "Hi WC-agent-2531"

with (
    DefaultAzureCredential() as credential,
    AIProjectClient(
        endpoint=endpoint,
        credential=credential,
        allow_preview=True,
    ) as project_client,
):
    # Bind the OpenAI client to the existing agent endpoint.
    openai_client = project_client.get_openai_client(agent_name=agent_name)

    # GitHub Copilot preview agents require a conversation for every Responses turn.
    conversation = openai_client.conversations.create()
    response = openai_client.responses.create(
        conversation=conversation.id,
        input=[{"role": "user", "content": user_message}],
    )

    print(f"Response output: {response.output_text}")

LangSmith End-to-End Observability and Cost Monitoring

The goal of this unit is to help you monitor, troubleshoot, and optimize a production AI Agent, including what it did at each step, why it failed, how much it cost, and how to locate performance problems.

What is Observability?

Observability is the ability to understand a system’s internal behavior by examining the data it produces, such as traces, logs, metrics, and errors.
可观测性是指通过分析系统产生的数据,例如调用链、日志、指标和错误,来理解系统内部的运行情况。

Without observability, you may only see that the agent returned an error or gave a poor answer. With observability, you can trace the execution path and identify the exact model call, tool execution, or retrieval step that caused the problem.

LangSmith

LangSmith is an observability and evaluation platform for applications built with LLMs and agents, including applications that do not use LangChain.
LangSmith 是一个用于监控和评估 LLM 应用及 Agent 的平台,也可以用于没有使用 LangChain 的应用。

Its core value is to organize execution data scattered across application code, model APIs, tools, and retrieval systems into traces that you can inspect and analyze.
它的核心价值是把原本分散在应用代码、模型 API、Tools 和检索系统中的执行信息,组织成可以检查和分析的调用链。

Cost Monitoring: How Do You Know What Your Agent Costs?

LangSmith can collect token usage and calculate model costs when the required usage information, provider, model name, and applicable pricing are available.
当必要的 Token 使用信息、提供商、模型名称和适用价格都可用时,LangSmith 可以收集 Token 使用量并计算模型成本。

For a model with linear input and output token pricing, the basic cost calculation is as follows.

Here, (I) is the number of input tokens, (O) is the number of output tokens, and (Pi) and (Po) are their respective prices per million tokens.
其中,(I) 是输入 Token 数量,(O) 是输出 Token 数量,(Pi) 和 (Po) 分别是每百万输入 Token 和输出 Token 的价格。

项目 / Item数值 / Value
Input tokens / 输入 Token10,000
Output tokens / 输出 Token2,000
Input price / 输入价格$2 per million tokens
Output price / 输出价格$8 per million tokens
Input cost / 输入成本$0.020
Output cost / 输出成本$0.016
Total / 总成本$0.036

If the agent makes three model calls during one request, the request cost is the sum of all three model-call costs, assuming each call is tracked correctly.
如果 Agent 在一次请求中调用模型三次,那么在每次调用都被正确追踪的前提下,这次请求的成本就是三次模型调用成本的总和。

Key Takeaways

要点 / TopicENCN
TraceRepresents one complete application execution.表示一次完整的应用程序执行。
Run / SpanRepresents an individual operation within a trace.表示 Trace 中的一个具体操作。
@traceableAdds tracing to important Python functions.为重要的 Python 函数添加调用追踪。
wrap_openai()Instruments supported OpenAI calls.为受支持的 OpenAI 调用添加追踪。
Execution treeShows parent-child relationships between operations.展示各操作之间的父子关系。
LatencyHelps locate slow operations.帮助定位耗时较长的操作。
Token usageShows model input and output consumption when available.在数据可用时展示模型输入和输出的使用量。
Cost trackingRequires usable token data and correct model pricing.需要可用的 Token 数据和正确的模型价格。
Custom costsCan account for additional operations and services.可以记录其他操作和服务的额外成本。
PrivacyRequires access control, redaction, and retention policies.需要访问控制、数据脱敏和保留策略。
Production monitoringCombines agent observability with infrastructure monitoring.将 Agent 可观测性与基础设施监控结合起来。

Multi-Agentar Architecture

The goal of this unit is to help you design, develop, and deploy a production-grade Multi-Agent system and understand how to implement this architecture in Azure AI Foundry. We will focus on architecture design, agent responsibilities, task delegation, result aggregation, error handling, and implementation in Azure AI Foundry, rather than just learning LangGraph syntax.
本单元的目标是让你能够设计、开发和部署一个生产级的 Multi-Agent 系统,并理解如何在 Azure AI Foundry 中实现这种架构。我们会重点关注 架构设计、Agent 职责划分、任务委派、结果汇总、错误处理,以及如何在 Azure AI Foundry 中实现。

Orchestrator–Subagent

Orchestrator–Subagent is a multi-agent orchestration architecture in which a primary agent responsible for control flow decomposes a complex task, delegates it to one or more specialist subagents, and uses their results to determine subsequent actions or produce the final output.
Orchestrator–Subagent 是一种多 Agent 编排架构,其中一个负责控制流程的主 Agent 将复杂任务拆分并委派给一个或多个专业子 Agent,再根据子 Agent 返回的结果决定下一步行动或生成最终输出。

Key concept: The Orchestrator coordinates the work, while Subagents execute their assigned specialist tasks.
Orchestrator 负责协调,Subagent 负责执行被分配的专业任务。

Orchestrator 的核心职责

A production-grade Orchestrator does more than delegate tasks. It should handle at least the following six responsibilities.

  1. Task decomposition — 任务拆分
    Break a complex request into subtasks that can be executed independently.
    把一个复杂请求拆分为可以独立执行的子任务。
  2. Routing — 任务路由
    Select the appropriate subagent based on the task type.
    根据任务类型选择合适的 Subagent。
  3. Execution control — 执行控制
    Decide which tasks can run in parallel and which must wait for prerequisite tasks to finish.
    决定哪些任务可以并行执行,哪些必须等待前置任务完成。
  4. State management — 状态管理
    Store task status, subtask results, errors, and execution progress.
    保存任务状态、子任务结果、错误和执行进度。
  5. Validation and recovery — 结果验证与故障恢复
    Check whether results are complete and valid, then decide whether to retry or report a failure.
    检查结果是否完整、是否符合预期,并决定是否重试或报告失败。
  6. Result aggregation — 结果汇总
    Combine results from different agents into a consistent and verifiable final answer.
    把不同 Agent 的结果合并为一致、可验证的最终答案。

Key Takeaways — 关键要点总结

ENCN
The Orchestrator owns the overall task flow.Orchestrator 负责整体任务流程。
Subagents own clearly defined specialist tasks.Subagent 负责定义清晰的专业任务。
State records execution progress and results.State 保存执行进度和结果。
Validate results before producing the final answer.生成最终答案之前,必须验证结果。
Use bounded retries and explicit failure handling.使用有上限的重试,并明确处理失败。

Subagent 应该如何设计?

  • Each Agent needs clear boundaries.
    Each subagent should have clearly defined responsibilities, inputs, outputs, tool permissions, and failure-handling rules.
    每个 Subagent 都应该有清晰的职责、输入、输出、工具权限和失败处理规则。
  • The output of the subagent should be structured.
    Subagent 的输出应该结构化

Should the tasks be executed in parallel or sequentially?

Parallel execution: If several tasks have no dependencies, they can run concurrently.
如果几个任务之间没有依赖关系,可以同时运行。

Sequential execution: If a later task depends on an earlier task’s result, the tasks should run sequentially.
如果后一个任务必须依赖前一个任务的结果,就应该串行执行。

Complex tasks often combine parallel and sequential stages.
复杂任务往往既有并行阶段,也有串行阶段。

Several issues that must be taken into account in the production architecture

  • Failure handling 失败处理
    If a subagent fails, the Orchestrator should have a defined recovery strategy.
    如果一个 Subagent 失败,Orchestrator 应该有明确的处理策略。
  • Permission isolation 权限隔离
    Different subagents can use different tools and permissions.
    不同 Subagent 可以使用不同的工具和权限。
  • Cost and latency 成本和延迟
    Each additional subagent that calls an LLM may increase model costs and response latency.
    每增加一个调用 LLM 的 Subagent,就可能增加模型调用成本和响应时间。
  • Monitoring and tracing 监控与追踪
    Production systems need to record the parent task ID, subagent name, input summary, execution time, status, errors, and cost.
    生产系统需要记录主任务 ID、Subagent 名称、输入摘要、执行时间、状态、错误和成本。

Key Takeaways

要点 / TopicEnglish中文
架构 / ArchitectureThe Orchestrator coordinates specialist agents.Orchestrator 协调专业 Agent。
职责 / ResponsibilitiesEach subagent should have a clear responsibility and boundary.每个 Subagent 都应该有明确的职责和边界。
委派 / DelegationThe Orchestrator assigns tasks to suitable subagents.Orchestrator 将任务分配给合适的 Subagent。
并行 / ParallelismIndependent subtasks can run concurrently.相互独立的子任务可以并行执行。
串行 / Sequential executionDependent subtasks must respect their execution order.有依赖关系的子任务必须遵循执行顺序。
状态 / StateTrack each subtask’s status and result.记录每个子任务的状态和结果。
输出 / OutputUse structured outputs instead of relying only on free-form text.使用结构化输出,不要只依赖自由文本。
错误处理 / Error handlingDistinguish task failure from a successful result containing no findings.区分任务失败和成功执行但没有发现问题。
安全 / SecurityApply least privilege and explicit controls to sensitive operations.对敏感操作实施最小权限和明确的控制。
平台 / PlatformUse Foundry capabilities where available and implement missing application logic yourself.使用 Foundry 已提供的能力,并自行实现缺少的应用逻辑。
架构选择 / Architecture choiceUse multiple agents only when their separation provides real benefits.只有职责拆分能带来实际收益时,才使用多个 Agent。

Agent-to-Agent Communication and Retry Strategies

The focus of this unit is not to relearn Multi-Agent architecture, but to solve two practical production problems: how multiple agents exchange tasks and results, and how a system recovers reliably when an agent fails.

What are Agent Communication and Retry?

Agent communication means one agent sends a task or information to another agent and receives its result.

Retry means attempting a failed operation again under controlled conditions.

Core communication design

A communication contract is similar to an API request/response schema. It allows different agents to be developed independently, as long as both sides follow the same contract.

Do not pass only a natural-language message such as “Please check the data.” Instead, define a standard data structure that specifies the task ID, sender, receiver, task type, input parameters, and execution result.

Field / 字段Purpose / 作用Example / 示例
task_idIdentifies a task / 标识任务task-001
senderIdentifies the sender / 发送方orchestrator
receiverIdentifies the receiver / 接收方sql_auditor
task_typeDefines the operation / 定义操作类型audit_sql
payloadCarries task inputs / 携带任务输入SQL and table name
statusReports the outcome / 报告执行状态success or failed
resultCarries the output / 携带输出结果Audit findings
Four communication patterns / 四种通信模式
  1. Request–Response / 请求与响应: Agent A sends a request and waits for Agent B’s result.
  2. Parallel execution / 并行执行: The Orchestrator sends independent tasks to multiple agents at the same time.
  3. Message Queue / 消息队列: The sender places a message in a queue, and a worker processes it later.
  4. Shared State / 共享状态:

Retry:如何正确处理失败

Not every error should be treated as retryable.

Failure / 失败Example / 示例Recommended action / 建议处理
Temporary / 临时故障HTTP 429, HTTP 503, transient network errorsRetry with backoff / 退避后重试
Permanent / 永久故障Invalid SQL, invalid input, HTTP 400Stop and report / 停止并报告
Unknown / 未知故障Unexpected exceptionApply a controlled policy; log and alert / 采用受控策略,记录日志并告警

Key Takeaways

要点ENCN
通信契约Use a structured message contract between agents.在 Agent 之间使用结构化消息契约。
统一消息格式Include task ID, sender, receiver, payload, status, and result.包含任务 ID、发送方、接收方、输入、状态和结果。
职责分离Let the Orchestrator coordinate and each agent handle its own logic.让 Orchestrator 负责协调,让每个 Agent 负责自己的业务逻辑。
错误分类Distinguish transient failures from permanent failures.区分临时故障与永久故障。
指数退避Increase the delay between retries.逐渐增加每次重试之间的等待时间。
重试上限Limit attempts and set timeouts.限制尝试次数并设置超时。
随机抖动Add jitter to reduce synchronized retries.添加随机抖动,减少同步重试。
幂等性Prevent repeated operations from causing duplicate side effects.防止重复执行造成重复副作用。
状态持久化Persist workflow state when recovery across process failures is required.需要跨进程故障恢复时,必须持久化工作流状态。
不保证恰好一次Retries alone do not guarantee exactly-once execution.仅靠重试不能保证操作恰好执行一次。

LangGraph Fundamentals: StateGraph core and Conditional Edges

What Is StateGraph?

StateGraph is LangGraph’s graph-based workflow model. It defines a shared state schema, nodes that process the state, and edges that control execution order. A compiled StateGraph becomes a runnable application that can be invoked with input state.
StateGraph 是 LangGraph 基于图的工作流模型。它定义共享状态结构、处理状态的节点,以及控制执行顺序的边。编译后的 StateGraph 会成为一个可执行的应用,可以接收输入状态并运行。

StateGraph itself is neither an LLM nor the Agent’s language model. It is the orchestration structure that controls how the application moves between tasks.
StateGraph 本身不是 LLM,也不是 Agent 的大语言模型。它是编排结构,用于控制应用如何在不同任务之间流转。

You can think of the LLM as the engine that understands and generates content, and StateGraph as the scheduler that controls the overall workflow.
你可以把 LLM 看作负责理解和生成内容的引擎,而把 StateGraph 看作控制整个工作流程的调度系统。

Core Components of StateGraph

State: Stores the current task’s data and processing results. State is the data shared by a workflow during execution.
State(状态):记录当前任务的数据和处理结果。是工作流在执行过程中共享的数据。

Node: Performs a specific task, such as checking data quality. A node is a function that performs a specific task.
Node(节点):执行一个具体任务,例如检查数据质量。是一个执行具体任务的函数。

Edge: Determines where the workflow goes after a node executes. A normal edge represents a fixed execution order.
Edge(边):决定一个节点执行后,流程前往哪里。普通边表示固定的执行顺序。

Conditional Edge: Dynamically chooses the next step based on state or rules.
Conditional Edge(条件边):根据状态或规则,动态选择下一步。根据当前状态决定下一步执行哪个节点。

Graph: Combines state, nodes, and edges into an executable workflow.
Graph(图):把状态、节点和边组合成一个可执行的工作流。

START represents the entry point of the workflow.
START 表示工作流的入口。

END represents the end of the workflow.
END 表示工作流的结束。

compile() converts the constructed graph into an executable Runnable.
compile() 将构建好的图转换成可执行的 Runnable。

ToolNode Integration

In this unit, we will solve a core problem: how to let a LangGraph agent call tools, execute Python functions, and return tool results to the LLM so the LLM can decide what to do next.

What is ToolNode?

ToolNode is a prebuilt component in LangGraph that executes tool calls contained in the current message state and returns tool results as messages.
ToolNode 是 LangGraph 提供的预置组件,用于执行当前消息状态中的工具调用,并将执行结果作为消息返回。

ToolNode is neither an LLM nor a business tool itself. It is a prebuilt LangGraph node responsible for executing tool calls.
ToolNode 不是 LLM,也不是具体的业务工具。它是 LangGraph 中负责执行工具调用的预置节点。

The most important distinction is that the LLM requests tool execution, while ToolNode performs it.
其中最重要的一点是:LLM 负责提出调用请求,ToolNode 负责执行调用。

Human-in-the-loop

The focus of this unit is how to pause an AI agent at a critical step, wait for human review or approval, and then resume execution from where it stopped.
如何让一个 AI Agent 在执行任务的关键步骤暂停,等待人类审核或批准,然后从暂停的位置继续执行。

What is Human-in-the-loop?

Human-in-the-loop (HITL) is a workflow design pattern in which an AI system pauses at a defined decision point and waits for human input before continuing a workflow or performing a consequential action.
Human-in-the-loop 是一种工作流设计模式,AI 系统在预先定义的决策点暂停,等待人类输入,然后才继续工作流或执行具有重要影响的操作。

There are three key points.

  1. A defined pause point / 明确的暂停点: The workflow must know exactly where human input is required. 工作流必须明确知道在哪个步骤需要人类介入。
  2. A human decision / 人类决策: A person can approve, reject, or provide revised input. 人类可以批准、拒绝或提供修改后的输入。
  3. Resumable execution / 可恢复执行: The workflow must retain enough state to continue correctly after the pause. 工作流必须保留足够的状态,以便暂停后正确恢复。

HITL’s core components

  1. StateGraph
    EN: Defines the workflow and its nodes and edges.
    CN: 定义工作流,以及其中的节点和边。
  2. interrupt() 暂停点
    Pauses the workflow and sends a review request to the caller
    暂停工作流,并向调用方发送审核请求。
  3. Checkpointer 保存任务进度的机制。
    Saves workflow state so execution can resume later.
    保存工作流状态,让执行过程可以在之后恢复。
  4. thread_id
    Identifies the execution thread whose state must be resumed.
    标识需要恢复状态的执行线程。
  5. Command(resume=…) 恢复执行
    Supplies the human’s response to the interrupted workflow.
    将人类的回复传回被暂停的工作流。

Capability Design: Platform-Independent Design Principles

What is platform-independent design?

EN: Platform-independent design means designing an AI capability so that its core logic does not depend too heavily on one specific AI provider, model, or framework.

CN: 平台无关设计,就是让 AI 能力的核心逻辑不严重依赖某一家 AI 服务商、某个模型或某个开发框架。

EN: For example, you might build a SQL-generation capability today using Claude, but later want to use OpenAI or Azure AI Foundry without rewriting the entire capability. The goal is not to make every platform identical; it is to isolate platform-specific differences so that the rest of the system remains stable.

CN: 例如,你今天使用 Claude 开发一个 SQL 生成能力,以后可能希望改用 OpenAI 或 Azure AI Foundry,而不必重写整个能力。目标不是让所有平台完全相同,而是隔离各个平台的差异,让系统的其他部分保持稳定。

The six core design principles

These are the principles you should understand.

  1. Separation of concerns: Separate business logic from platform-specific code.
    将业务逻辑与平台专属代码分离。
  2. Stable interfaces: Define clear inputs and outputs for each capability.
    为每个能力定义清晰的输入和输出。
  3. Dependency injection: Pass the model client or service into the capability instead of hard-coding it.
    将模型客户端或服务传入能力,而不是写死在代码中。
  4. Configuration over hard-coding: Put model names, endpoints, and settings in configuration.
    将模型名称、端点和设置放在配置中。
  5. Standards and portability: Use shared formats and protocols where practical, such as JSON and MCP.
    在适用的情况下使用通用格式和协议,例如 JSON 和 MCP。
  6. Testable components: Test core logic independently from the AI provider.
    将核心逻辑与 AI 服务商分开测试。

Key Takeaways

EN: Platform-independent design means building the capability once, defining a stable interface, and isolating provider-specific details behind adapters.

CN: 平台无关设计意味着只构建一次能力、定义稳定的接口,并通过适配器隔离服务商特有的实现细节。

EN: For your goal of becoming an AI/LLM engineer, the key skill is knowing what to keep reusable and what must remain platform-specific.

CN: 对于你成为 AI/LLM 工程师的目标,关键能力是知道哪些部分应该保持可复用,哪些部分必须保留平台特有的实现。

The Basic Concepts of Harness

What is Harness?

An Agent Harness is the engineering system surrounding an LLM that controls how the agent receives a task, reasons, uses tools, observes results, maintains state, handles failures, and decides when to continue or stop.
Agent Harness(Agent运行框架) 是围绕 LLM 建立的一套工程系统,它控制 Agent 如何接收任务、进行推理、调用工具、观察结果、维护状态、处理失败,以及决定什么时候继续、什么时候停止。

The LLM is the brain, while the harness is the operating system and control mechanism around the brain.
LLM 是 大脑,而 Harness 就是围绕这个大脑运行的 操作系统和控制机制。

A model by itself mainly produces the next piece of output. A harness turns that model into a system that can repeatedly act on the real world.
一个单独的模型,本质上主要是在产生下一段输出。而 Harness 把这个模型变成一个能够反复对真实世界采取行动的系统。

Let’s review:

A model is a mathematical system that learns patterns from data and uses those patterns to make predictions, generate outputs, or support decisions.
Model(模型)是一种数学系统。它通过训练数据学习规律,然后利用这些规律进行预测、生成内容或辅助决策。

An AI Agent is a system that uses an AI model to understand a goal, decide what to do, use tools when needed, and take actions until the task is completed or it needs to stop.
AI Agent(智能体)是一种能够理解目标、决定下一步做什么、按需调用工具,并持续执行任务,直到完成任务或需要停止的 AI 系统。

A Large Language Model is an AI model trained on large amounts of text and other data to understand and generate language, follow instructions, and perform reasoning tasks.
LLM 是一种使用大量文本及其他数据训练出来的 AI 模型。它可以理解和生成语言、遵循指令,并完成一些推理任务。

What is an Agentic Loop?

An Agentic Loop is a repeated execution cycle in which the model receives the current state, decides what to do, performs an action such as calling a tool, observes the result, and then decides what to do next.
Agentic Loop(Agent循环) 是一个不断重复的执行周期:模型读取当前状态,决定下一步做什么,执行动作,例如调用 Tool,然后观察结果,再决定下一步做什么。

What Does a Harness Actually Control?

A harness is the runtime/control system that makes the agent actually operate reliably.
Harness 是让 Agent 真正可靠运行起来的 Runtime / Control System。

CapabilityENCN
Model interactionCall the LLM and interpret its output调用 LLM 并解释输出
Tool routingDecide which tool should execute决定执行哪个 Tool
Tool executionExecute the selected tool执行选中的 Tool
StateMaintain current agent state维护 Agent 当前状态
ContextBuild the context sent to the model构建发送给模型的 Context
Loop controlDecide whether to continue决定是否继续
Stop conditionDecide when the agent is finished决定什么时候结束
Error handlingHandle failed actions处理失败动作
RetryRetry recoverable failures重试可恢复的失败
GuardrailsPrevent unsafe actions防止危险动作
Human approvalAsk humans for approval when needed必要时请求人工批准
ObservabilityRecord logs/traces/metrics记录日志、Trace、Metrics
PersistenceSave execution state保存执行状态
RecoveryResume after interruption中断后恢复执行
EvaluationMeasure agent quality衡量 Agent 质量

This is why a harness is much more than a prompt. The harness sits between the application and the model-driven execution process.

┌─────────────────────────────────────────┐
│             User / Application          │
└───────────────────┬─────────────────────┘
                    │
                    ▼
┌─────────────────────────────────────────┐
│              Agent Harness              │
│                                         │
│  State                                   │
│  Context Management                      │
│  Loop Control                            │
│  Tool Routing                            │
│  Retry / Recovery                        │
│  Guardrails                              │
│  Human Approval                          │
│  Observability                           │
│  Persistence                             │
└───────────────────┬─────────────────────┘
                    │
                    ▼
┌─────────────────────────────────────────┐
│                  LLM                    │
│      OpenAI / Claude / DeepSeek         │
└───────────────────┬─────────────────────┘
                    │
             Tool Calls / Decisions
                    │
       ┌────────────┼────────────┐
       ▼            ▼            ▼
    MCP Tool      API Tool     Python
       │            │            │
       └────────────┼────────────┘
                    ▼
             External Systems

Key Takeaways

Three Sentences You Should Remember

  1. An LLM generates intelligence, but a harness turns that intelligence into an executable agent system.
    LLM 产生智能,但是 Harness 把这种智能变成一个可以执行的 Agent 系统。
  2. The core agentic loop is Decide → Act → Observe → Decide → … → Stop.
    Agentic Loop 的核心就是 决策 → 执行 → 观察 → 决策 → …… → 停止。
  3. The model decides what should happen next, while the harness controls how the decision is executed safely and reliably.
    模型决定下一步应该做什么,而 Harness 控制这个决定如何安全、可靠地执行。
要点ENCN
HarnessA control system around the LLM围绕 LLM 的控制系统
LLMProvides intelligence and decisions提供智能和决策
ToolPerforms external actions执行外部动作
Agentic LoopDecide → Act → Observe → Continue/Stop决策 → 执行 → 观察 → 继续/停止
Harness roleControls the entire execution lifecycle控制整个执行生命周期
StateMaintains what the agent currently knows保存 Agent 当前状态
ContextProvides relevant information to the model给模型提供相关信息
Tool routingRoutes model requests to tools将模型请求路由到 Tool
RetryRecovers from recoverable failures从可恢复失败中恢复
GuardrailLimits unsafe or invalid behavior限制危险或无效行为
ObservabilityMakes agent behavior inspectable让 Agent 行为可观察
RecoveryAllows interrupted work to continue允许中断任务继续
FrameworkDevelopment abstraction开发抽象
HarnessRuntime/control systemRuntime / 控制系统
Core loopLLM → Tool → Result → LLMLLM → Tool → Result → LLM
Key ideaThe model decides; the harness controls; tools act.模型负责决策;Harness 负责控制;Tool 负责执行。

Skill Composition: Multi-Skill Collaboration + MCP Composition

Today we move to Multi-Skill Collaboration + MCP Composition, which is important because it connects the Skill design capabilities with MCP Tools / Servers.

What does “Skill Composition” mean?

什么叫 Skill Composition?Composition means combining multiple specialized capabilities to accomplish a larger task.
Composition 的意思就是把多个专业能力组合起来完成一个更大的任务。

Multi-Skill = an Agent has multiple specialized capabilities and selects and combines them according to the task.
Multi-Skill = 一个 Agent 拥有多个专业能力,并根据任务选择和组合这些能力。

We have already learned that a Skill is a capability/work procedure, while an MCP Tool is an external execution capability.
Skill 是“能力/工作方法”,MCP Tool 是“外部执行能力”。

This topic addresses a practical problem: a real Agent cannot realistically have only one capability or call only one Tool.
一个真实 Agent 不可能只会一种能力,也不可能只调用一个 Tool。

MCP Composition = Skills do not implement every external operation themselves; they obtain external capabilities such as databases, APIs, filesystems, and Databricks through MCP.
MCP Composition = Skill 不直接实现所有外部操作,而是通过 MCP 获得数据库、API、文件系统、Databricks 等外部能力。

So, we can simply think this:

Skill = “我知道怎么做”
Skill = “I know how to do it.”

MCP Tool = “我有办法真正去做”
MCP Tool = “I have the ability to actually do it.”

LLM/Agent = “我决定什么时候做什么”
LLM/Agent = “I decide what to do and when to do it.”

ConceptEnglish中文
SkillDefines how to accomplish a capability定义如何完成一个能力
ToolDefines an executable operation定义一个可以执行的操作
AgentDecides what to do决定做什么
MCPProvides standardized access to external capabilities提供标准化的外部能力访问方式

Think about it like a human organization.
可以把它想象成人类组织。

Agent = Manager
Agent = 经理

Skill = Expert’s operating procedure
Skill = 专家的工作方法

Tool = Equipment the expert can use
Tool = 专家可以使用的工具

MCP = Standard interface connecting the expert to external equipment
MCP = 连接专家与外部工具的标准接口

Imagine that you have an AI Data Engineering Team, there are three experts in this team. They are: SQL Developer, Data Quality Engineer and Pipeline Auditor.

CapabilitiesSkillMCP
SQL DeveloperSQL Generation SkillDatabricks MCP
Data Quality EngineerDQ Report SkillDatabricks MCP
Pipeline AuditorPipeline Audit SkillDatabricks MCP

The team receiced this “Inspect the sales_orders pipeline, identify data-quality issues, generate SQL validations, and give me a report.”
“检查 sales_orders pipeline,找出数据质量问题,生成 SQL 验证,并给我一份报告。”

Agent may work this way:
User Request
│
▼
Agent
│
├── Pipeline Audit Skill
│ │
│ └── MCP → Databricks
│
├── SQL Generator Skill
│ │
│ └── MCP → Databricks
│
└── DQ Report Skill
│
└── MCP → Databricks

The Agent does not put all logic into one giant Skill. Instead, each Skill focuses on one clearly defined responsibility.
Agent 不是把所有逻辑塞进一个巨大 Skill。而是让每个 Skill 专注一个明确的职责。

Who should coordinate the Skills?

谁负责协调这些 Skill?Normally, Skill A should not directly control Skill B. Instead, the Agent or Orchestrator should coordinate them.
通常情况下,Skill A 不应该直接控制 Skill B。相反,应该由 Agent 或 Orchestrator 来协调它们。

             Agent
               │
   ┌───────────┼───────────┐
   │           │           │
   ▼           ▼           ▼
Skill A     Skill B     Skill C

The Agent decides which capability is needed. The Skill provides the instructions and workflow for that capability. This gives us a clean separation of responsibilities.
Agent 决定需要哪个能力。Skill 提供该能力所需要的 Instructions 和 Workflow。这样就实现了清晰的职责分离。

Skill Composition 的核心思想

Why we need Multi-Skill? A Skill can eventually contain thousands of lines of instructions. The LLM may have to process a large amount of information unrelated to the current task. This reduces focus, maintainability, and reliability.

First principle: One Skill should have one coherent capability
第一个原则:一个 Skill 应该负责一个内聚的能力

A Skill should have a clear purpose and a reasonably narrow scope.
一个 Skill 应该有明确的目的和相对清晰的职责范围。

A simple MCP Tool

from mcp.server.fastmcp import FastMCP


# Create the MCP Server.
# 创建 MCP Server。
#
# The MCP Server exposes external capabilities to an Agent.
# MCP Server 把外部系统能力暴露给 Agent。
mcp = FastMCP("Databricks MCP Server")


@mcp.tool()
def execute_sql(sql: str) -> str:
    """
    Execute SQL in Databricks.
    在 Databricks 中执行 SQL。
    
    This function represents an executable operation.
    这个函数代表一个可以执行的操作。
    """

    # In a real implementation, this section would connect
    # to Databricks and execute the SQL statement.
    # 在真实实现中,这里会连接 Databricks 并执行 SQL。

    # We return a simulated result for learning purposes.
    # 为了教学目的,这里返回一个模拟结果。
    return f"SQL executed: {sql}"


@mcp.tool()
def get_table_schema(table_name: str) -> str:
    """
    Retrieve table schema.
    获取表结构。
    """

    # In a real system, this would query Databricks metadata.
    # 在真实系统中,这里应该查询 Databricks metadata。
    return (
        f"Schema for {table_name}: "
        "customer_id, order_id, order_date, amount"
    )


# Start the MCP server.
# 启动 MCP Server。
if __name__ == "__main__":
    mcp.run()

Skill Testing and Iteration

This section is very important. provious we focused on how to write a Skill. we need answer a very simple question: is the Skill you wrote actually good?

Now, we focuse on how to prove whether the Skill works well and how to iteratively improve it. This is where we start moving from Prompt/Skill authoring into AI Engineering quality engineering.

For example, the SOP (Standard Operating Procedure) says:

Data Quality Report Skill

  1. Check row count.
  2. Check NULL values.
  3. Check duplicate records.
  4. Check data quality rules.
  5. Generate a report.

How do you know this SOP is actually good? You should test it.

A Test Case is basically an “exam question.” we have customer_id
1001
1002
1003
1003
<– duplicated
1004
NULL <– null

Now let agent use the Skill to Test.

Actual Result:
Row Count = 6
NULL = YES
Duplicate = YES

so result PASS.


if Agent return
Row Count = 6
NULL = NO
Duplicate = YES

so result FAIL

We should perpare multiple test case, because a Skill can encounter many different situations.

Key Takeaways

要点ENCN
Skill TestingTest whether a Skill behaves correctly测试 Skill 是否按照要求正确工作
Behavioral TestingValidate what the Skill actually does验证 Skill 实际执行了什么
Quality EvaluationEvaluate output quality, not just existence评价输出质量,而不仅仅是有没有输出
Golden Test CasesUse stable cases to validate behavior使用稳定的标准案例验证行为
Regression TestingMake sure old behavior does not break确保修改后原来的功能没有坏
Root Cause AnalysisIdentify which layer caused the failure判断失败到底是哪一层造成的
IterationTest → diagnose → modify → retest测试 → 定位 → 修改 → 再测试
AI EngineeringTreat Skill quality as an engineering problem把 Skill 质量当成工程问题处理
E07 vs G02E07 tests a Skill; G02 systematizes Golden Dataset evaluationE07 测试具体 Skill;G02 系统化构建 Golden Dataset