Passaggio 1: Il primo agente

Creare un agente e ottenere una risposta, in poche righe di codice.

dotnet add package Microsoft.Agents.AI.Foundry --prerelease

Creare l'agente:

using System;
using Azure.AI.Projects;
using Azure.Identity;
using Microsoft.Agents.AI;

var endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT")
    ?? throw new InvalidOperationException("Set AZURE_OPENAI_ENDPOINT");
var deploymentName = Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT_NAME") ?? "gpt-4o-mini";

AIAgent agent = new AIProjectClient(new Uri(endpoint), new DefaultAzureCredential())
    .AsAIAgent(
        model: deploymentName,
        instructions: "You are a friendly assistant. Keep your answers brief.",
        name: "HelloAgent");

Avvertimento

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.

Eseguilo:

Console.WriteLine(await agent.RunAsync("What is the largest city in France?"));

In alternativa, trasmettere la risposta:

await foreach (var update in agent.RunStreamingAsync("Tell me a one-sentence fun fact."))
{
    Console.Write(update);
}

Tip

Vedere qui per un'applicazione di esempio eseguibile completa.

pip install agent-framework-foundry azure-identity

Il pacchetto agent-framework-foundry installa agent-framework-core con l'integrazione di Microsoft Foundry. Il agent-framework metapacchetto installa agent-framework-coreanche , insieme a molte altre integrazioni facoltative.

Accedi con il interfaccia della riga di comando di Azure eseguendo az login. Nell'esempio seguente, sostituire project_endpoint con l'endpoint del progetto Microsoft Foundry e model con il nome della distribuzione del modello.

Salvare l'esempio completo come hello_agent.py:

import asyncio

from agent_framework import Agent
from agent_framework.foundry import FoundryChatClient
from azure.identity import AzureCliCredential


async def main() -> None:
    agent = Agent(
        client=FoundryChatClient(
            project_endpoint="https://your-account.services.ai.azure.com/api/projects/your-project",
            model="gpt-6-luna",
            credential=AzureCliCredential(),
        ),
        instructions="You are a friendly assistant. Keep your answers brief.",
    )
    print(await agent.run("What is the largest city of France?"))


if __name__ == "__main__":
    asyncio.run(main())

Esegui l'esempio:

python hello_agent.py

Annotazioni

Agent Framework non carica .env automaticamente i file. Per usare un .env file per la configurazione, chiamare load_dotenv() all'inizio dello script:

from dotenv import load_dotenv
load_dotenv()

In alternativa, impostare le variabili di ambiente direttamente nella shell o nell'IDE. Per informazioni dettagliate, vedere la nota sulla migrazione delle impostazioni .

Tip

Vedere l'esempio completo per il file eseguibile completo.

go get github.com/microsoft/agent-framework-go

Creare l'agente:

package main

import (
    "context"
    "fmt"
    "os"

    "github.com/microsoft/agent-framework-go/agent"
    "github.com/microsoft/agent-framework-go/provider/foundryprovider"

    "github.com/Azure/azure-sdk-for-go/sdk/azidentity"
)

func main() {
    endpoint := os.Getenv("FOUNDRY_PROJECT_ENDPOINT")
    model := os.Getenv("FOUNDRY_MODEL")

    token, err := azidentity.NewDefaultAzureCredential(nil)
    if err != nil {
        panic(err)
    }

    a := foundryprovider.NewAgent(
        endpoint,
        token,
        foundryprovider.ModelDeployment(model),
        foundryprovider.AgentConfig{
            Instructions: "You are a friendly assistant. Keep your answers brief.",
            Config: agent.Config{
                Name: "HelloAgent",
            },
        },
    )

Avvertimento

azidentity.NewDefaultAzureCredential è 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 azidentity.NewManagedIdentityCredential, per evitare problemi di latenza, probe di credenziali indesiderate e potenziali rischi per la sicurezza dai meccanismi di fallback.

Eseguilo:

    ctx := context.Background()

    resp, err := a.RunText(ctx, "What is the largest city in France?").Collect()
    fmt.Println(resp, err)

In alternativa, trasmettere la risposta:

    for update, err := range a.RunText(ctx, "Tell me a one-sentence fun fact.", agent.Stream(true)) {
        if err != nil {
            panic(err)
        }
        fmt.Print(update)
    }
}

Tip

Vedere l'esempio completo per il file eseguibile completo.

Passaggi successivi

Approfondimento:

  • Agenti : informazioni sull'architettura dell'agente
  • Provider : vedere tutti i provider supportati