如何:建立您的第一個流程

警告

語意核心進程架構 是實驗性的,仍在開發中,而且可能會變更。

概述

Semantic Kernel Process Framework 是功能強大的協調流程 SDK,旨在簡化 AI 整合程式的開發和執行。 無論您是管理簡單的工作流程或複雜系統,此架構都可讓您定義一系列步驟,以結構化方式執行,以輕鬆且彈性地增強應用程式的功能。

Process Framework 專為擴充性所建置,支援各種不同的作業模式,例如循序執行、平行處理、扇入和扇出配置,甚至是 map-reduce 策略。 這種適應性使其適用於各種現實世界的應用,特別是需要智能決策和多步驟工作流程的應用。

快速入門

語意核心進程架構可用來將 AI 注入您所能想到的任何商務程式。 作為入門的範例說明,讓我們來看看建立流程來產生新產品的檔案。

開始之前,請確定您已安裝必要的語意核心套件:

// Install the Semantic Kernel Process Framework Local Runtime package
dotnet add package Microsoft.SemanticKernel.Process.LocalRuntime --version 1.46.0-alpha
// or
// Install the Semantic Kernel Process Framework Dapr Runtime package
dotnet add package Microsoft.SemanticKernel.Process.Runtime.Dapr --version 1.46.0-alpha

pip install semantic-kernel==1.20.0

說明範例:為新產品產生文件

在此範例中,我們將利用Semantic Kernel Process Framework開發自動化流程,以建立新產品的文件。 這個過程將從簡單開始,然後隨著我們深入探索,逐漸發展以涵蓋更真實的案例。

首先,我們會使用非常基本的流程來建立文件程式模型:

  1. GatherProductInfoStep:收集產品的相關信息。
  2. GenerateDocumentationStep:要求 LLM 從步驟 1 中收集的資訊生成文件。
  3. PublishDocumentationStep:發佈文件。

第一個程式的 流程圖:A[要求功能檔] --> B[要求 LLM 撰寫檔] --> C[發佈檔至公用]

既然我們瞭解我們的程式,讓我們來建置它。

定義程式步驟

Process 的每個步驟都是由繼承自基底步驟類別的類別所定義。 在此程式中,我們有三個步驟:

using Microsoft.SemanticKernel.ChatCompletion;
using Microsoft.SemanticKernel;

// A process step to gather information about a product
public class GatherProductInfoStep: KernelProcessStep
{
    [KernelFunction]
    public string GatherProductInformation(string productName)
    {
        Console.WriteLine($"{nameof(GatherProductInfoStep)}:\n\tGathering product information for product named {productName}");

        // For example purposes we just return some fictional information.
        return
            """
            Product Description:
            GlowBrew is a revolutionary AI driven coffee machine with industry leading number of LEDs and programmable light shows. The machine is also capable of brewing coffee and has a built in grinder.

            Product Features:
            1. **Luminous Brew Technology**: Customize your morning ambiance with programmable LED lights that sync with your brewing process.
            2. **AI Taste Assistant**: Learns your taste preferences over time and suggests new brew combinations to explore.
            3. **Gourmet Aroma Diffusion**: Built-in aroma diffusers enhance your coffee's scent profile, energizing your senses before the first sip.

            Troubleshooting:
            - **Issue**: LED Lights Malfunctioning
                - **Solution**: Reset the lighting settings via the app. Ensure the LED connections inside the GlowBrew are secure. Perform a factory reset if necessary.
            """;
    }
}

// A process step to generate documentation for a product
public class GenerateDocumentationStep : KernelProcessStep<GeneratedDocumentationState>
{
    private GeneratedDocumentationState _state = new();

    private string systemPrompt =
            """
            Your job is to write high quality and engaging customer facing documentation for a new product from Contoso. You will be provide with information
            about the product in the form of internal documentation, specs, and troubleshooting guides and you must use this information and
            nothing else to generate the documentation. If suggestions are provided on the documentation you create, take the suggestions into account and
            rewrite the documentation. Make sure the product sounds amazing.
            """;

    // Called by the process runtime when the step instance is activated. Use this to load state that may be persisted from previous activations.
    override public ValueTask ActivateAsync(KernelProcessStepState<GeneratedDocumentationState> state)
    {
        this._state = state.State!;
        this._state.ChatHistory ??= new ChatHistory(systemPrompt);

        return base.ActivateAsync(state);
    }

    [KernelFunction]
    public async Task GenerateDocumentationAsync(Kernel kernel, KernelProcessStepContext context, string productInfo)
    {
        Console.WriteLine($"[{nameof(GenerateDocumentationStep)}]:\tGenerating documentation for provided productInfo...");

        // Add the new product info to the chat history
        this._state.ChatHistory!.AddUserMessage($"Product Info:\n{productInfo.Title} - {productInfo.Content}");

        // Get a response from the LLM
        IChatCompletionService chatCompletionService = kernel.GetRequiredService<IChatCompletionService>();
        var generatedDocumentationResponse = await chatCompletionService.GetChatMessageContentAsync(this._state.ChatHistory!);

        DocumentInfo generatedContent = new()
        {
            Id = Guid.NewGuid().ToString(),
            Title = $"Generated document - {productInfo.Title}",
            Content = generatedDocumentationResponse.Content!,
        };

        this._state!.LastGeneratedDocument = generatedContent;

        await context.EmitEventAsync("DocumentationGenerated", generatedContent);
    }

    public class GeneratedDocumentationState
    {
        public DocumentInfo LastGeneratedDocument { get; set; } = new();
        public ChatHistory? ChatHistory { get; set; }
    }
}

// A process step to publish documentation
public class PublishDocumentationStep : KernelProcessStep
{
    [KernelFunction]
    public DocumentInfo PublishDocumentation(DocumentInfo document)
    {
        // For example purposes we just write the generated docs to the console
        Console.WriteLine($"[{nameof(PublishDocumentationStep)}]:\tPublishing product documentation approved by user: \n{document.Title}\n{document.Content}");
        return document;
    }
}

// Custom classes must be serializable
public class DocumentInfo
{
    public string Id { get; set; } = string.Empty;
    public string Title { get; set; } = string.Empty;
    public string Content { get; set; } = string.Empty;
}

上述程式代碼會定義程式所需的三個步驟。 這裡有幾個要指出的要點:

  • 在 Semantic Kernel 中,KernelFunction 會定義一個可由原生代碼或 LLM 調用的程式碼區塊。 在 Process 架構的情況下,KernelFunction是 Step 的可叫用成員,而且每個步驟至少需要定義一個 KernelFunction。
  • Process Framework 支援無狀態和有狀態的步驟。 具狀態步驟會自動檢查並記錄其進度,並在多次調用中保持狀態。 GenerateDocumentationStep提供這個範例,其中 類別GeneratedDocumentationState用來保存 ChatHistoryLastGeneratedDocument 物件。
  • 步驟可以在 EmitEventAsync 物件上呼叫 KernelProcessStepContext,以手動發出事件。 若要取得實例 KernelProcessStepContext 只要將它新增為 KernelFunction 上的參數,架構就會自動插入它。
import asyncio
from typing import ClassVar

from pydantic import BaseModel, Field

from semantic_kernel import Kernel
from semantic_kernel.connectors.ai.chat_completion_client_base import ChatCompletionClientBase
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion
from semantic_kernel.contents import ChatHistory
from semantic_kernel.functions import kernel_function
from semantic_kernel.processes import ProcessBuilder
from semantic_kernel.processes.kernel_process import KernelProcessStep, KernelProcessStepContext, KernelProcessStepState
from semantic_kernel.processes.local_runtime import KernelProcessEvent, start


# A process step to gather information about a product
class GatherProductInfoStep(KernelProcessStep):
    @kernel_function
    def gather_product_information(self, product_name: str) -> str:
        print(f"{GatherProductInfoStep.__name__}\n\t Gathering product information for Product Name: {product_name}")

        return """
Product Description:

GlowBrew is a revolutionary AI driven coffee machine with industry leading number of LEDs and 
programmable light shows. The machine is also capable of brewing coffee and has a built in grinder.

Product Features:
1. **Luminous Brew Technology**: Customize your morning ambiance with programmable LED lights that sync 
    with your brewing process.
2. **AI Taste Assistant**: Learns your taste preferences over time and suggests new brew combinations 
    to explore.
3. **Gourmet Aroma Diffusion**: Built-in aroma diffusers enhance your coffee's scent profile, energizing 
    your senses before the first sip.

Troubleshooting:
- **Issue**: LED Lights Malfunctioning
    - **Solution**: Reset the lighting settings via the app. Ensure the LED connections inside the 
        GlowBrew are secure. Perform a factory reset if necessary.
        """


# A sample step state model for the GenerateDocumentationStep
class GeneratedDocumentationState(BaseModel):
    """State for the GenerateDocumentationStep."""

    chat_history: ChatHistory | None = None


# A process step to generate documentation for a product
class GenerateDocumentationStep(KernelProcessStep[GeneratedDocumentationState]):
    state: GeneratedDocumentationState = Field(default_factory=GeneratedDocumentationState)

    system_prompt: ClassVar[str] = """
Your job is to write high quality and engaging customer facing documentation for a new product from Contoso. You will 
be provided with information about the product in the form of internal documentation, specs, and troubleshooting guides 
and you must use this information and nothing else to generate the documentation. If suggestions are provided on the 
documentation you create, take the suggestions into account and rewrite the documentation. Make sure the product 
sounds amazing.
"""

    async def activate(self, state: KernelProcessStepState[GeneratedDocumentationState]):
        self.state = state.state
        if self.state.chat_history is None:
            self.state.chat_history = ChatHistory(system_message=self.system_prompt)
        self.state.chat_history

    @kernel_function
    async def generate_documentation(
        self, context: KernelProcessStepContext, product_info: str, kernel: Kernel
    ) -> None:
        print(f"{GenerateDocumentationStep.__name__}\n\t Generating documentation for provided product_info...")

        self.state.chat_history.add_user_message(f"Product Information:\n{product_info}")

        chat_service, settings = kernel.select_ai_service(type=ChatCompletionClientBase)
        assert isinstance(chat_service, ChatCompletionClientBase)  # nosec

        response = await chat_service.get_chat_message_content(chat_history=self.state.chat_history, settings=settings)

        await context.emit_event(process_event="documentation_generated", data=str(response))


# A process step to publish documentation
class PublishDocumentationStep(KernelProcessStep):
    @kernel_function
    async def publish_documentation(self, docs: str) -> None:
        print(f"{PublishDocumentationStep.__name__}\n\t Publishing product documentation:\n\n{docs}")

上述程式代碼會定義程式所需的三個步驟。 這裡有幾個要指出的要點:

  • 在 Semantic Kernel 中,KernelFunction 會定義一個可由原生代碼或 LLM 調用的程式碼區塊。 在 Process 架構的情況下,KernelFunction是 Step 的可叫用成員,而且每個步驟至少需要定義一個 KernelFunction。
  • Process Framework 支援無狀態和有狀態的步驟。 具狀態步驟會自動檢查並記錄其進度,並在多次調用中保持狀態。 GenerateDocumentationStep 提供一個範例,其中 GeneratedDocumentationState 類別用來保存 ChatHistory 物件。
  • 步驟可以在 emit_event 物件上呼叫 KernelProcessStepContext,以手動發出事件。 若要取得實例 KernelProcessStepContext 只要將它新增為 KernelFunction 上的參數,架構就會自動插入它。

定義進程流程

// Create the process builder
ProcessBuilder processBuilder = new("DocumentationGeneration");

// Add the steps
var infoGatheringStep = processBuilder.AddStepFromType<GatherProductInfoStep>();
var docsGenerationStep = processBuilder.AddStepFromType<GenerateDocumentationStep>();
var docsPublishStep = processBuilder.AddStepFromType<PublishDocumentationStep>();

// Orchestrate the events
processBuilder
    .OnInputEvent("Start")
    .SendEventTo(new(infoGatheringStep));

infoGatheringStep
    .OnFunctionResult()
    .SendEventTo(new(docsGenerationStep));

docsGenerationStep
    .OnFunctionResult()
    .SendEventTo(new(docsPublishStep));

這裡有一些正在進行的事情,讓我們一步一步地分析。

  1. 建立建構器:流程使用建構器模式來簡化所有項目的連接。 建置者提供方法來管理程式內的步驟,以及管理程式的生命週期。

  2. 新增步驟:可以透過呼叫建構器的 AddStepFromType 方法,將步驟新增到流程中。 這可讓 Process Framework 視需要具現化實例來管理步驟的生命週期。 在此情況下,我們已將三個步驟新增至程式,併為每個步驟建立變數。 這些變數提供我們操作每個步驟獨特實例的方法,可用來定義事件的編排流程。

  3. 協調事件:這是設定事件如何從一個步驟傳遞到下一個步驟的過程。 在此情況下,我們有下列路由:

    • 當具有 id = Start 的外部事件傳送至進程時,此事件及其相關聯的數據將會傳送至 infoGatheringStep 步驟。
    • infoGatheringStep 完成執行時,將傳回的物件傳送至 docsGenerationStep 步驟。
    • 最後,當 docsGenerationStep 完成執行時,將傳回的物件傳送至 docsPublishStep 步驟。

小技巧

Process Framework 中的事件路由: 您可能想知道步驟所接收的事件是如何被路由至步驟中的 KernelFunctions。 在上述程式代碼中,每個步驟只會定義單一 KernelFunction,而每個 KernelFunction 只有單一參數(除了 Kernel 和步驟內容以外,稍後更特別)。 當包含所產生檔的事件傳送至 docsPublishStep 時,會傳遞至 document 步驟之 PublishDocumentation KernelFunction 的 docsGenerationStep 參數,因為沒有其他選擇。 不過,步驟可以包含多個 KernelFunctions,而每個 KernelFunction 又可以擁有多個參數。在這些進階案例中,您需要指定目標函式和參數。

# Create the process builder
process_builder = ProcessBuilder(name="DocumentationGeneration")

# Add the steps
info_gathering_step = process_builder.add_step(GatherProductInfoStep)
docs_generation_step = process_builder.add_step(GenerateDocumentationStep)
docs_publish_step = process_builder.add_step(PublishDocumentationStep)

# Orchestrate the events
process_builder.on_input_event("Start").send_event_to(target=info_gathering_step)

info_gathering_step.on_function_result().send_event_to(
    target=docs_generation_step, function_name="generate_documentation", parameter_name="product_info"
)

docs_generation_step.on_event("documentation_generated").send_event_to(target=docs_publish_step)

# Configure the kernel with an AI service and connection details, if necessary
kernel = Kernel()
kernel.add_service(AzureChatCompletion())

# Build the process
kernel_process = process_builder.build()

這裡有一些正在進行的事情,讓我們一步一步地分析。

  1. 建立建構器:流程使用建構器模式來簡化所有項目的連接。 建置者提供方法來管理程式內的步驟,以及管理程式的生命週期。

  2. 新增步驟:可藉由呼叫建構器的 add_step 方法,將步驟類型新增至建構器來進行步驟的添加。 這可讓 Process Framework 視需要具現化實例來管理步驟的生命週期。 在此情況下,我們已將三個步驟新增至程式,併為每個步驟建立變數。 這些變數提供我們操作每個步驟獨特實例的方法,可用來定義事件的編排流程。

  3. 協調事件:這是設定事件如何從一個步驟傳遞到下一個步驟的過程。 在此情況下,我們有下列路由:

    • 將具有 id = Start 的外部事件傳送至行程時,此事件及其相關聯的數據將會傳送至 info_gathering_step
    • info_gathering_step 完成執行時,將傳回的物件傳送至 docs_generation_step
    • 最後,當完成執行時 docs_generation_step ,將傳回的物件傳送至 docs_publish_step

小技巧

Process Framework 中的事件路由: 您可能想知道步驟所接收的事件是如何被路由至步驟中的 KernelFunctions。 在上述程式代碼中,每個步驟只會定義單一 KernelFunction,而每個 KernelFunction 只有單一參數(除了 Kernel 和步驟內容以外,稍後更特別)。 當包含所產生文件的事件被傳送到 docs_publish_step 時,它會被傳遞到 docs 的 KernelFunction 中的 publish_documentation 參數,因為沒有其他選擇。 不過,步驟可以包含多個 KernelFunctions,而每個 KernelFunction 又可以擁有多個參數。在這些進階案例中,您需要指定目標函式和參數。

建置並執行程式

// Configure the kernel with your LLM connection details
Kernel kernel = Kernel.CreateBuilder()
    .AddAzureOpenAIChatCompletion("myDeployment", "myEndpoint", "myApiKey")
    .Build();

// Build and run the process
var process = processBuilder.Build();
await process.StartAsync(kernel, new KernelProcessEvent { Id = "Start", Data = "Contoso GlowBrew" });

我們會建置程式並呼叫 StartAsync 來執行。 我們的流程希望由一個稱為 Start 的初始外部事件來啟動,因此我們也提供這個事件。 執行此程式會在控制台中顯示下列輸出:

GatherProductInfoStep: Gathering product information for product named Contoso GlowBrew
GenerateDocumentationStep: Generating documentation for provided productInfo
PublishDocumentationStep: Publishing product documentation:

# GlowBrew: Your Ultimate Coffee Experience Awaits!

Welcome to the world of GlowBrew, where coffee brewing meets remarkable technology! At Contoso, we believe that your morning ritual shouldn't just include the perfect cup of coffee but also a stunning visual experience that invigorates your senses. Our revolutionary AI-driven coffee machine is designed to transform your kitchen routine into a delightful ceremony.

## Unleash the Power of GlowBrew

### Key Features

- **Luminous Brew Technology**
  - Elevate your coffee experience with our cutting-edge programmable LED lighting. GlowBrew allows you to customize your morning ambiance, creating a symphony of colors that sync seamlessly with your brewing process. Whether you need a vibrant wake-up call or a soothing glow, you can set the mood for any moment!

- **AI Taste Assistant**
  - Your taste buds deserve the best! With the GlowBrew built-in AI taste assistant, the machine learns your unique preferences over time and curates personalized brew suggestions just for you. Expand your coffee horizons and explore delightful new combinations that fit your palate perfectly.

- **Gourmet Aroma Diffusion**
  - Awaken your senses even before that first sip! The GlowBrew comes equipped with gourmet aroma diffusers that enhance the scent profile of your coffee, diffusing rich aromas that fill your kitchen with the warm, inviting essence of freshly-brewed bliss.

### Not Just Coffee - An Experience

With GlowBrew, it's more than just making coffee-it's about creating an experience that invigorates the mind and pleases the senses. The glow of the lights, the aroma wafting through your space, and the exceptional taste meld into a delightful ritual that prepares you for whatever lies ahead.

## Troubleshooting Made Easy

While GlowBrew is designed to provide a seamless experience, we understand that technology can sometimes be tricky. If you encounter issues with the LED lights, we've got you covered:

- **LED Lights Malfunctioning?**
  - If your LED lights aren't working as expected, don't worry! Follow these steps to restore the glow:
    1. **Reset the Lighting Settings**: Use the GlowBrew app to reset the lighting settings.
    2. **Check Connections**: Ensure that the LED connections inside the GlowBrew are secure.
    3. **Factory Reset**: If you're still facing issues, perform a factory reset to rejuvenate your machine.

With GlowBrew, you not only brew the perfect coffee but do so with an ambiance that excites the senses. Your mornings will never be the same!

## Embrace the Future of Coffee

Join the growing community of GlowBrew enthusiasts today, and redefine how you experience coffee. With stunning visual effects, customized brewing suggestions, and aromatic enhancements, it's time to indulge in the delightful world of GlowBrew-where every cup is an adventure!

### Conclusion

Ready to embark on an extraordinary coffee journey? Discover the perfect blend of technology and flavor with Contoso's GlowBrew. Your coffee awaits!
# Configure the kernel with an AI service and connection details, if necessary
kernel = Kernel()
kernel.add_service(AzureChatCompletion())

# Build the process
kernel_process = process_builder.build()

# Start the process
async with await start(
    process=kernel_process,
    kernel=kernel,
    initial_event=KernelProcessEvent(id="Start", data="Contoso GlowBrew"),
) as process_context:
    _ = await process_context.get_state()

我們會使用異步內容管理員來建置程式並呼叫 start 以執行它。 我們的流程希望由一個稱為 Start 的初始外部事件來啟動,因此我們也提供這個事件。 執行此程式會在控制台中顯示下列輸出:

GatherProductInfoStep
         Gathering product information for Product Name: Contoso GlowBrew
GenerateDocumentationStep
         Generating documentation for provided product_info...
PublishDocumentationStep
         Publishing product documentation:

# GlowBrew AI-Driven Coffee Machine: Elevate Your Coffee Experience

Welcome to the future of coffee enjoyment with GlowBrew, the AI-driven coffee machine that not only crafts the perfect cup but does so with a light show that brightens your day. Designed for coffee enthusiasts and tech aficionados alike, GlowBrew combines cutting-edge brewing technology with an immersive lighting experience to start every day on a bright note.

## Unleash the Power of Luminous Brew Technology

With GlowBrew, your mornings will never be dull. The industry-leading number of programmable LEDs offers endless possibilities for customizing your coffee-making ritual. Sync the light show with the brewing process to create a visually stimulating ambiance that transforms your kitchen into a vibrant café each morning.

## Discover New Flavor Dimensions with the AI Taste Assistant

Leave the traditional coffee routines behind and say hello to personalization sophistication. The AI Taste Assistant learns and adapts to your unique preferences over time. Whether you prefer a strong espresso or a light latte, the assistant suggests new brew combinations tailored to your palate, inviting you to explore a world of flavors you never knew existed.

## Heighten Your Senses with Gourmet Aroma Diffusion

The moment you step into the room, let the GlowBrew’s built-in aroma diffusers captivate your senses. This feature is designed to enrich your coffee’s scent profile, ensuring every cup you brew is a multi-sensory delight. Let the burgeoning aroma energize you before the very first sip.

## Troubleshooting Guide: LED Lights Malfunctioning

Occasionally, you might encounter an issue with the LED lights not functioning as intended. Here’s how to resolve it efficiently:

- **Reset Lighting Settings**: Start by using the GlowBrew app to reset the lighting configurations to their default state.
- **Check Connections**: Ensure that all LED connections inside your GlowBrew machine are secure and properly connected.
- **Perform a Factory Reset**: If the problem persists, perform a factory reset on your GlowBrew to restore all settings to their original state.

Experience the art of coffee making like never before with the GlowBrew AI-driven coffee machine. From captivating light shows to aromatic sensations, every feature is engineered to enhance your daily brew. Brew, savor, and glow with GlowBrew.

接下來是什麼?

文件生成過程的第一個草稿已在運作,但還有很大的改進空間。 生產版本至少需要:

  • 校對代理程序將對產生的文件進行評分,並確認其符合我們的品質和準確性標準。
  • 審批流程,即文件僅在人為核准後才會發佈(人工介入)。