Bagikan melalui


Alur Kerja Microsoft Agent Framework - Bekerja dengan Agen

Halaman ini memberikan gambaran umum tentang cara menggunakan Agen dalam Alur Kerja Kerangka Kerja Agen Microsoft.

Gambaran Umum

Untuk menambahkan kecerdasan ke alur kerja, Anda dapat memanfaatkan agen AI sebagai bagian dari eksekusi alur kerja Anda. Agen AI dapat dengan mudah diintegrasikan ke dalam alur kerja, memungkinkan Anda membuat solusi cerdas yang kompleks yang sebelumnya sulit dicapai.

Menambahkan Agen Langsung ke Alur Kerja

Anda dapat menambahkan agen ke alur kerja Anda melalui tepi:

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>();

Menjalankan Alur Kerja

Di dalam alur kerja yang dibuat di atas, agen sebenarnya dibungkus di dalam eksekutor yang menangani komunikasi agen dengan bagian lain dari alur kerja. Pelaksana dapat menangani tiga jenis pesan:

  • ChatMessage: Satu pesan obrolan tunggal.
  • List<ChatMessage>: Daftar pesan obrolan.
  • TurnToken: Token giliran yang menandakan dimulainya giliran baru.

Pelaksana tidak mengaktifkan agen untuk merespons sampai menerima TurnToken. Pesan-pesan yang diterima sebelum TurnToken akan di-buffer dan dikirim ke agen ketika TurnToken diterima.

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 AgentResponseUpdateEvent
    // will be emitted as new chunks are generated.
    if (evt is AgentResponseUpdateEvent agentRunUpdate)
    {
        Console.WriteLine($"{agentRunUpdate.ExecutorId}: {agentRunUpdate.Data}");
    }
}

Menggunakan Eksekutor Agen Bawaan

Anda dapat menambahkan agen ke alur kerja Anda melalui tepi:

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.as_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.as_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()

Menjalankan Alur Kerja

Di dalam alur kerja yang dibuat di atas, agen sebenarnya dibungkus di dalam eksekutor yang menangani komunikasi agen dengan bagian lain dari alur kerja. Pelaksana dapat menangani tiga jenis pesan:

  • str: Pesan obrolan tunggal dalam format string
  • ChatMessage: Satu pesan obrolan
  • List<ChatMessage>: Daftar pesan obrolan

Setiap kali pelaksana menerima pesan dari salah satu jenis ini, itu akan memicu agen untuk merespons, dan jenis respons akan menjadi AgentExecutorResponse objek. Kelas ini berisi informasi yang berguna tentang respons agen, termasuk:

  • executor_id: ID pelaksana yang menghasilkan respons ini
  • agent_run_response: Respons penuh dari agen
  • full_conversation: Riwayat percakapan lengkap hingga saat ini

Dua kemungkinan jenis peristiwa yang terkait dengan respons agen dapat dipancarkan saat menjalankan alur kerja:

  • AgentResponseUpdateEvent berisi potongan respons agen saat dihasilkan dalam mode streaming.
  • AgentRunEvent yang berisi respons lengkap dari agen dalam mode non-streaming.

Secara bawaan, agen dibungkus dalam eksekutor yang berjalan dalam mode streaming. Anda dapat menyesuaikan perilaku ini dengan membuat pelaksana kustom. Lihat bagian berikutnya untuk detail selengkapnya.

last_executor_id = None
async for event in workflow.run_streaming("Write a short blog post about AI agents."):
    if isinstance(event, AgentResponseUpdateEvent):
        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)

Menggunakan Pelaksana Agen Kustom

Terkadang Anda mungkin ingin menyesuaikan bagaimana agen AI diintegrasikan ke dalam alur kerja. Anda dapat mencapai ini dengan membuat eksekutor kustom. Ini memungkinkan Anda untuk mengontrol:

  • Pemanggilan agen: streaming atau non-streaming
  • Jenis pesan yang akan ditangani agen, termasuk jenis pesan kustom
  • Siklus hidup agen, termasuk inisialisasi dan pembersihan
  • Penggunaan sesi agen dan sumber daya lainnya
  • Peristiwa tambahan yang dipancarkan selama eksekusi agen, termasuk peristiwa kustom
  • Integrasi dengan fitur alur kerja lainnya, seperti status bersama dan permintaan/respons
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.as_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)

Langkah Selanjutnya