セマンティック カーネル
Von Bedeutung
この機能は実験段階にあります。 この段階の機能は開発中であり、プレビューまたはリリース候補ステージに進む前に変更される可能性があります。
機能は現在 Java では使用できません。
AzureAIAgent
とは何ですか?
AzureAIAgent
は、セマンティック カーネル フレームワーク内の特殊なエージェントであり、シームレスなツール統合を備えた高度な会話機能を提供するように設計されています。 ツールの呼び出しが自動化され、手動での解析と呼び出しが不要になります。 また、エージェントはスレッドを使用して会話履歴を安全に管理し、状態を維持するオーバーヘッドを削減します。 さらに、AzureAIAgent
では、ファイルの取得、コードの実行、Bing、Azure AI Search、Azure Functions、OpenAPI によるデータ操作など、さまざまな組み込みツールがサポートされています。
AzureAIAgent
を使用するには、Azure AI Foundry プロジェクトを利用する必要があります。 次の記事では、Azure AI Foundry の概要、プロジェクトの作成と構成方法、およびエージェント サービスについて説明します。
- Azure AI Foundry とは
- Azure AI Foundry SDK を使用して する
- Azure AI Agent Service とは
- クイック スタート: 新しいエージェント を作成する
開発環境の準備
AzureAIAgent
の開発を続行するには、適切なパッケージを使用して開発環境を構成します。
Microsoft.SemanticKernel.Agents.AzureAI
パッケージをプロジェクトに追加します。
dotnet add package Microsoft.SemanticKernel.Agents.AzureAI --prerelease
Azure.Identity
パッケージを含めることもできます。
dotnet add package Azure.Identity
semantic-kernel
パッケージのインストール:
pip install semantic-kernel
機能は現在 Java では使用できません。
AI プロジェクト クライアントの構成
AzureAIAgent
にアクセスするには、まず、特定の Foundry プロジェクト用に構成されたクライアントを作成する必要があります。最も一般的には、プロジェクト エンドポイントを提供します (Azure AI Foundry SDK: プロジェクトの概要)。
PersistentAgentsClient client = AzureAIAgent.CreateAgentsClient("<your endpoint>", new AzureCliCredential());
ルート ディレクトリ内の .env
ファイルを次の内容に変更します。
AZURE_AI_AGENT_ENDPOINT = "<example-endpoint>"
AZURE_AI_AGENT_MODEL_DEPLOYMENT_NAME = "<example-model-deployment-name>"
構成が定義されると、クライアントが作成される場合があります。
from semantic_kernel.agents import AzureAIAgent
async with (
DefaultAzureCredential() as creds,
AzureAIAgent.create_client(credential=creds) as client,
):
# Your operational code here
基になる endpoint
は、構成されている場合、Pydantic Settings によって取得されます。 それ以外の場合は、 create_client()
メソッドに明示的に渡すことができます。
from semantic_kernel.agents import AzureAIAgent
async with (
DefaultAzureCredential() as creds,
AzureAIAgent.create_client(credential=creds, endpoint="<your-endpoint>") as client,
):
# Your operational code here
機能は現在 Java では使用できません。
AzureAIAgent
を作成する
AzureAIAgent
を作成するには、まず、Azure エージェント サービスを使用して Foundry プロジェクトを構成して初期化し、セマンティック カーネルと統合します。
PersistentAgentsClient client = AzureAIAgent.CreateAgentsClient("<your endpoint>", new AzureCliCredential());
// 1. Define an agent on the Azure AI agent service
PersistentAgent definition = await agentsClient.Administration.CreateAgentAsync(
"<name of the the model used by the agent>",
name: "<agent name>",
description: "<agent description>",
instructions: "<agent instructions>");
// 2. Create a Semantic Kernel agent based on the agent definition
AzureAIAgent agent = new(definition, agentsClient);
from azure.identity.aio import DefaultAzureCredential
from semantic_kernel.agents import AzureAIAgent, AzureAIAgentSettings
async with (
DefaultAzureCredential() as creds,
AzureAIAgent.create_client(credential=creds) as client,
):
# 1. Define an agent on the Azure AI agent service
agent_definition = await client.agents.create_agent(
model=AzureAIAgentSettings().model_deployment_name,
name="<name>",
instructions="<instructions>",
)
# 2. Create a Semantic Kernel agent based on the agent definition
agent = AzureAIAgent(
client=client,
definition=agent_definition,
)
機能は現在 Java では使用できません。
AzureAIAgent
との対話
AzureAIAgent
との対話は簡単です。 エージェントはスレッドを使用して会話履歴を自動的に保持します。
Azure AI エージェント スレッドの詳細は、Microsoft.SemanticKernel.Agents.AzureAI.AzureAIAgentThread
の実装である Microsoft.SemanticKernel.Agents.AgentThread
クラスを介して抽象化されます。
Von Bedeutung
Azure AI Agents SDK には PersistentAgentThread
クラスがあることに注意してください。
Microsoft.SemanticKernel.Agents.AgentThread
と混同しないでください。これは、すべてのスレッド型の一般的なセマンティック カーネル エージェントの抽象化です。
AzureAIAgent
は現在、AzureAIAgentThread
型のスレッドのみをサポートしています。
AzureAIAgentThread agentThread = new(agent.Client);
try
{
ChatMessageContent message = new(AuthorRole.User, "<your user input>");
await foreach (ChatMessageContent response in agent.InvokeAsync(message, agentThread))
{
Console.WriteLine(response.Content);
}
}
finally
{
await agentThread.DeleteAsync();
await agent.Client.DeleteAgentAsync(agent.Id);
}
Azure AI エージェント スレッドの詳細は、AzureAIAgentThread
の実装である AgentThread
クラスを介して抽象化されます。
USER_INPUTS = ["Hello", "What's your name?"]
thread: AzureAIAgentThread = AzureAIAgentThread()
try:
for user_input in USER_INPUTS:
response = await agent.get_response(messages=user_inputs, thread=thread)
print(response)
thread = response.thread
finally:
await thread.delete() if thread else None
必要に応じて、エージェントを次のように呼び出すことができます。
for user_input in USER_INPUTS:
async for content in agent.invoke(messages=user_input, thread=thread):
print(content.content)
thread = response.thread
メッセージの一覧を get_response(...)
、 invoke(...)
、または invoke_stream(...)
メソッドに渡すこともできます。
USER_INPUTS = ["Hello", "What's your name?"]
thread: AzureAIAgentThread = AzureAIAgentThread()
try:
for user_input in USER_INPUTS:
response = await agent.get_response(messages=USER_INPUTS, thread=thread)
print(response)
thread = response.thread
finally:
await thread.delete() if thread else None
エージェントは、ストリーム応答を生成することもできます。
ChatMessageContent message = new(AuthorRole.User, "<your user input>");
await foreach (StreamingChatMessageContent response in agent.InvokeStreamingAsync(message, agentThread))
{
Console.Write(response.Content);
}
for user_input in USER_INPUTS:
await agent.add_chat_message(thread_id=thread.id, message=user_input)
async for content in agent.invoke_stream(thread_id=thread.id):
print(content.content, end="", flush=True)
機能は現在 Java では使用できません。
AzureAIAgent
を使ったプラグインの使用
セマンティック カーネルでは、強化された機能のためのカスタム プラグインを使用した AzureAIAgent
の拡張がサポートされています。
KernelPlugin plugin = KernelPluginFactory.CreateFromType<YourPlugin>();
PersistentAgentsClient client = AzureAIAgent.CreateAgentsClient("<your endpoint>", new AzureCliCredential());
PersistentAgent definition = await agentsClient.Administration.CreateAgentAsync(
"<name of the the model used by the agent>",
name: "<agent name>",
description: "<agent description>",
instructions: "<agent instructions>");
AzureAIAgent agent = new(definition, agentsClient, plugins: [plugin]);
from semantic_kernel.functions import kernel_function
class SamplePlugin:
@kernel_function(description="Provides sample data.")
def get_data(self) -> str:
return "Sample data"
async with (
DefaultAzureCredential() as creds,
AzureAIAgent.create_client(credential=creds) as client,
):
agent_definition = await client.agents.create_agent(
model=AzureAIAgentSettings().model_deployment_name,
)
agent = AzureAIAgent(
client=client,
definition=agent_definition,
plugins=[SamplePlugin()]
)
機能は現在 Java では使用できません。
高度な機能
AzureAIAgent
では、次のような高度なツールを利用できます。
- コード インタープリター
- ファイル検索
- OpenAPI 統合
- Azure AI Search の統合 についての
- Bingグラウンディング
コード インタープリター
コード インタープリターを使用すると、エージェントは、セキュリティで保護された実行環境 (Azure AI エージェント サービス コード インタープリター) で Python コードを記述して実行できます。
PersistentAgentsClient client = AzureAIAgent.CreateAgentsClient("<your endpoint>", new AzureCliCredential());
PersistentAgent definition = await agentsClient.CreateAgentAsync(
"<name of the the model used by the agent>",
name: "<agent name>",
description: "<agent description>",
instructions: "<agent instructions>",
tools: [new CodeInterpreterToolDefinition()],
toolResources:
new()
{
CodeInterpreter = new()
{
FileIds = { ... },
}
}));
AzureAIAgent agent = new(definition, agentsClient);
from azure.ai.agents.models import CodeInterpreterTool
async with (
DefaultAzureCredential() as creds,
AzureAIAgent.create_client(credential=creds) as client,
):
code_interpreter = CodeInterpreterTool()
agent_definition = await client.agents.create_agent(
model=ai_agent_settings.model_deployment_name,
tools=code_interpreter.definitions,
tool_resources=code_interpreter.resources,
)
機能は現在 Java では使用できません。
ファイル検索
ファイル検索は、モデルの外部からの知識を持つエージェントを拡張します (Azure AI エージェント サービス ファイル検索ツール)。
PersistentAgentsClient client = AzureAIAgent.CreateAgentsClient("<your endpoint>", new AzureCliCredential());
PersistentAgent definition = await agentsClient.CreateAgentAsync(
"<name of the the model used by the agent>",
name: "<agent name>",
description: "<agent description>",
instructions: "<agent instructions>",
tools: [new FileSearchToolDefinition()],
toolResources:
new()
{
FileSearch = new()
{
VectorStoreIds = { ... },
}
});
AzureAIAgent agent = new(definition, agentsClient);
from azure.ai.agents.models import FileSearchTool
async with (
DefaultAzureCredential() as creds,
AzureAIAgent.create_client(credential=creds) as client,
):
file_search = FileSearchTool(vector_store_ids=[vector_store.id])
agent_definition = await client.agents.create_agent(
model=ai_agent_settings.model_deployment_name,
tools=file_search.definitions,
tool_resources=file_search.resources,
)
機能は現在 Java では使用できません。
OpenAPI 統合
エージェントを外部 API に接続します (OpenAPI 指定ツールを使用して Azure AI エージェント サービスを使用する方法)。
PersistentAgentsClient client = AzureAIAgent.CreateAgentsClient("<your endpoint>", new AzureCliCredential());
string apiJsonSpecification = ...; // An Open API JSON specification
PersistentAgent definition = await agentsClient.CreateAgentAsync(
"<name of the the model used by the agent>",
name: "<agent name>",
description: "<agent description>",
instructions: "<agent instructions>",
tools: [
new OpenApiToolDefinition(
"<api name>",
"<api description>",
BinaryData.FromString(apiJsonSpecification),
new OpenApiAnonymousAuthDetails())
]
);
AzureAIAgent agent = new(definition, agentsClient);
from azure.ai.agents.models import OpenApiTool, OpenApiAnonymousAuthDetails
async with (
DefaultAzureCredential() as creds,
AzureAIAgent.create_client(credential=creds) as client,
):
openapi_spec_file_path = "sample/filepath/..."
with open(os.path.join(openapi_spec_file_path, "spec_one.json")) as file_one:
openapi_spec_one = json.loads(file_one.read())
with open(os.path.join(openapi_spec_file_path, "spec_two.json")) as file_two:
openapi_spec_two = json.loads(file_two.read())
# Note that connection or managed identity auth setup requires additional setup in Azure
auth = OpenApiAnonymousAuthDetails()
openapi_tool_one = OpenApiTool(
name="<name>",
spec=openapi_spec_one,
description="<description>",
auth=auth,
)
openapi_tool_two = OpenApiTool(
name="<name>",
spec=openapi_spec_two,
description="<description>",
auth=auth,
)
agent_definition = await client.agents.create_agent(
model=ai_agent_settings.model_deployment_name,
tools=openapi_tool_one.definitions + openapi_tool_two.definitions,
)
機能は現在 Java では使用できません。
AzureAI Search の統合
エージェントで既存の Azure AI Search インデックスを使用します (既存の AI Search インデックスを使用します)。
PersistentAgentsClient client = AzureAIAgent.CreateAgentsClient("<your endpoint>", new AzureCliCredential());
PersistentAgent definition = await agentsClient.CreateAgentAsync(
"<name of the the model used by the agent>",
name: "<agent name>",
description: "<agent description>",
instructions: "<agent instructions>",
tools: [new AzureAISearchToolDefinition()],
toolResources: new()
{
AzureAISearch = new()
{
IndexList = { new AISearchIndexResource("<your connection id>", "<your index name>") }
}
});
AzureAIAgent agent = new(definition, agentsClient);
from azure.ai.agents.models import AzureAISearchTool, ConnectionType
async with (
DefaultAzureCredential() as creds,
AzureAIAgent.create_client(credential=creds) as client,
):
conn_list = await client.connections.list()
ai_search_conn_id = ""
for conn in conn_list:
if conn.connection_type == ConnectionType.AZURE_AI_SEARCH:
ai_search_conn_id = conn.id
break
ai_search = AzureAISearchTool(
index_connection_id=ai_search_conn_id,
index_name=AZURE_AI_SEARCH_INDEX_NAME,
)
agent_definition = await client.agents.create_agent(
model=ai_agent_settings.model_deployment_name,
instructions="Answer questions using your index.",
tools=ai_search.definitions,
tool_resources=ai_search.resources,
headers={"x-ms-enable-preview": "true"},
)
機能は現在 Java では使用できません。
Bingグラウンドング
近日公開予定の例。
from azure.ai.agents.models import BingGroundingTool
from azure.identity.aio import DefaultAzureCredential
from semantic_kernel.agents import AzureAIAgent, AzureAIAgentSettings
async with (
DefaultAzureCredential() as creds,
AzureAIAgent.create_client(credential=creds) as client,
):
# 1. Enter your Bing Grounding Connection Name
bing_connection = await client.connections.get(connection_name="<your-bing-grounding-connection-name>")
conn_id = bing_connection.id
# 2. Initialize agent bing tool and add the connection id
bing_grounding = BingGroundingTool(connection_id=conn_id)
# 3. Create an agent with Bing grounding on the Azure AI agent service
agent_definition = await client.agents.create_agent(
name="BingGroundingAgent",
instructions="Use the Bing grounding tool to answer the user's question.",
model=AzureAIAgentSettings().model_deployment_name,
tools=bing_grounding.definitions,
)
# 4. Create a Semantic Kernel agent for the Azure AI agent
agent = AzureAIAgent(
client=client,
definition=agent_definition,
)
Bing Grounding ツールを使用する場合、FunctionCallContent
コールバックに渡されるon_intermediate_message
の関数名は "bing_grounding"
に設定されます。 実行が完了すると、呼び出しが標準かストリーミングかに応じて、 ChatMessageContent.items
リストに AnnotationContent
または StreamingAnnotationContent
が含まれます。 これらの注釈項目には、 FunctionCallContent
に存在する情報と同様に、エージェントが応答中にアクセスしたリンクに関する情報が含まれています。
詳細については、次の概念サンプルを参照してください。
機能は現在 Java では使用できません。
既存の AzureAIAgent
の取得
既存のエージェントは、そのアシスタント ID を指定することで取得および再利用できます。
PersistentAgent definition = await agentsClient.Administration.GetAgentAsync("<your agent id>");
AzureAIAgent agent = new(definition, agentsClient);
agent_definition = await client.agents.get_agent(assistant_id="your-agent-id")
agent = AzureAIAgent(client=client, definition=agent_definition)
機能は現在 Java では使用できません。
AzureAIAgent
の削除
エージェントとそれに関連付けられているスレッドは、不要になったら削除できます。
await agentThread.DeleteAsync();
await agentsClient.Administration.DeleteAgentAsync(agent.Id);
await client.agents.delete_thread(thread.id)
await client.agents.delete_agent(agent.id)
ベクター ストアまたはファイルを操作している場合は、削除することもできます。
await agentsClient.VectorStores.DeleteVectorStoreAsync("<your store id>");
await agentsClient.Files.DeleteFileAsync("<your file id>");
await client.agents.files.delete(file_id=file.id)
await client.agents.vector_stores.delete(vector_store_id=vector_store.id)
機能は現在 Java では使用できません。
ファイル検索 ツールの詳細については、Azure AI Agent Service ファイル検索ツール 記事を参照してください。
使い方
AzureAIAgent
を使用する実際の例については、GitHub のコード サンプルを参照してください。
機能は現在 Java では使用できません。
中間メッセージをAzureAIAgent
を使用して処理する
セマンティック カーネル AzureAIAgent
は、ユーザーのクエリまたは質問を満たすエージェントを呼び出すように設計されています。 呼び出し中、エージェントはツールを実行して最終的な回答を導き出すことができます。 このプロセス中に生成された中間メッセージにアクセスするために、呼び出し元は、 FunctionCallContent
または FunctionResultContent
のインスタンスを処理するコールバック関数を提供できます。
AzureAIAgent
のコールバック ドキュメントは近日公開予定です。
on_intermediate_message
またはagent.invoke(...)
内でagent.invoke_stream(...)
コールバックを構成すると、エージェントの最終的な応答を作成するプロセス中に生成された中間メッセージを呼び出し元が受信できます。
import asyncio
from typing import Annotated
from azure.identity.aio import DefaultAzureCredential
from semantic_kernel.agents import AzureAIAgent, AzureAIAgentSettings, AzureAIAgentThread
from semantic_kernel.contents import FunctionCallContent, FunctionResultContent
from semantic_kernel.contents.chat_message_content import ChatMessageContent
from semantic_kernel.functions import kernel_function
# Define a sample plugin for the sample
class MenuPlugin:
"""A sample Menu Plugin used for the concept sample."""
@kernel_function(description="Provides a list of specials from the menu.")
def get_specials(self) -> Annotated[str, "Returns the specials from the menu."]:
return """
Special Soup: Clam Chowder
Special Salad: Cobb Salad
Special Drink: Chai Tea
"""
@kernel_function(description="Provides the price of the requested menu item.")
def get_item_price(
self, menu_item: Annotated[str, "The name of the menu item."]
) -> Annotated[str, "Returns the price of the menu item."]:
return "$9.99"
# This callback function will be called for each intermediate message,
# which will allow one to handle FunctionCallContent and FunctionResultContent.
# If the callback is not provided, the agent will return the final response
# with no intermediate tool call steps.
async def handle_intermediate_steps(message: ChatMessageContent) -> None:
for item in message.items or []:
if isinstance(item, FunctionResultContent):
print(f"Function Result:> {item.result} for function: {item.name}")
elif isinstance(item, FunctionCallContent):
print(f"Function Call:> {item.name} with arguments: {item.arguments}")
else:
print(f"{item}")
async def main() -> None:
ai_agent_settings = AzureAIAgentSettings()
async with (
DefaultAzureCredential() as creds,
AzureAIAgent.create_client(credential=creds, endpoint=ai_agent_settings.endpoint) as client,
):
AGENT_NAME = "Host"
AGENT_INSTRUCTIONS = "Answer questions about the menu."
# Create agent definition
agent_definition = await client.agents.create_agent(
model=ai_agent_settings.deployment_name,
name=AGENT_NAME,
instructions=AGENT_INSTRUCTIONS,
)
# Create the AzureAI Agent
agent = AzureAIAgent(
client=client,
definition=agent_definition,
plugins=[MenuPlugin()], # add the sample plugin to the agent
)
# Create a thread for the agent
# If no thread is provided, a new thread will be
# created and returned with the initial response
thread: AzureAIAgentThread = None
user_inputs = [
"Hello",
"What is the special soup?",
"How much does that cost?",
"Thank you",
]
try:
for user_input in user_inputs:
print(f"# User: '{user_input}'")
async for response in agent.invoke(
messages=user_input,
thread=thread,
on_intermediate_message=handle_intermediate_steps,
):
print(f"# Agent: {response}")
thread = response.thread
finally:
# Cleanup: Delete the thread and agent
await thread.delete() if thread else None
await client.agents.delete_agent(agent.id)
if __name__ == "__main__":
asyncio.run(main())
エージェント呼び出しプロセスからの出力例を次に示します。
User: 'Hello'
Agent: Hi there! How can I assist you today?
User: 'What is the special soup?'
Function Call:> MenuPlugin-get_specials with arguments: {}
Function Result:>
Special Soup: Clam Chowder
Special Salad: Cobb Salad
Special Drink: Chai Tea
for function: MenuPlugin-get_specials
Agent: The special soup is Clam Chowder. Would you like to know anything else about the menu?
User: 'How much does that cost?'
Function Call:> MenuPlugin-get_item_price with arguments: {"menu_item":"Clam Chowder"}
Function Result:> $9.99 for function: MenuPlugin-get_item_price
Agent: The Clam Chowder costs $9.99. Let me know if you would like assistance with anything else!
User: 'Thank you'
Agent: You're welcome! Enjoy your meal! 😊
機能は現在 Java では使用できません。
宣言型仕様
宣言型仕様の使用に関するドキュメントは近日公開予定です。
Von Bedeutung
この機能は実験段階にあります。 この段階の機能は開発中であり、プレビューまたはリリース候補ステージに進む前に変更される可能性があります。
AzureAIAgent
では、YAML 宣言仕様からのインスタンス化がサポートされています。 宣言型アプローチでは、エージェントのプロパティ、命令、モデル構成、ツール、およびその他のオプションを、監査可能な 1 つのドキュメントで定義できます。 これにより、エージェントの構成を移植可能にし、環境間で簡単に管理できます。
注
宣言型 YAML に記載されているツール、関数、またはプラグインは、構築時にエージェントで使用できる必要があります。 カーネルベースのプラグインの場合、これはカーネルに登録する必要があることを意味します。 Bing Grounding、File Search、OpenAPI ツールなどの組み込みツールの場合は、正しい構成と資格情報を指定する必要があります。 エージェント ローダーは、最初から関数を作成しません。 必要なコンポーネントがない場合、エージェントの作成は失敗します。
宣言型仕様を使用する方法
このセクションでは、考えられるすべての YAML 構成を列挙するのではなく、主要な原則の概要を説明し、各ツールの種類の完全なコードを示す概念サンプルへのリンクを示します。 宣言型の仕様を使用した AzureAIAgent
のエンド ツー エンドの実装については、次の概念サンプルを参照してください。
- 関数プラグイン
- ファイルからの関数プラグイン
- AI 検索
- Bingグラウンディング
- コード インタープリター
- ファイル検索
- OpenAPI
- プロンプト テンプレート
- 既存のエージェント ID からの読み込み
例: YAML からの AzureAIAgent の作成
最小限の YAML 宣言型仕様は、次のようになります。
type: foundry_agent
name: MyAgent
instructions: Respond politely to the user's questions.
model:
id: ${AzureAI:ChatModelId}
tools:
- id: MenuPlugin.get_specials
type: function
- id: MenuPlugin.get_item_price
type: function
エージェントを接続する方法の詳細については、上記の完全なコード サンプルを参照してください。
重要なポイント
- 宣言型仕様を使用すると、YAML でエージェントの構造、ツール、および動作を定義できます。
- 参照されているすべてのツールとプラグインは、実行時に登録またはアクセス可能である必要があります。
- Bing、ファイル検索、コード インタープリターなどの組み込みツールには、適切な構成と資格情報が必要です (多くの場合、環境変数または明示的な引数を使用)。
- 包括的な例については、プラグインの登録、Azure ID の構成、高度なツールの使用など、実際のシナリオを示すサンプル リンクを参照してください。
この機能は使用できません。