Condividi tramite


Chiamata alla funzione degli agenti di intelligenza artificiale di Azure

Gli agenti di intelligenza artificiale di Azure supportano le chiamate di funzione, che consentono di descrivere la struttura delle funzioni a un assistente e quindi di restituire le funzioni che devono essere chiamate insieme ai relativi argomenti.

Nota

Le esecuzioni scadono dieci minuti dopo la creazione. Assicurarsi di inviare gli output dello strumento prima della scadenza.

Supporto per l'utilizzo

Supporto di Azure ai foundry Python SDK SDK per C# JavaScript SDK REST API Configurazione dell'agente di base Configurazione dell'agente standard
✔️ ✔️ ✔️ ✔️ ✔️ ✔️

Definire una funzione che l'agente deve chiamare

Per iniziare, definire una funzione per chiamare l'agente. Quando si crea una funzione per chiamare un agente, viene descritta la relativa struttura con i parametri necessari in una docstring. Includere tutte le definizioni di funzione in un singolo file, user_functions.py che è quindi possibile importare nello script principale.

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,
}

Vedere il file Python in GitHub per un esempio di una serie completa di definizioni di funzione. Questo file viene definito come user_functions.py nell'esempio seguente.

Creare un client e un agente

Nell'esempio seguente viene creato un client e viene definito un toolset oggetto che verrà usato per elaborare le funzioni definite in user_functions.

toolset: quando si usa il parametro del set di strumenti, si forniscono non solo le definizioni e le descrizioni delle funzioni, ma anche le relative implementazioni. L'SDK eseguirà queste funzioni all'interno di create_and_run_process o streaming. Queste funzioni verranno richiamate in base alle relative definizioni.

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)

agent = project_client.agents.create_agent(
    model="gpt-4o-mini", name="my-agent", instructions="You are a weather bot. Use the provided functions to help answer questions.", toolset=toolset
)
print(f"Created agent, ID: {agent.id}")

Creare un thread

# 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}")

Creare un'esecuzione e controllare l'output

# Create and process agent run in thread with tools
run = project_client.agents.create_and_process_run(thread_id=thread.id, agent_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}")

Vedi anche