Nota
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare ad accedere o modificare le directory.
L'accesso a questa pagina richiede l'autorizzazione. È possibile provare a modificare le directory.
Microsoft Agent Framework supporta tre tipi di client OpenAI di Azure distinti, ognuno destinato a una superficie API diversa con diverse funzionalità degli strumenti:
| Tipo di client | API | Ideale per |
|---|---|---|
| Completamento conversazione | API di completamento chat | Agenti semplici, supporto generale del modello |
| Risposte | API delle risposte | Agenti completi con strumenti ospitati (interprete del codice, ricerca di file, ricerca Web, MCP ospitato) |
| Assistenti | Assistenti API | Agenti gestiti dal server con interprete del codice e ricerca di file |
Suggerimento
Per gli equivalenti OpenAI diretti (OpenAIChatClient, OpenAIResponsesClient, OpenAIAssistantsClient), vedere la pagina del provider OpenAI. Il supporto dello strumento è identico.
Come iniziare
Aggiungere i pacchetti NuGet necessari al progetto.
dotnet add package Azure.AI.OpenAI --prerelease
dotnet add package Azure.Identity
dotnet add package Microsoft.Agents.AI.OpenAI --prerelease
Tutti i tipi di client OpenAI di Azure iniziano creando un oggetto AzureOpenAIClient:
using System;
using Azure.AI.OpenAI;
using Azure.Identity;
using Microsoft.Agents.AI;
AzureOpenAIClient client = new AzureOpenAIClient(
new Uri("https://<myresource>.openai.azure.com"),
new DefaultAzureCredential());
Avviso
DefaultAzureCredential è utile per lo sviluppo, ma richiede un'attenta considerazione nell'ambiente di produzione. Nell'ambiente di produzione prendere in considerazione l'uso di credenziali specifiche ,ad esempio ManagedIdentityCredential, per evitare problemi di latenza, probe di credenziali indesiderate e potenziali rischi per la sicurezza dai meccanismi di fallback.
Client per il completamento della chat
Il client di completamento della chat offre un modo semplice per creare agenti usando l'API ChatCompletion.
var chatClient = client.GetChatClient("gpt-4o-mini");
AIAgent agent = chatClient.AsAIAgent(
instructions: "You are good at telling jokes.",
name: "Joker");
Console.WriteLine(await agent.RunAsync("Tell me a joke about a pirate."));
Strumenti supportati: Strumenti per le funzioni, ricerca Web, strumenti MCP locali.
Risposte del cliente
Il client Risposte offre il supporto più ricco di strumenti, tra cui interprete del codice, ricerca di file, ricerca Web e MCP ospitato.
var responsesClient = client.GetResponseClient("gpt-4o-mini");
AIAgent agent = responsesClient.AsAIAgent(
instructions: "You are a helpful coding assistant.",
name: "CodeHelper");
Console.WriteLine(await agent.RunAsync("Write a Python function to sort a list."));
Strumenti supportati: Strumenti per le funzioni, approvazione degli strumenti, interprete del codice, ricerca di file, ricerca Web, MCP ospitato, strumenti MCP locali.
Assistenti alla clientela
Il client Assistants crea agenti gestiti dal server con interprete di codice predefinito e ricerca di file.
var assistantsClient = client.GetAssistantClient();
AIAgent agent = assistantsClient.AsAIAgent(
instructions: "You are a data analysis assistant.",
name: "DataHelper");
Console.WriteLine(await agent.RunAsync("Analyze trends in the uploaded data."));
Strumenti supportati: Strumenti per le funzioni, interprete del codice, ricerca di file, strumenti MCP locali.
Strumenti per le funzioni
È possibile fornire strumenti di funzione personalizzati a qualsiasi agente OpenAI di Azure:
using System.ComponentModel;
using Microsoft.Extensions.AI;
[Description("Get the weather for a given location.")]
static string GetWeather([Description("The location to get the weather for.")] string location)
=> $"The weather in {location} is cloudy with a high of 15°C.";
AIAgent agent = new AzureOpenAIClient(
new Uri(endpoint),
new DefaultAzureCredential())
.GetChatClient(deploymentName)
.AsAIAgent(instructions: "You are a helpful assistant", tools: [AIFunctionFactory.Create(GetWeather)]);
Console.WriteLine(await agent.RunAsync("What is the weather like in Amsterdam?"));
Risposte in streaming
await foreach (var update in agent.RunStreamingAsync("Tell me a joke about a pirate."))
{
Console.Write(update);
}
Suggerimento
Uso dell'agente
Tutti e tre i tipi di client producono uno standard AIAgent che supporta le stesse operazioni dell'agente (streaming, thread, middleware).
Per altre informazioni, vedere le esercitazioni introduttive.
Installazione
pip install agent-framework --pre
Impostazione
Ogni tipo di client usa variabili di ambiente diverse:
Completamento chat
AZURE_OPENAI_ENDPOINT="https://<myresource>.openai.azure.com"
AZURE_OPENAI_CHAT_DEPLOYMENT_NAME="gpt-4o-mini"
Responses
AZURE_OPENAI_ENDPOINT="https://<myresource>.openai.azure.com"
AZURE_OPENAI_RESPONSES_DEPLOYMENT_NAME="gpt-4o-mini"
Assistants
AZURE_OPENAI_ENDPOINT="https://<myresource>.openai.azure.com"
AZURE_OPENAI_CHAT_DEPLOYMENT_NAME="gpt-4o-mini"
Facoltativamente, è anche possibile impostare:
AZURE_OPENAI_API_VERSION="2024-10-21" # Default API version
AZURE_OPENAI_API_KEY="<your-api-key>" # If not using Azure CLI authentication
Tutti i client usano le credenziali di Azure per l'autenticazione. L'approccio più semplice è AzureCliCredential dopo aver eseguito az login.
Client per il completamento della chat
AzureOpenAIChatClient usa l'API di completamento chat, l'opzione più semplice con ampio supporto per i modelli.
import asyncio
from agent_framework.azure import AzureOpenAIChatClient
from azure.identity import AzureCliCredential
async def main():
agent = AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
name="Joker",
instructions="You are good at telling jokes.",
)
result = await agent.run("Tell me a joke about a pirate.")
print(result)
asyncio.run(main())
Strumenti supportati: Strumenti per le funzioni, ricerca Web, strumenti MCP locali.
Risposte del cliente
AzureOpenAIResponsesClient usa l'API Risposte, l'opzione più ricca di funzionalità con strumenti ospitati.
import asyncio
from agent_framework.azure import AzureOpenAIResponsesClient
from azure.identity import AzureCliCredential
async def main():
agent = AzureOpenAIResponsesClient(credential=AzureCliCredential()).as_agent(
name="FullFeaturedAgent",
instructions="You are a helpful assistant with access to many tools.",
)
result = await agent.run("Write and run a Python script that calculates fibonacci numbers.")
print(result)
asyncio.run(main())
Risposte del client con endpoint del progetto Azure AI Foundry
AzureOpenAIResponsesClient può anche essere creato da un endpoint del progetto Azure AI Foundry:
from agent_framework.azure import AzureOpenAIResponsesClient
from azure.identity import AzureCliCredential
client = AzureOpenAIResponsesClient(
project_endpoint="https://<your-project>.services.ai.azure.com/api/projects/<project-id>",
deployment_name="gpt-4o-mini",
credential=AzureCliCredential(),
)
agent = client.as_agent(
name="FoundryResponsesAgent",
instructions="You are a helpful assistant.",
)
Strumenti supportati: Strumenti per le funzioni, approvazione degli strumenti, interprete del codice, ricerca di file, ricerca Web, MCP ospitato, strumenti MCP locali.
Strumenti Ospitati con Client di Risposte
Il client Risposte fornisce get_*_tool() metodi per ogni tipo di strumento ospitato:
async def hosted_tools_example():
client = AzureOpenAIResponsesClient(credential=AzureCliCredential())
code_interpreter = client.get_code_interpreter_tool()
web_search = client.get_web_search_tool()
file_search = client.get_file_search_tool(vector_store_ids=["vs_abc123"])
mcp_tool = client.get_mcp_tool(
name="GitHub",
url="https://api.githubcopilot.com/mcp/",
approval_mode="never_require",
)
agent = client.as_agent(
name="PowerAgent",
instructions="You have access to code execution, web search, files, and GitHub.",
tools=[code_interpreter, web_search, file_search, mcp_tool],
)
result = await agent.run("Search the web for Python best practices, then write a summary.")
print(result)
Assistenti alla clientela
AzureOpenAIAssistantsClient usa l'API Assistants : agenti gestiti dal server con interprete di codice e ricerca di file predefiniti. Si noti il gestore del contesto per la gestione automatica del async with ciclo di vita dell'assistente.
import asyncio
from agent_framework.azure import AzureOpenAIAssistantsClient
from azure.identity import AzureCliCredential
async def main():
async with AzureOpenAIAssistantsClient(credential=AzureCliCredential()).as_agent(
name="DataAnalyst",
instructions="You analyze data using code execution.",
) as agent:
result = await agent.run("Calculate the first 20 prime numbers.")
print(result)
asyncio.run(main())
Strumenti supportati: Strumenti per le funzioni, interprete del codice, ricerca di file, strumenti MCP locali.
Funzionalità comuni
Tutti e tre i tipi di client supportano queste funzionalità dell'agente standard:
Strumenti per le funzioni
from agent_framework import tool
@tool
def get_weather(location: str) -> str:
"""Get the weather for a given location."""
return f"The weather in {location} is sunny, 25°C."
async def example():
agent = AzureOpenAIResponsesClient(credential=AzureCliCredential()).as_agent(
instructions="You are a weather assistant.",
tools=get_weather,
)
result = await agent.run("What's the weather in Tokyo?")
print(result)
Conversazioni a più turni
async def thread_example():
agent = AzureOpenAIResponsesClient(credential=AzureCliCredential()).as_agent(
instructions="You are a helpful assistant.",
)
session = await agent.create_session()
result1 = await agent.run("My name is Alice", session=session)
print(result1)
result2 = await agent.run("What's my name?", session=session)
print(result2) # Remembers "Alice"
Trasmissione in diretta
async def streaming_example():
agent = AzureOpenAIResponsesClient(credential=AzureCliCredential()).as_agent(
instructions="You are a creative storyteller.",
)
print("Agent: ", end="", flush=True)
async for chunk in agent.run("Tell me a short story about AI.", stream=True):
if chunk.text:
print(chunk.text, end="", flush=True)
print()
Uso dell'agente
Tutti i tipi di client producono uno standard Agent che supporta le stesse operazioni.
Per altre informazioni, vedere le esercitazioni introduttive.