最近在折腾Azure AI Foundry时,发现它现在可以通过OpenAI的Responses API无缝集成Model Context Protocol(MCP)服务器。以前要自己写MCP客户端,挺麻烦的,现在直接配置就能用,开发Agentic AI方案变得简单多了。

场景:时尚趋势发现

举个例子,假如你是时尚分析师,只需要在命令行里输入类似“可持续时尚的最新趋势”这样的查询,系统就能自动帮你搞定后续所有流程:

  1. 自动网页导航:Agent会打开Pinterest,自动找到搜索框并输入查询。
  2. 智能内容发现:系统会识别并点击趋势图片,进入详情页。
  3. 内容分析:用计算机视觉分析时尚元素、颜色、图案和设计趋势。
  4. 智能整理:把分析结果汇总成专业的Markdown报告。
  5. 上下文存储:系统还能自动判断是否需要把报告存到云端,比如Azure Blob Storage。

技术能力拆解

整个体验背后,其实是多个AI模型的协作:

  • Pinterest导航:CUA模型能像人一样“看懂”网页布局,精准找到搜索框和导航元素。
  • 搜索结果处理:不用传统的DOM解析,Agent直接用视觉理解识别图片,计算点击坐标。
  • 内容分析:每个趋势图片都用GPT-4o的视觉能力做详细分析,提取时尚元素、季节趋势等。
  • 自动决策:Agent能判断哪些信息需要保存,并自动调用云存储。

技术架构一览

整体架构大致如下:

┌─────────────────────────────────────────────────────────────────┐
│                     Azure AI Foundry                            │
│  ┌─────────────────────────────────────────────────────────┐    │
│  │              Responses API                              │    │
│  │  ┌─────────────┐  ┌─────────────┐  ┌─────────────────┐  │    │
│  │  │ CUA Model   │  │ GPT-4o      │  │ Built-in MCP    │  │    │
│  │  │ (Interface) │  │ (Content)   │  │ Client          │  │    │
│  │  └─────────────┘  └─────────────┘  └─────────────────┘  │    │
│  └─────────────────────────────────────────────────────────┘    │
└─────────────────────────────────────────────────────────────────┘
                               │
                               ▼
         ┌─────────────────────────────────────────┐
         │        Function Calling Layer           │
         │     (Workflow Orchestration)            │
         └─────────────────────────────────────────┘
                               │
                               ▼
    ┌─────────────────┐                 ┌──────────────────┐
    │   Playwright    │◄──────────────► │ Trends Compiler  │
    │   Automation    │                 │    Engine        │
    └─────────────────┘                 └──────────────────┘
                               │
                               ▼
                    ┌─────────────────────┐
                    │   Azure Blob        │
                    │   Storage (MCP)     │
                    └─────────────────────┘

各技术模块说明

  • Responses API:负责智能决策,判断什么时候用CUA模型做网页操作,什么时候用MCP存储数据。
  • CUA模型:专门训练来理解网页结构,能给出精确的点击坐标。
  • Playwright自动化:把CUA模型的“看法”转化为实际的浏览器操作,比如点击、输入、截图等。
  • GPT-4o视觉模型:分析图片内容,提取时尚趋势和语义信息。
  • MCP集成:Agent能自动判断何时需要存储数据,通过内置MCP客户端直接和Azure Blob Storage通信,无需自己写存储逻辑。

代码片段与智能决策

主流程在app.py里,核心逻辑大致如下:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
async def main() -> str:
    conversation_history = []
    generated_reports = []
    
    while True:
        user_query = input("Enter your query for fashion trends:->  ")
        new_user_message = {
            "role": "user",
            "content": [{"type": "input_text", "text": user_query}],
        }
        conversation_history.append(new_user_message)
        
        response = ai_client.create_app_response(
            instructions=instructions,
            conversation_history=conversation_history,
            mcp_server_url=config.mcp_server_url,
            available_functions=available_functions,
        )
        
        for output in response.output:
            if output.type == "function_call":
                function_to_call = available_functions[output.name]
                function_args = json.loads(output.arguments)
                function_response = await function_to_call(**function_args)
            elif output.type == "mcp_tool_call":
                print(f"MCP tool call: {output.name}")

Agent会根据上下文自动选择是编译趋势报告还是存储数据,整个过程无需人工干预。

趋势编译器的自动化流程

compiler.py里的TrendsCompiler类实现了多步自验证的自动化:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class TrendsCompiler:
    async def compile_trends(self, user_query: str) -> str:
        async with LocalPlaywrightComputer() as computer:
            state = {"trends_compiled": False}
            step = 0
            while not state["trends_compiled"]:
                try:
                    if step == 0:
                        await self._launch_pinterest(computer)
                        step += 1
                    elif step == 1:
                        coordinates = await self._search_and_get_coordinates(computer, user_query)
                        if coordinates:
                            step += 1
                    elif step == 2:
                        await self._process_image_results(computer, coordinates, user_query)
                        markdown_report = await self._generate_markdown_report(user_query)
                        state["trends_compiled"] = True
                except Exception as e:
                    print(f"Autonomous error handling in step {step}: {e}")
                    state["trends_compiled"] = True
            return markdown_report

每一步都自检,遇到异常也能自动处理,完全不需要人工介入。

Pinterest视觉坐标提取

CUA模型能直接“看”截图,提取图片的坐标:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
async def _detect_search_results(self, computer) -> List[Tuple[int, int, int, int]]:
    screenshot_bytes = await computer.screenshot()
    screenshot_b64 = base64.b64encode(screenshot_bytes).decode()
    prompt = """
    Analyze this Pinterest search results page and identify all trend/fashion 
    images displayed. For each image, provide the exact bounding box coordinates 
    in the format: <click>x1,y1,x2,y2</click>
    Focus on the main content images, not navigation or advertisement elements.
    """
    response = await self.ai_client.create_cua_response(
        prompt=prompt,
        screenshot_b64=screenshot_b64
    )
    coordinates = self.coordinate_parser.extract_coordinates(response.content)
    print(f"CUA model identified {len(coordinates)} image regions")
    return coordinates

再通过中心点算法,确保点击精准:

1
2
3
4
5
6
7
def calculate_centers(self, coordinates: List[Tuple[int, int, int, int]]) -> List[Tuple[int, int]]:
    centers = []
    for x1, y1, x2, y2 in coordinates:
        center_x = (x1 + x2) // 2
        center_y = (y1 + y2) // 2
        centers.append((center_x, center_y))
    return centers

模型分工与协作

  • CUA模型:负责“点哪里”“怎么导航”。
  • GPT-4o:负责“这是什么”“有什么意义”。
  • 协同智能:各司其职,互补长短。

自动生成Markdown报告

报告自动结构化,内容丰富:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
async def _generate_markdown_report(self, user_query: str) -> str:
    if not self.image_analyses:
        return "No trend data collected for analysis."
    report_sections = [
        f"# Fashion Trends Analysis: {user_query}",
        f"*Generated on {datetime.now().strftime('%B %d, %Y')}*",
        "",
        "## Executive Summary",
        await self._generate_executive_summary(),
        "",
        "## Detailed Trend Analysis"
    ]
    for idx, analysis in enumerate(self.image_analyses, 1):
        trend_section = [
            f"### Trend Item {idx}",
            analysis.get('analysis', 'No analysis available'),
            f"*Analysis timestamp: {analysis.get('timestamp', 'Unknown')}*",
            ""
        ]
        report_sections.extend(trend_section)
    report_sections.extend([
        "## Trend Synthesis and Insights",
        await self._generate_trend_synthesis(),
        "",
        "## Recommendations",
        await self._generate_recommendations()
    ])
    return "\n".join(report_sections)

MCP一键集成

无需自己写MCP客户端,配置好就能用:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
def create_app_tools(self, mcp_server_url: str, available_functions: Dict[str, Any]) -> List[Dict[str, Any]]:
    tools = [
        {
            "type": "mcp",
            "server_label": "azure-storage-mcp-server",
            "server_url": mcp_server_url,
            "require_approval": "never",
            "allowed_tools": ["create_container", "list_containers", "upload_blob"],
        }
    ]
    return tools

总结

通过Azure AI Foundry的MCP一键集成、CUA模型、GPT-4o和Playwright自动化,完全可以实现无需人工干预的Agentic AI应用。整个流程从网页导航、内容分析到云端存储,全自动完成,极大提升了开发效率和智能化水平。

相关代码和Demo可参考CUA-Trends-Compiler GitHub仓库


如需进一步了解Agentic AI和自动化方案,建议直接体验Azure AI Foundry的MCP集成和Computer Use能力,开启你的智能自动化之旅。