Microsoft Agent Framework の利点
- 簡略化された API: 複雑さと定型コードの削減。
- パフォーマンスの向上: オブジェクトの作成とメモリ使用量を最適化しました。
- 統合インターフェイス: さまざまな AI プロバイダー間で一貫したパターン。
- 開発者エクスペリエンスの強化: より直感的で検出可能な API。
次のセクションでは、セマンティック カーネル エージェント フレームワークと Microsoft Agent Framework の主な違いをまとめ、コードの移行に役立ちます。
1. 名前空間の更新
セマンティック カーネル
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Agents;
エージェント フレームワーク
Agent Framework 名前空間は Microsoft.Agents.AI下にあります。
Agent Framework は、コンポーネント間の通信に、 Microsoft.Extensions.AI のコア AI メッセージとコンテンツ タイプを使用します。
using Microsoft.Extensions.AI;
using Microsoft.Agents.AI;
2. エージェント作成の簡略化
セマンティック カーネル
セマンティック カーネル内のすべてのエージェントは、 Kernel インスタンスに依存し、指定されていない場合は空の Kernel を持っています。
Kernel kernel = Kernel
.AddOpenAIChatClient(modelId, apiKey)
.Build();
ChatCompletionAgent agent = new() { Instructions = ParrotInstructions, Kernel = kernel };
Microsoft Foundry では、それを使用するローカル エージェント クラスを作成する前に、エージェント リソースをクラウドに作成する必要があります。
PersistentAgentsClient azureAgentClient = AzureAIAgent.CreateAgentsClient(azureEndpoint, new DefaultAzureCredential());
PersistentAgent definition = await azureAgentClient.Administration.CreateAgentAsync(
deploymentName,
instructions: ParrotInstructions);
AzureAIAgent agent = new(definition, azureAgentClient);
Warning
DefaultAzureCredential は開発には便利ですが、運用環境では慎重に考慮する必要があります。 運用環境では、待機時間の問題、意図しない資格情報のプローブ、フォールバック メカニズムによる潜在的なセキュリティ リスクを回避するために、特定の資格情報 ( ManagedIdentityCredential など) を使用することを検討してください。
エージェント フレームワーク
Agent Framework でのエージェントの作成は、すべてのメイン プロバイダーによって提供される拡張機能により簡単になります。
AIAgent openAIAgent = chatClient.AsAIAgent(instructions: ParrotInstructions);
AIAgent azureFoundryAgent = aiProjectClient.AsAIAgent(model: deploymentName, instructions: ParrotInstructions);
AIAgent openAIAssistantAgent = await assistantClient.CreateAIAgentAsync(instructions: ParrotInstructions);
さらに、ホストされるエージェント プロバイダーの場合は、 AsAIAgent メソッドを使用して、既存のホストされているエージェント レコードからエージェントを取得することもできます。
ProjectsAgentRecord agentRecord = await aiProjectClient.AgentAdministrationClient.GetAgentAsync(agentName);
AIAgent azureFoundryAgent = aiProjectClient.AsAIAgent(agentRecord);
3. エージェントスレッド/セッションの作成
セマンティック カーネル
呼び出し元はスレッドの種類を認識し、手動で作成する必要があります。
// Create a thread for the agent conversation.
AgentThread thread = new OpenAIAssistantAgentThread(this.AssistantClient);
AgentThread thread = new AzureAIAgentThread(this.Client);
AgentThread thread = new OpenAIResponseAgentThread(this.Client);
エージェント フレームワーク
エージェントはセッションの作成を担当します。
// New.
AgentSession session = await agent.CreateSessionAsync();
4. ホストエージェントスレッド/セッションクリーンアップ
このケースは、まだホストされているスレッドを提供するいくつかの AI プロバイダーにのみ適用されます。
セマンティック カーネル
スレッドには、 self 削除メソッドがあります。
OpenAI アシスタント プロバイダー:
await thread.DeleteAsync();
エージェント フレームワーク
Note
OpenAI Responses では、会話の処理方法を簡略化する新しい会話モデルが導入されました。 この変更により、現在非推奨となった OpenAI Assistants モデルと比較して、ホストされたチャット履歴管理が簡略化されます。 詳細については、 OpenAI Assistants 移行ガイドを参照してください。
Agent Framework には、ホストされたチャット履歴またはチャット履歴の削除をサポートするプロバイダーが含まれていないので、 AgentSession の種類にチャット履歴またはセッション削除 API はありません。
チャット履歴の削除が必要で、プロバイダーが許可する場合、呼び出し元は作成されたセッションを追跡し、プロバイダーの SDK を介して必要に応じて、関連するチャット hsitory を後で削除する 必要があります 。
OpenAI アシスタント プロバイダー:
await assistantClient.DeleteThreadAsync(session.ConversationId);
5. ツール登録
セマンティック カーネル
関数をツールとして公開するには、次の手順を実行する必要があります。
-
[KernelFunction]属性を使用して関数を装飾します。 -
Pluginクラスを持っているか、KernelPluginFactoryを使用して関数をラップします。 - プラグインを追加する
Kernelがあります。 -
Kernelをエージェントに渡します。
KernelFunction function = KernelFunctionFactory.CreateFromMethod(GetWeather);
KernelPlugin plugin = KernelPluginFactory.CreateFromFunctions("KernelPluginName", [function]);
Kernel kernel = ... // Create kernel
kernel.Plugins.Add(plugin);
ChatCompletionAgent agent = new() { Kernel = kernel, ... };
エージェント フレームワーク
Agent Framework では、1 回の呼び出しで、エージェント作成プロセスにツールを直接登録できます。
AIAgent agent = chatClient.AsAIAgent(tools: [AIFunctionFactory.Create(GetWeather)]);
6. エージェントの非ストリーミング呼び出し
InvokeからRun、戻り値の型、パラメーターAgentRunOptionsまでのメソッド名に主な違いがあります。
セマンティック カーネル
非ストリーミングでは、複数のエージェント メッセージを返すストリーミング パターン IAsyncEnumerable<AgentResponseItem<ChatMessageContent>> を使用します。
await foreach (AgentResponseItem<ChatMessageContent> result in agent.InvokeAsync(userInput, thread, agentOptions))
{
Console.WriteLine(result.Message);
}
エージェント フレームワーク
非ストリーミングは、複数のメッセージを含むことができるエージェント応答を含む単一の AgentResponse を返します。
実行のテキスト結果は、 AgentResponse.Text または AgentResponse.ToString()で使用できます。
応答の一部として作成されたすべてのメッセージは、 AgentResponse.Messages リストに返されます。
これには、ツール呼び出しメッセージ、関数の結果、推論の更新、および最終的な結果が含まれる場合があります。
AgentResponse agentResponse = await agent.RunAsync(userInput, session);
7. エージェント ストリーミング呼び出し
主な違いは、 Invoke から Run、戻り値の型、パラメーター AgentRunOptionsまでのメソッド名です。
セマンティック カーネル
await foreach (StreamingChatMessageContent update in agent.InvokeStreamingAsync(userInput, thread))
{
Console.Write(update);
}
エージェント フレームワーク
Agent Framework にも同様のストリーミング API パターンがあります。主な違いは、更新ごとにエージェント関連の情報を含む AgentResponseUpdate オブジェクトを返す点です。
AIAgent の基になるサービスによって生成されたすべての更新が返されます。 エージェントのテキスト結果は、 AgentResponse.Text 値を連結することによって使用できます。
await foreach (AgentResponseUpdate update in agent.RunStreamingAsync(userInput, session))
{
Console.Write(update); // Update is ToString() friendly
}
8. ツール関数シグネチャ
問題: プラグイン メソッドSemantic Kernelには[KernelFunction]属性が必要です。
public class MenuPlugin
{
[KernelFunction] // Required.
public static MenuItem[] GetMenu() => ...;
}
解決策: Agent Framework では、属性なしでメソッドを直接使用できます。
public class MenuTools
{
[Description("Get menu items")] // Optional description.
public static MenuItem[] GetMenu() => ...;
}
9. オプションの構成
問題: Semantic Kernelでの複雑なオプションの設定。
OpenAIPromptExecutionSettings settings = new() { MaxTokens = 1000 };
AgentInvokeOptions options = new() { KernelArguments = new(settings) };
解決策: Agent Framework の簡略化されたオプション。
ChatClientAgentRunOptions options = new(new() { MaxOutputTokens = 1000 });
Important
この例では、実装固有のオプションを ChatClientAgentに渡す方法を示します。 すべての AIAgents が ChatClientAgentRunOptionsをサポートしているわけではありません。
ChatClientAgent は、基になる推論サービスに基づいてエージェントを構築するために提供されるため、 MaxOutputTokensなどの推論オプションをサポートします。
10. 依存関係の挿入
セマンティック カーネル
エージェントの抽象化はすべて Kernel プロパティを使用して初期化する必要があります。そのため、エージェントを作成できるようにするには、サービス コンテナーにKernel登録が必要です。
セマンティック カーネルは、エージェントの基本抽象化クラスとして Agent 型を使用します。
services.AddKernel().AddProvider(...);
serviceContainer.AddKeyedSingleton<SemanticKernel.Agents.Agent>(
TutorName,
(sp, key) =>
new ChatCompletionAgent()
{
// Passing the kernel is required.
Kernel = sp.GetRequiredService<Kernel>(),
});
エージェント フレームワーク
Agent Framework は、基本抽象化クラスとして AIAgent 型を提供します。
services.AddKeyedSingleton<AIAgent>(() => client.AsAIAgent(...));
11. エージェントの種類の統合
セマンティック カーネル
セマンティック カーネルは、次に例を示すさまざまなサービスに固有のエージェント クラスを提供します。
-
ChatCompletionAgentチャット補完ベースの推論サービスで使用できます。 -
OpenAIAssistantAgentOpenAI Assistants サービスで使用できます。 -
AzureAIAgentは Foundry Agent Service で使用できます。
エージェント フレームワーク
Agent Framework は、単一のエージェントの種類 ( ChatClientAgent) を介して、上記のすべてのサービスをサポートします。
ChatClientAgent は、 IChatClient インターフェイスを実装する SDK を提供する基になるサービスを使用してエージェントを構築するために使用できます。
主な違い
コードの移行に役立つセマンティック カーネル エージェント フレームワークと Microsoft Agent Framework の主な違いの概要を次に示します。
1. 更新プログラムのパッケージ化とインポート
セマンティック カーネル
セマンティック カーネル パッケージは、 semantic-kernel としてインストールされ、 semantic_kernelとしてインポートされます。 パッケージには、さまざまな AI プロバイダーやその他の機能のさまざまな依存関係をインストールするためにインストールできる多数の extras もあります。
from semantic_kernel import Kernel
from semantic_kernel.agents import ChatCompletionAgent
エージェント フレームワーク
Agent Framework パッケージは agent-framework としてインストールされ、 agent_frameworkとしてインポートされます。
エージェント フレームワークの構築方法は異なり、コア機能を含むコア パッケージ agent-framework-core があり、そのコア パッケージに依存するパッケージ ( agent-framework-openai、 agent-framework-foundry、 agent-framework-mem0、 agent-framework-copilotstudioなど) が複数存在します。 pip install agent-framework 実行すると、コア パッケージとメタ パッケージに付属するプロバイダー パッケージがインストールされるため、一般的な機能をすぐに使い始めることができます。 必要なものがわかっているため、パッケージの数を減らす準備ができたら、必要なパッケージのみをインストールできます。たとえば、Foundry と Mem0 のみを使用する場合は、これら 2 つのパッケージのみをインストールできます。 pip install --pre agent-framework-foundry agent-framework-mem0、 agent-framework-core はこれら 2 つのパッケージへの依存関係であるため、自動的にインストールされます。
パッケージが分割されていても、インポートはすべて agent_frameworkから、またはモジュールです。 たとえば、Foundry のクライアントをインポートするには、次のようにします。
from agent_framework.foundry import FoundryChatClient
最もよく使用される型の多くは、 agent_frameworkから直接インポートされます。
from agent_framework import Message, Agent
2. エージェントの種類の統合
セマンティック カーネル
セマンティック カーネルは、ChatCompletionAgent、AzureAIAgent、OpenAIAssistantAgent など、さまざまなサービスに固有のエージェント クラスを提供します。 セマンティック カーネルのエージェントの種類を参照してください。
エージェント フレームワーク
Agent Framework では、ほとんどのエージェントは、Foundry、OpenAI ChatCompletion、OpenAI Responses などのすべてのAgent ベースのサービスで使用できるChatClientを使用して構築されます。 エージェントには、Copilot Studio で使用する CopilotStudioAgent と A2A で使用する A2AAgent の 2 つがあります。
すべての組み込みエージェントは、BaseAgent (from agent_framework import BaseAgent) に基づいています。 また、すべてのエージェントは、 SupportsAgentRun (from agent_framework import SupportsAgentRun) インターフェイスと一貫性があります。
3. エージェント作成の簡略化
セマンティック カーネル
セマンティック カーネル内のすべてのエージェントは、 Kernel インスタンスに依存し、指定されていない場合は空の Kernel を持つことになります。
from semantic_kernel.agents import ChatCompletionAgent
from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion
agent = ChatCompletionAgent(
service=OpenAIChatCompletion(),
name="Support",
instructions="Answer in one sentence.",
)
エージェント フレームワーク
Agent Framework でのエージェントの作成は、次の 2 つの方法で直接実行できます。
from agent_framework import Agent, Message
from agent_framework.foundry import FoundryChatClient
from azure.identity import AzureCliCredential
agent = Agent(client=FoundryChatClient(credential=AzureCliCredential()), instructions="You are a helpful assistant")
または、チャット クライアントによって提供される便利なメソッドを使用します。
from agent_framework.foundry import FoundryChatClient
from azure.identity import AzureCliCredential
agent = FoundryChatClient(credential=AzureCliCredential()).as_agent(instructions="You are a helpful assistant")
ダイレクト メソッドは、エージェントに対して設定できるすべてのパラメーターを公開します。 便利なメソッドにはサブセットが含まれていますが、ダイレクト メソッドを内部的に呼び出すので、同じパラメーター セットを渡すことができます。
4. エージェント スレッドの作成
セマンティック カーネル
呼び出し元はスレッドの種類を認識し、手動で作成する必要があります。
from semantic_kernel.agents import ChatHistoryAgentThread
thread = ChatHistoryAgentThread()
エージェント フレームワーク
エージェントは、新しいスレッドを作成するように求めることができます。
agent = ...
session = agent.create_session()
エージェント/クライアントと実行オプションに応じて、セッションをローカルまたはサービスでバックアップできます。
- 新しいローカル セッションに
agent.create_session()を使用します。 - サービスで管理される会話を続行する場合は、
agent.get_session(service_session_id=...)を使用します。 -
session=sessionを使用してセッションをagent.run(...)に渡します。
エージェント フレームワーク
Note
OpenAI Responses では、会話の処理方法を簡略化する新しい会話モデルが導入されました。 これにより、現在非推奨になった OpenAI Assistants モデルと比較して、ホストされたスレッド管理が簡略化されます。 詳細については、 OpenAI Assistants 移行ガイドを参照してください。
Agent Framework では、すべてのプロバイダーがホストされたスレッドまたはスレッドの削除をサポートしているわけではないので、 AgentThread の種類にスレッド削除 API はありません。これは、より多くのプロバイダーが応答ベースのアーキテクチャに移行するにつれて一般的になります。
スレッドの削除が必要で、プロバイダーがこれを許可する場合、呼び出し元は作成されたスレッドを追跡し、後でプロバイダーの SDK を使用して必要に応じて削除する必要 があります 。
OpenAI アシスタント プロバイダー:
# OpenAI Assistants threads have self-deletion method in Semantic Kernel
await thread.delete_async()
5. ツール登録
セマンティック カーネル
関数をツールとして公開するには、次の手順を実行する必要があります。
-
@kernel_functionデコレーターで関数を装飾します。 -
Pluginクラスを持っているか、カーネル プラグイン ファクトリを使用して関数をラップします。 - プラグインを追加する
Kernelがあります。 -
Kernelをエージェントに渡します。
from semantic_kernel.functions import kernel_function
class SpecialsPlugin:
@kernel_function(name="specials", description="List daily specials")
def specials(self) -> str:
return "Clam chowder, Cobb salad, Chai tea"
agent = ChatCompletionAgent(
service=OpenAIChatCompletion(),
name="Host",
instructions="Answer menu questions accurately.",
plugins=[SpecialsPlugin()],
)
エージェント フレームワーク
1 回の呼び出しで、エージェント作成プロセスでツールを直接登録できます。 Agent Framework には、複数の関数をラップするプラグインの概念はありませんが、必要に応じてそれを行うことができます。
ツールを作成する最も簡単な方法は、Python 関数を作成することです。
def get_weather(location: str) -> str:
"""Get the weather for a given location."""
return f"The weather in {location} is sunny."
agent = chat_client.as_agent(tools=get_weather)
Note
tools パラメーターは、エージェントの作成とrunメソッド (stream=Trueの有無にかかわらず) とget_response(..., options={"tools": [...]})の両方に存在します。
関数の名前がツールの名前になり、docstring がツールの説明になります。パラメーターに説明を追加することもできます。
from typing import Annotated
def get_weather(location: Annotated[str, "The location to get the weather for."]) -> str:
"""Get the weather for a given location."""
return f"The weather in {location} is sunny."
最後に、デコレーターを使用して、ツールの名前と説明をさらにカスタマイズできます。
from typing import Annotated
from agent_framework import tool
@tool(name="weather_tool", description="Retrieves weather information for any location")
def get_weather(location: Annotated[str, "The location to get the weather for."]):
"""Get the weather for a given location."""
return f"The weather in {location} is sunny."
これは、複数のツールをメソッドとして持つクラスを作成する場合にも機能します。
エージェントを作成するときに、 tools パラメーターに渡すことで、関数ツールをエージェントに提供できるようになりました。
class Plugin:
def __init__(self, initial_state: str):
self.state: list[str] = [initial_state]
def get_weather(self, location: Annotated[str, "The location to get the weather for."]) -> str:
"""Get the weather for a given location."""
self.state.append(f"Requested weather for {location}. ")
return f"The weather in {location} is sunny."
def get_weather_details(self, location: Annotated[str, "The location to get the weather details for."]) -> str:
"""Get detailed weather for a given location."""
self.state.append(f"Requested detailed weather for {location}. ")
return f"The weather in {location} is sunny with a high of 25°C and a low of 15°C."
plugin = Plugin("Initial state")
agent = chat_client.as_agent(tools=[plugin.get_weather, plugin.get_weather_details])
... # use the agent
print("Plugin state:", plugin.state)
Note
クラス内の関数を @tool で修飾して、ツールの名前と説明をカスタマイズすることもできます。
このメカニズムは、接続、シークレットなど、LLM で提供できない追加の入力を必要とするツールにも役立ちます。
互換性: Agent Framework ツールとしての KernelFunction の使用
(プロンプトまたはメソッドから) KernelFunction インスタンスを含むセマンティック カーネル コードが既にある場合は、 .as_agent_framework_tool メソッドを使用して、それらを Agent Framework ツールに変換できます。
Important
この機能には、 semantic-kernel バージョン 1.38 以降が必要です。
プロンプト テンプレートからの KernelFunction の使用
from semantic_kernel import Kernel
from semantic_kernel.functions import KernelFunctionFromPrompt
from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion, OpenAIChatPromptExecutionSettings
from semantic_kernel.prompt_template import KernelPromptTemplate, PromptTemplateConfig
from agent_framework.openai import OpenAIChatClient
# Create a kernel with services and plugins
kernel = Kernel()
# will get the api_key and model from the environment
kernel.add_service(OpenAIChatCompletion(service_id="default"))
# Create a function from a prompt template that uses plugin functions
function_definition = """
Today is: {{time.date}}
Current time is: {{time.time}}
Answer to the following questions using JSON syntax, including the data used.
Is it morning, afternoon, evening, or night (morning/afternoon/evening/night)?
Is it weekend time (weekend/not weekend)?
"""
prompt_template_config = PromptTemplateConfig(template=function_definition)
prompt_template = KernelPromptTemplate(prompt_template_config=prompt_template_config)
# Create a KernelFunction from the prompt
kernel_function = KernelFunctionFromPrompt(
description="Determine the kind of day based on the current time and date.",
plugin_name="TimePlugin",
prompt_execution_settings=OpenAIChatPromptExecutionSettings(service_id="default", max_tokens=100),
function_name="kind_of_day",
prompt_template=prompt_template,
)
# Convert the KernelFunction to an Agent Framework tool
agent_tool = kernel_function.as_agent_framework_tool(kernel=kernel)
# Use the tool with an Agent Framework agent
agent = OpenAIChatClient(model="gpt-4o").as_agent(tools=agent_tool)
response = await agent.run("What kind of day is it?")
print(response.text)
メソッドからの KernelFunction の使用
from semantic_kernel.functions import kernel_function
from agent_framework.openai import OpenAIChatClient
# Create a plugin class with kernel functions
@kernel_function(name="get_weather", description="Get the weather for a location")
def get_weather(self, location: str) -> str:
return f"The weather in {location} is sunny."
# Get the KernelFunction and convert it to an Agent Framework tool
agent_tool = get_weather.as_agent_framework_tool()
# Use the tool with an Agent Framework agent
agent = OpenAIChatClient(model="gpt-4o").as_agent(tools=agent_tool)
response = await agent.run("What's the weather in Seattle?")
print(response.text)
create_search_functionでの VectorStore の使用
セマンティック カーネルの VectorStore と Agent Framework の統合を使用することもできます。 ベクター ストア コレクションの create_search_function メソッドは、Agent Framework ツールに変換できる KernelFunction を返します。
from semantic_kernel import Kernel
from semantic_kernel.connectors.ai.open_ai import OpenAITextEmbedding
from semantic_kernel.connectors.azure_ai_search import AzureAISearchCollection
from semantic_kernel.functions import KernelParameterMetadata
from agent_framework.openai import OpenAIChatClient
# Define your data model
class HotelSampleClass:
HotelId: str
HotelName: str
Description: str
# ... other fields
# Create an Azure AI Search collection
collection = AzureAISearchCollection[str, HotelSampleClass](
record_type=HotelSampleClass,
embedding_generator=OpenAITextEmbedding()
)
async with collection:
await collection.ensure_collection_exists()
# Load your records into the collection
# await collection.upsert(records)
# Create a search function from the collection
search_function = collection.create_search_function(
description="A hotel search engine, allows searching for hotels in specific cities.",
search_type="keyword_hybrid",
filter=lambda x: x.Address.Country == "USA",
parameters=[
KernelParameterMetadata(
name="query",
description="What to search for.",
type="str",
is_required=True,
type_object=str,
),
KernelParameterMetadata(
name="city",
description="The city that you want to search for a hotel in.",
type="str",
type_object=str,
),
KernelParameterMetadata(
name="top",
description="Number of results to return.",
type="int",
default_value=5,
type_object=int,
),
],
string_mapper=lambda x: f"(hotel_id: {x.record.HotelId}) {x.record.HotelName} - {x.record.Description}",
)
# Convert the search function to an Agent Framework tool
search_tool = search_function.as_agent_framework_tool()
# Use the tool with an Agent Framework agent
agent = OpenAIChatClient(model="gpt-4o").as_agent(
instructions="You are a travel agent that helps people find hotels.",
tools=search_tool
)
response = await agent.run("Find me a hotel in Seattle")
print(response.text)
このパターンは、任意のSemantic Kernel VectorStore コネクタ (Foundry IQ (Azure AI 検索)、Qdrant、Pinecone など) で動作し、Agent Framework エージェントで既存のベクター検索インフラストラクチャを活用できます。
この互換性レイヤーを使用すると、セマンティック カーネルから Agent Framework にコードを段階的に移行し、Agent Framework の簡略化されたエージェントの作成と実行パターンを利用しながら、既存の KernelFunction 実装を再利用できます。
6. エージェントの非ストリーミング呼び出し
メソッド名には、 invoke から run、戻り値の型 ( AgentResponseなど) とパラメーターの主な違いがあります。
セマンティック カーネル
非ストリーミング呼び出しでは、非同期反復子パターンを使用して複数のエージェント メッセージを返します。
async for response in agent.invoke(
messages=user_input,
thread=thread,
):
print(f"# {response.role}: {response}")
thread = response.thread
そして、最終的な応答を得るための便利な方法があった:
response = await agent.get_response(messages="How do I reset my bike tire?", thread=thread)
print(f"# {response.role}: {response}")
エージェント フレームワーク
ストリーミング以外の実行では、複数のメッセージを含むことができるエージェント応答を含む単一の AgentResponse が返されます。
実行のテキスト結果は、 response.text または str(response)で使用できます。
応答の一部として作成されたすべてのメッセージは、 response.messages リストに返されます。
これには、ツール呼び出しメッセージ、関数の結果、推論の更新、最終結果が含まれる場合があります。
agent = ...
response = await agent.run(user_input, session=session)
print("Agent response:", response.text)
7. エージェント ストリーミング呼び出し
メソッド名の主な違いは、 invoke から run(..., stream=True)、戻り値の型 (AgentResponseUpdate) とパラメーターです。
セマンティック カーネル
async for update in agent.invoke_stream(
messages="Draft a 2 sentence blurb.",
thread=thread,
):
if update.message:
print(update.message.content, end="", flush=True)
エージェント フレームワーク
同様のストリーミング API パターンと主な違いは、更新ごとにより多くのエージェント関連情報を含む AgentResponseUpdate オブジェクトを返す点です。
エージェントの基になるサービスによって生成されたすべてのコンテンツが返されます。 エージェントの最終的な結果は、 update 値を 1 つの応答に結合することによって使用できます。
from agent_framework import AgentResponse
agent = ...
updates = []
stream = agent.run(user_input, session=session, stream=True)
async for update in stream:
updates.append(update)
print(update.text)
full_response = AgentResponse.from_updates(updates)
print("Full agent response:", full_response.text)
これを直接行うことさえできます。
from agent_framework import AgentResponse
agent = ...
full_response = await AgentResponse.from_update_generator(agent.run(user_input, session=session, stream=True))
print("Full agent response:", full_response.text)
8. オプションの構成
問題: Semantic Kernelでの複雑なオプションの設定
from semantic_kernel.connectors.ai.open_ai import OpenAIPromptExecutionSettings
settings = OpenAIPromptExecutionSettings(max_tokens=1000)
arguments = KernelArguments(settings)
response = await agent.get_response(user_input, thread=thread, arguments=arguments)
解決策: Agent Framework での TypedDict ベースの簡略化されたオプション
Agent Framework は、 ChatClients と Agentsに TypedDict ベースのオプション システムを使用します。 オプションは、1 つの options パラメーターを介して型指定されたディクショナリとして渡され、完全な IDE オートコンプリートと型チェック用のプロバイダー固有の TypedDict クラス ( OpenAIChatOptions など) が含まれます。
from agent_framework.openai import OpenAIChatClient
client = OpenAIChatClient()
# Set default options at agent creation
agent = client.as_agent(
instructions="You are a helpful assistant.",
default_options={
"max_tokens": 1000,
"temperature": 0.7,
}
)
# Override options per call
response = await agent.run(
user_input,
thread,
options={
"max_tokens": 500,
"frequency_penalty": 0.5,
}
)
Note
toolsパラメーターとinstructions パラメーターは、エージェントの作成およびrun()メソッドの直接キーワード引数として残り、options ディクショナリを介して渡されません。 詳細な移行パターンについては、「 Typed Options Upgrade Guide」を 参照してください。
Note
この機能の Go サポートは近日公開予定です。 最新の状態については、 Agent Framework Go リポジトリ を参照してください。