你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

Azure AI 代理函数调用

Azure AI 代理支持函数调用,这允许你向助手描述函数的结构,然后返回需要调用的函数及其参数。

注意

创建 10 分钟后运行将过期。 请务必在过期之前提交工具输出。

定义代理要调用的函数

首先定义代理要调用的函数。 创建代理要调用的函数时,可以使用 docstring 中的任何必需参数来描述其结构。 将所有函数定义包含在单个文件 user_functions.py 中,然后可以将其导入到主脚本中。

import json
import datetime
from typing import Any, Callable, Set, Dict, List, Optional

def fetch_weather(location: str) -> str:
    """
    Fetches the weather information for the specified location.

    :param location (str): The location to fetch weather for.
    :return: Weather information as a JSON string.
    :rtype: str
    """
    # In a real-world scenario, you'd integrate with a weather API.
    # Here, we'll mock the response.
    mock_weather_data = {"New York": "Sunny, 25°C", "London": "Cloudy, 18°C", "Tokyo": "Rainy, 22°C"}
    weather = mock_weather_data.get(location, "Weather data not available for this location.")
    weather_json = json.dumps({"weather": weather})
    return weather_json

    # Statically defined user functions for fast reference
user_functions: Set[Callable[..., Any]] = {
    fetch_weather,
}

有关完整的函数定义系列的示例,请参阅 GitHub 上的 python 文件。 此文件在下面的示例中称为 user_functions.py

创建 客户端

在下面的示例中,我们将创建一个客户端并定义一个 toolset,它将用于处理在 user_functions 中定义的函数。

toolset:使用工具集参数时,不仅提供函数定义和说明,而且还提供其实现。 SDK 将在create_and_run_process 或流式传输中执行这些函数。 将根据这些函数的定义调用这些函数。

import os
from azure.ai.projects import AIProjectClient
from azure.identity import DefaultAzureCredential
from azure.ai.projects.models import FunctionTool, ToolSet
from user_functions import user_functions # user functions which can be found in a user_functions.py file.

# Create an Azure AI Client from a connection string, copied from your Azure AI Foundry project.
# It should be in the format "<HostName>;<AzureSubscriptionId>;<ResourceGroup>;<HubName>"
# Customers need to login to Azure subscription via Azure CLI and set the environment variables

project_client = AIProjectClient.from_connection_string(
    credential=DefaultAzureCredential(),
    conn_str=os.environ["PROJECT_CONNECTION_STRING"],
)

# Initialize agent toolset with user functions
functions = FunctionTool(user_functions)
toolset = ToolSet()
toolset.add(functions)

提交函数输出


# Create agent with toolset and process a run

agent = project_client.agents.create_agent(
    model="gpt-4o-mini", name="my-agent", instructions="You are a helpful agent", toolset=toolset
)
print(f"Created agent, ID: {agent.id}")

创建线程

# Create thread for communication
thread = project_client.agents.create_thread()
print(f"Created thread, ID: {thread.id}")

# Create message to thread
message = project_client.agents.create_message(
    thread_id=thread.id,
    role="user",
    content="Hello, send an email with the datetime and weather information in New York?",
)
print(f"Created message, ID: {message.id}")

创建运行并检查输出

# Create and process agent run in thread with tools
run = project_client.agents.create_and_process_run(thread_id=thread.id, assistant_id=agent.id)
print(f"Run finished with status: {run.status}")

if run.status == "failed":
    print(f"Run failed: {run.last_error}")

# Delete the agent when done
project_client.agents.delete_agent(agent.id)
print("Deleted agent")

# Fetch and log all messages
messages = project_client.agents.list_messages(thread_id=thread.id)
print(f"Messages: {messages}")

另请参阅