Nuta
Dostęp do tej strony wymaga autoryzacji. Możesz spróbować się zalogować lub zmienić katalog.
Dostęp do tej strony wymaga autoryzacji. Możesz spróbować zmienić katalogi.
Program Microsoft Agent Framework obsługuje tworzenie agentów korzystających z usługi Azure AI Foundry Agents . Możesz tworzyć trwałe wystąpienia agenta oparte na usłudze za pomocą wątków konwersacji zarządzanych przez usługę.
Wprowadzenie
Dodaj wymagane pakiety NuGet do projektu.
dotnet add package Azure.Identity
dotnet add package Microsoft.Agents.AI.AzureAI.Persistent --prerelease
Tworzenie agentów usługi Azure AI Foundry
Pierwszym krokiem jest utworzenie klienta w celu nawiązania połączenia z usługą Azure AI Foundry Agents.
using System;
using Azure.AI.Agents.Persistent;
using Azure.Identity;
using Microsoft.Agents.AI;
var persistentAgentsClient = new PersistentAgentsClient(
"https://<myresource>.services.ai.azure.com/api/projects/<myproject>",
new AzureCliCredential());
Aby użyć usługi Azure AI Foundry Agents, musisz utworzyć zasób agenta w usłudze. Można to zrobić przy użyciu zestawu AZURE.AI.Agents.Persistent SDK lub pomocników programu Microsoft Agent Framework.
Korzystanie z Persistent SDK
Utwórz agenta trwałego i pobierz go jako AIAgent przy użyciu elementu PersistentAgentsClient.
// Create a persistent agent
var agentMetadata = await persistentAgentsClient.Administration.CreateAgentAsync(
model: "gpt-4o-mini",
name: "Joker",
instructions: "You are good at telling jokes.");
// Retrieve the agent that was just created as an AIAgent using its ID
AIAgent agent1 = await persistentAgentsClient.GetAIAgentAsync(agentMetadata.Value.Id);
// Invoke the agent and output the text result.
Console.WriteLine(await agent1.RunAsync("Tell me a joke about a pirate."));
Korzystanie z pomocników programu Agent Framework
Możesz również utworzyć i zwrócić element AIAgent w jednym kroku:
AIAgent agent2 = await persistentAgentsClient.CreateAIAgentAsync(
model: "gpt-4o-mini",
name: "Joker",
instructions: "You are good at telling jokes.");
Ponowne użycie agentów Azure AI Foundry
Możesz ponownie użyć istniejących agentów usługi Azure AI Foundry, pobierając je przy użyciu ich identyfikatorów.
AIAgent agent3 = await persistentAgentsClient.GetAIAgentAsync("<agent-id>");
Korzystanie z agenta
Agent jest standardowy AIAgent i obsługuje wszystkie standardowe AIAgent operacje.
Aby uzyskać więcej informacji na temat uruchamiania agentów i interakcji z nimi, zobacz samouczki wprowadzające do agenta.
Konfiguracja
Zmienne środowiskowe
Przed rozpoczęciem korzystania z agentów usługi Azure AI Foundry należy skonfigurować następujące zmienne środowiskowe:
export AZURE_AI_PROJECT_ENDPOINT="https://<your-project>.services.ai.azure.com/api/projects/<project-id>"
export AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini"
Alternatywnie możesz podać te wartości bezpośrednio w kodzie.
Instalacja
Dodaj pakiet Azure AI platformy Agent Framework do projektu:
pip install agent-framework-azure-ai --pre
Wprowadzenie
Authentication
Agenci usługi Azure AI Foundry używają poświadczeń platformy Azure do uwierzytelniania. Najprostszym podejściem jest użycie AzureCliCredential po uruchomieniu az login.
from azure.identity.aio import AzureCliCredential
async with AzureCliCredential() as credential:
# Use credential with Azure AI agent client
Tworzenie agentów usługi Azure AI Foundry
Tworzenie podstawowego agenta
Najprostszym sposobem utworzenia agenta jest użycie zmiennych AzureAIAgentClient środowiskowych:
import asyncio
from agent_framework.azure import AzureAIAgentClient
from azure.identity.aio import AzureCliCredential
async def main():
async with (
AzureCliCredential() as credential,
AzureAIAgentClient(async_credential=credential).create_agent(
name="HelperAgent",
instructions="You are a helpful assistant."
) as agent,
):
result = await agent.run("Hello!")
print(result.text)
asyncio.run(main())
Jawna konfiguracja
Możesz również jawnie podać konfigurację zamiast używać zmiennych środowiskowych:
import asyncio
from agent_framework.azure import AzureAIAgentClient
from azure.identity.aio import AzureCliCredential
async def main():
async with (
AzureCliCredential() as credential,
AzureAIAgentClient(
project_endpoint="https://<your-project>.services.ai.azure.com/api/projects/<project-id>",
model_deployment_name="gpt-4o-mini",
async_credential=credential,
agent_name="HelperAgent"
).create_agent(
instructions="You are a helpful assistant."
) as agent,
):
result = await agent.run("Hello!")
print(result.text)
asyncio.run(main())
Korzystanie z istniejących agentów usługi Azure AI Foundry
Używanie istniejącego agenta za pomocą identyfikatora
Jeśli masz istniejącego agenta w usłudze Azure AI Foundry, możesz go użyć, podając jego identyfikator:
import asyncio
from agent_framework import ChatAgent
from agent_framework.azure import AzureAIAgentClient
from azure.identity.aio import AzureCliCredential
async def main():
async with (
AzureCliCredential() as credential,
ChatAgent(
chat_client=AzureAIAgentClient(
async_credential=credential,
agent_id="<existing-agent-id>"
),
instructions="You are a helpful assistant."
) as agent,
):
result = await agent.run("Hello!")
print(result.text)
asyncio.run(main())
Tworzenie agentów trwałych i zarządzanie nimi
Aby uzyskać większą kontrolę nad cyklem życia agenta, możesz utworzyć agentów trwałych przy użyciu klienta usługi Azure AI Projects:
import asyncio
import os
from agent_framework import ChatAgent
from agent_framework.azure import AzureAIAgentClient
from azure.ai.projects.aio import AIProjectClient
from azure.identity.aio import AzureCliCredential
async def main():
async with (
AzureCliCredential() as credential,
AIProjectClient(
endpoint=os.environ["AZURE_AI_PROJECT_ENDPOINT"],
credential=credential
) as project_client,
):
# Create a persistent agent
created_agent = await project_client.agents.create_agent(
model=os.environ["AZURE_AI_MODEL_DEPLOYMENT_NAME"],
name="PersistentAgent",
instructions="You are a helpful assistant."
)
try:
# Use the agent
async with ChatAgent(
chat_client=AzureAIAgentClient(
project_client=project_client,
agent_id=created_agent.id
),
instructions="You are a helpful assistant."
) as agent:
result = await agent.run("Hello!")
print(result.text)
finally:
# Clean up the agent
await project_client.agents.delete_agent(created_agent.id)
asyncio.run(main())
Funkcje agenta
Narzędzia funkcji
Możesz udostępnić niestandardowe narzędzia funkcji agentom usługi Azure AI Foundry:
import asyncio
from typing import Annotated
from agent_framework.azure import AzureAIAgentClient
from azure.identity.aio import AzureCliCredential
from pydantic import Field
def get_weather(
location: Annotated[str, Field(description="The location to get the weather for.")],
) -> str:
"""Get the weather for a given location."""
return f"The weather in {location} is sunny with a high of 25°C."
async def main():
async with (
AzureCliCredential() as credential,
AzureAIAgentClient(async_credential=credential).create_agent(
name="WeatherAgent",
instructions="You are a helpful weather assistant.",
tools=get_weather
) as agent,
):
result = await agent.run("What's the weather like in Seattle?")
print(result.text)
asyncio.run(main())
Interpreter kodów
Agenci usługi Azure AI Foundry obsługują wykonywanie kodu za pośrednictwem interpretera hostowanego kodu:
import asyncio
from agent_framework import HostedCodeInterpreterTool
from agent_framework.azure import AzureAIAgentClient
from azure.identity.aio import AzureCliCredential
async def main():
async with (
AzureCliCredential() as credential,
AzureAIAgentClient(async_credential=credential).create_agent(
name="CodingAgent",
instructions="You are a helpful assistant that can write and execute Python code.",
tools=HostedCodeInterpreterTool()
) as agent,
):
result = await agent.run("Calculate the factorial of 20 using Python code.")
print(result.text)
asyncio.run(main())
Odpowiedzi w strumieniowaniu
Uzyskiwanie odpowiedzi podczas ich generowania przy użyciu przesyłania strumieniowego:
import asyncio
from agent_framework.azure import AzureAIAgentClient
from azure.identity.aio import AzureCliCredential
async def main():
async with (
AzureCliCredential() as credential,
AzureAIAgentClient(async_credential=credential).create_agent(
name="StreamingAgent",
instructions="You are a helpful assistant."
) as agent,
):
print("Agent: ", end="", flush=True)
async for chunk in agent.run_stream("Tell me a short story"):
if chunk.text:
print(chunk.text, end="", flush=True)
print()
asyncio.run(main())
Korzystanie z agenta
Agent jest standardowy BaseAgent i obsługuje wszystkie standardowe operacje agenta.
Aby uzyskać więcej informacji na temat uruchamiania agentów i interakcji z nimi, zobacz samouczki wprowadzające do agenta.