先日、Semantic Kernel Agent Frameworkが一般提供(GA)開始となりました。
Agent FrameworkはSemantic KernelのAIエージェント向けのフレームワークです。
アップデートによりマルチエージェントのオーケストレーション機能も強化されたため、本記事ではSemantic Kernel Agent Frameworkでのオーケストレーションに関して記載します。
マルチエージェントのオーケストレーションパターン
Semantic Kernel Agent Frameworkでは、以下のような主要なオーケストレーションパターンが提供されています。
- Concurrent
- 複数エージェントによる独立した分析が必要なタスクに適しています。
- Sequential
- ステップごとに進める必要があるタスクに適しています。
- Handoff
- 動的で明確な手順がないタスクに対応します。
- GroupChat
- 複数エージェント間の多様な意見交換が必要なタスクに有用です。
- Magentic One
- グループチャットに計画管理機能を備えた次世代型のオーケストレーション。
詳しくは以下のサイトでご確認いただけます。
複数エージェントの並列処理
Semantic Kernelによるマルチエージェントの並列処理 - JBS Tech Blogの記事を記載した時点では、Semantic Kernelでのエージェントの並列処理に関しては公式ドキュメントに記載がなく、並列で実行するためのコードを作成する必要がありました。
現在は、SDKで複数エージェントを並列で実行するクラスやメソッドが提供されています。実際にサンプルコードを試したところ、非常に簡単に複数エージェントの並列処理を実行可能になっていました。
サンプルコードは以下のリンクでご確認いただけます。
実行環境
- semantic-kernel 1.30.0
- Python 3.11.9
サンプルコード
公式のサンプルコードに、複数エージェントからの回答を集約するエージェントを追加したコードを記載します。
実行するには以下を環境変数に設定してください。
AZURE_OPENAI_API_KEY="<api_key>" AZURE_OPENAI_ENDPOINT="https://<resource_name>.openai.azure.com/" CHAT_DEPLOYMENT_NAME="<deployment_name>"
処理は以下の流れで行われます。
- 複数のエージェントを作成
- 作成されたエージェントを並列で実行(members=で指定されたエージェントはすべて実行されます。)
- 並列実行の完了を待ち、要約用のエージェントで最終的な回答を生成
import asyncio from semantic_kernel.agents import Agent, ChatCompletionAgent, ConcurrentOrchestration from semantic_kernel.agents.runtime import InProcessRuntime from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion """ The following sample demonstrates how to create a concurrent orchestration for executing multiple agents on the same task in parallel. This sample demonstrates the basic steps of creating and starting a runtime, creating a concurrent orchestration with multiple agents, invoking the orchestration, and finally waiting for the results. """ def get_agents() -> list[Agent]: """Return a list of agents that will participate in the concurrent orchestration. Feel free to add or remove agents. """ physics_agent = ChatCompletionAgent( name="PhysicsExpert", instructions="You are an expert in physics. You answer questions from a physics perspective.", service=AzureChatCompletion(), ) chemistry_agent = ChatCompletionAgent( name="ChemistryExpert", instructions="You are an expert in chemistry. You answer questions from a chemistry perspective.", service=AzureChatCompletion(), ) return [physics_agent, chemistry_agent] def get_summarize_agents() -> Agent: """ Return a summarize agent. """ summarize_agent = ChatCompletionAgent( name="SummarizeAgent", instructions="""Your task is to collect and summarize the responses provided by multiple agents. When crafting your summary, begin by listing the names of the agents who contributed responses, ensuring this introduction is clear and concise. After noting the contributing agents, provide a condensed and clear summary of their answers. Strive to integrate and highlight the key points, avoiding redundancy while maintaining accuracy.""", service=AzureChatCompletion(), ) return summarize_agent async def main(): """Main function to run the agents.""" # 1. Create a concurrent orchestration with multiple agents agents = get_agents() concurrent_orchestration = ConcurrentOrchestration(members=agents) # 2. Create a runtime and start it runtime = InProcessRuntime() runtime.start() # 3. Invoke the orchestration with a task and the runtime task = "What is temperature?" print(f"Task: {task}") orchestration_result = await concurrent_orchestration.invoke( task=task, runtime=runtime, ) # 4. Wait for the results # Note: the order of the results is not guaranteed to be the same # as the order of the agents in the orchestration. value = await orchestration_result.get(timeout=20) for item in value: print(f"# {item.name}: {item.content}") # 5. Stop the runtime after the invocation is complete await runtime.stop_when_idle() # Summarize responses summarize_agent = get_summarize_agents() response_summarize = await summarize_agent.get_response( messages=value, ) print(f"------") print(f"# {response_summarize.name}: {response_summarize.message}") if __name__ == "__main__": asyncio.run(main())
回答例
次の例では、作成されたPhysicsExpertとChemistryExpertがそれぞれ回答を行い、SummarizeAgentが回答を要約していることが確認できます。
Task: What is temperature? ------ # PhysicsExpert: Temperature is a physical quantity that characterizes the thermal state of matter. It is a measure of the average kinetic energy of the particles in a substance. In simpler terms, temperature indicates how hot or cold an object is. From a thermodynamic perspective, temperature is a fundamental parameter that determines the direction of heat transfer between systems. Heat flows from a region of higher temperature to a region of lower temperature until thermal equilibrium is reached. Temperature is measured using various scales, the most common of which are Celsius (°C), Fahrenheit (°F), and Kelvin (K). The Kelvin scale is an absolute temperature scale, starting at absolute zero (0 K), which is the theoretical point at which all particle motion ceases. In the Celsius scale, water freezes at 0 °C and boils at 100 °C under standard atmospheric conditions, while on the Kelvin scale, these points are 273.15 K and 373.15 K, respectively. In summary, temperature is a key physical property that influences many aspects of matter and its interactions, playing a crucial role in thermodynamics, statistical mechanics, and various fields of science and engineering. ------ # ChemistryExpert: Temperature is a measure of the average kinetic energy of the particles in a substance. It quantifies how hot or cold an object is relative to a defined scale, typically measured in degrees Celsius (°C), Kelvin (K), or degrees Fahrenheit (°F). In a more scientific context, temperature reflects the energy state of matter; as the temperature increases, the energy of the particles also increases, leading to greater motion and vibration within the substance. The concepts of temperature play a crucial role in various areas of chemistry, including thermodynamics, reaction kinetics, and the behavior of gases, where temperature can influence reaction rates, equilibrium, and phase changes. For example, according to the ideal gas law, an increase in temperature at constant volume increases pressure, while in chemical reactions, higher temperatures often lead to an increased rate of reaction due to the greater energy available for overcoming activation barriers. Temperature also affects solubility, equilibrium position, and the states of matter (solid, liquid, gas). ------ # SummarizeAgent: Contributing Agents: PhysicsExpert, ChemistryExpert Summary: Both agents agree that temperature is a measure of the average kinetic energy of particles in a substance, serving as an indicator of how fast these particles are moving. They highlight that higher temperatures correspond to faster particle motion and vice versa. Temperature is crucial in thermodynamics and chemistry, affecting properties such as phase changes and reaction rates. Temperature is commonly measured in Celsius (°C), Fahrenheit (°F), and Kelvin (K), with Kelvin being the SI unit, starting at absolute zero (0 K), where particle motion ceases. The agents emphasize the importance of temperature in understanding the behaviors of different states of matter and its implications in scientific contexts, particularly in predicting the behavior of substances under varying conditions.
終わりに
今回はSemantic Kernel Agent Frameworkでのオーケストレーションに関して記載しました。
AutoGenで実装されていた一部の機能がSemantic Kernelに統合されているようで、エージェントの並列実行も非常に簡単に実装可能となりました。
質問に応じて回答する仕組みを追加で実装することで、自動でエージェント選択・並列実行が可能になります。
今後も他のオーケストレーションパターンについて検証を進める予定です。