Udostępnij przez


Przepływy pracy programu Microsoft Agent Framework — praca z agentami

Ta strona zawiera omówienie sposobu używania agentów w ramach przepływów pracy programu Microsoft Agent Framework.

Przegląd

Aby dodać inteligencję do przepływów pracy, możesz wykorzystać agentów sztucznej inteligencji podczas wykonywania przepływów pracy. Agenci sztucznej inteligencji można łatwo zintegrować z przepływami pracy, umożliwiając tworzenie złożonych, inteligentnych rozwiązań, które wcześniej były trudne do osiągnięcia.

Dodawanie agenta bezpośrednio do przepływu pracy

Agentów można dodawać do przepływu pracy za pomocą krawędzi:

using Microsoft.Agents.AI.Workflows;
using Microsoft.Extensions.AI;
using Microsoft.Agents.AI;

// Create the agents first
AIAgent agentA = new ChatClientAgent(chatClient, instructions);
AIAgent agentB = new ChatClientAgent(chatClient, instructions);

// Build a workflow with the agents
WorkflowBuilder builder = new(agentA);
builder.AddEdge(agentA, agentB);
Workflow<ChatMessage> workflow = builder.Build<ChatMessage>();

Uruchamianie przepływu pracy

Wewnątrz utworzonego powyżej przepływu pracy agenci są faktycznie owinięci wewnątrz funkcji wykonawczej obsługującej komunikację agenta z innymi częściami przepływu pracy. Funkcja wykonawcza może obsługiwać trzy typy komunikatów:

  • ChatMessage: pojedyncza wiadomość czatu
  • List<ChatMessage>: Lista wiadomości czatu
  • TurnToken: token turn, który sygnalizuje rozpoczęcie nowego turnu

Funkcja wykonawcza nie wyzwala agenta do odpowiedzi, dopóki nie otrzyma TurnToken. Wszystkie komunikaty odebrane przed TurnToken są buforowane i wysyłane do agenta po odebraniu TurnToken.

StreamingRun run = await InProcessExecution.StreamAsync(workflow, new ChatMessage(ChatRole.User, "Hello World!"));
// Must send the turn token to trigger the agents. The agents are wrapped as executors.
// When they receive messages, they will cache the messages and only start processing
// when they receive a TurnToken. The turn token will be passed from one agent to the next.
await run.TrySendMessageAsync(new TurnToken(emitEvents: true));
await foreach (WorkflowEvent evt in run.WatchStreamAsync().ConfigureAwait(false))
{
    // The agents will run in streaming mode and an AgentRunUpdateEvent
    // will be emitted as new chunks are generated.
    if (evt is AgentRunUpdateEvent agentRunUpdate)
    {
        Console.WriteLine($"{agentRunUpdate.ExecutorId}: {agentRunUpdate.Data}");
    }
}

Korzystanie z wbudowanego modułu wykonawczego agenta

Agentów można dodawać do przepływu pracy za pomocą krawędzi:

from agent_framework import WorkflowBuilder
from agent_framework.azure import AzureChatClient
from azure.identity import AzureCliCredential

# Create the agents first
chat_client = AzureChatClient(credential=AzureCliCredential())
writer_agent: ChatAgent = chat_client.create_agent(
    instructions=(
        "You are an excellent content writer. You create new content and edit contents based on the feedback."
    ),
    name="writer_agent",
)
reviewer_agent = chat_client.create_agent(
    instructions=(
        "You are an excellent content reviewer."
        "Provide actionable feedback to the writer about the provided content."
        "Provide the feedback in the most concise manner possible."
    ),
    name="reviewer_agent",
)

# Build a workflow with the agents
builder = WorkflowBuilder()
builder.set_start_executor(writer_agent)
builder.add_edge(writer_agent, reviewer_agent)
workflow = builder.build()

Uruchamianie przepływu pracy

Wewnątrz utworzonego powyżej przepływu pracy agenci są faktycznie owinięci wewnątrz funkcji wykonawczej obsługującej komunikację agenta z innymi częściami przepływu pracy. Funkcja wykonawcza może obsługiwać trzy typy komunikatów:

  • str: pojedyncza wiadomość czatu w formacie ciągu
  • ChatMessage: pojedyncza wiadomość czatu
  • List<ChatMessage>: Lista wiadomości czatu

Za każdym razem, gdy wykonawca odbiera komunikat jednego z tych typów, spowoduje, że agent odpowie, a typ odpowiedzi będzie obiektem AgentExecutorResponse. Ta klasa zawiera przydatne informacje o odpowiedzi agenta, w tym:

  • executor_id: identyfikator funkcji wykonawczej, która wygenerowała tę odpowiedź
  • agent_run_response: Pełna odpowiedź agenta
  • full_conversation: Pełna historia konwersacji do tego momentu

Podczas uruchamiania przepływu pracy można emitować dwa możliwe typy zdarzeń związane z odpowiedziami agentów:

  • AgentRunUpdateEvent zawierające fragmenty odpowiedzi agenta, które są generowane w trybie przesyłania strumieniowego.
  • AgentRunEvent zawierające pełną odpowiedź agenta w trybie bez przesyłania strumieniowego.

Domyślnie agenci są owinięci w egzekutorzy uruchamianych w trybie przesyłania strumieniowego. To zachowanie można dostosować, tworząc niestandardowy egzekutor. Aby uzyskać więcej informacji, zobacz następną sekcję.

last_executor_id = None
async for event in workflow.run_streaming("Write a short blog post about AI agents."):
    if isinstance(event, AgentRunUpdateEvent):
        if event.executor_id != last_executor_id:
            if last_executor_id is not None:
                print()
            print(f"{event.executor_id}:", end=" ", flush=True)
            last_executor_id = event.executor_id
        print(event.data, end="", flush=True)

Korzystanie z niestandardowego egzekutora agenta

Czasami warto dostosować sposób integracji agentów sztucznej inteligencji z przepływem pracy. Można to osiągnąć, tworząc niestandardowy egzekutor. Pozwala to kontrolować:

  • Wywołanie agenta: przesyłanie strumieniowe lub nieprzesyłanie strumieniowe
  • Typy komunikatów obsługiwane przez agenta, w tym niestandardowe typy komunikatów
  • Cykl życia agenta, w tym inicjowanie i oczyszczanie
  • Użycie wątków agenta i innych zasobów
  • Dodatkowe zdarzenia generowane podczas wykonywania agenta, w tym zdarzenia niestandardowe
  • Integracja z innymi funkcjami przepływu pracy, takimi jak stany udostępnione i żądania/odpowiedzi
internal sealed class CustomAgentExecutor : Executor<CustomInput, CustomOutput>("CustomAgentExecutor")
{
    private readonly AIAgent _agent;

    /// <summary>
    /// Creates a new instance of the <see cref="CustomAgentExecutor"/> class.
    /// </summary>
    /// <param name="agent">The AI agent used for custom processing</param>
    public CustomAgentExecutor(AIAgent agent) : base("CustomAgentExecutor")
    {
        this._agent = agent;
    }

    public async ValueTask<CustomOutput> HandleAsync(CustomInput message, IWorkflowContext context)
    {
        // Retrieve any shared states if needed
        var sharedState = await context.ReadStateAsync<SharedStateType>("sharedStateId", scopeName: "SharedStateScope");

        // Render the input for the agent
        var agentInput = RenderInput(message, sharedState);

        // Invoke the agent
        // Assume the agent is configured with structured outputs with type `CustomOutput`
        var response = await this._agent.RunAsync(agentInput);
        var customOutput = JsonSerializer.Deserialize<CustomOutput>(response.Text);

        return customOutput;
    }
}
from agent_framework import (
    ChatAgent,
    ChatMessage,
    Executor,
    WorkflowContext,
    handler
)

class Writer(Executor):

    agent: ChatAgent

    def __init__(self, chat_client: AzureChatClient, id: str = "writer"):
        # Create a domain specific agent using your configured AzureChatClient.
        agent = chat_client.create_agent(
            instructions=(
                "You are an excellent content writer. You create new content and edit contents based on the feedback."
            ),
        )
        # Associate the agent with this executor node. The base Executor stores it on self.agent.
        super().__init__(agent=agent, id=id)

    @handler
    async def handle(self, message: ChatMessage, ctx: WorkflowContext[list[ChatMessage]]) -> None:
        """Handles a single chat message and forwards the accumulated messages to the next executor in the workflow."""
        # Invoke the agent with the incoming message and get the response
        messages: list[ChatMessage] = [message]
        response = await self.agent.run(messages)
        # Accumulate messages and send them to the next executor in the workflow.
        messages.extend(response.messages)
        await ctx.send_message(messages)

Dalsze kroki