バックエンド ツールでは、通常の MAF ツール パイプラインが使用されます。 AG-UI は、クライアントが呼び出しと結果を観察できるようにトランスポート イベントを追加します。個別のツール抽象化は導入されていません。
バックエンド ツールを追加する
MAF エージェントの場合と同様に、ツールを定義して登録します。
using System.ComponentModel;
using Microsoft.Extensions.AI;
[Description("Get the weather for a location.")]
static string GetWeather(
[Description("The city to look up.")] string location) =>
$"The weather in {location} is sunny.";
AITool getWeather = AIFunctionFactory.Create(GetWeather, name: "get_weather");
AIAgent agent = chatClient.AsAIAgent(tools: [getWeather]);
app.MapAGUIServer("/", agent);
複雑な要求または応答の種類の場合は、ASP.NET CoreとAIFunctionFactory.Createに同じJsonSerializerOptionsを構成します。
Tip
完全な実装については、.NETバックエンド ツールのサンプルを参照してください。
ツール スキーマ、依存関係の挿入、エラー処理、および一般的なツール設計については、「 エージェントで関数ツールを使用する」を参照してください。
AG-UI イベント マッピング
エージェントがツールを呼び出すとき:
-
FunctionCallContentは、AG-UITOOL_CALL_START、TOOL_CALL_ARGS、およびTOOL_CALL_ENDイベントとして出力されます。 -
FunctionResultContentは、TOOL_CALL_RESULTイベントとして出力されます。 - テキストやその他のエージェント コンテンツは、引き続き通常どおりストリーミングされます。
.NET クライアントは、翻訳されたコンテンツをFunctionCallContentおよびFunctionResultContentとして受け取ります。
await foreach (AgentResponseUpdate update in agent.RunStreamingAsync(messages, session))
{
foreach (AIContent content in update.Contents)
{
if (content is FunctionCallContent call)
{
Console.WriteLine($"Calling {call.Name}");
}
else if (content is FunctionResultContent result)
{
Console.WriteLine($"Result: {result.Result}");
}
}
}
ツールの結果は、AG-UI クライアントにも公開されるモデル向けの値です。 ツールの結果に加えて共有 UI 状態を出力するには、「 状態管理」で説明されている明示的なマッピングを使用します。
次のステップ
このチュートリアルでは、AG-UI エージェントに関数ツールを追加する方法について説明します。 関数ツールは、データの取得、計算の実行、外部システムとの対話などの特定のタスクを実行するためにエージェントが呼び出すことができるカスタム Python 関数です。 AG-UI では、これらのツールはバックエンドで実行され、その結果は自動的にクライアントにストリーミングされます。
前提条件
開始する前に、 作業の開始 に関するチュートリアルを完了し、次のことを行っていることを確認します。
- Python 3.10 以降
-
agent-framework-ag-uiインストールされました - 構成された Azure OpenAI サービス
- AG-UI サーバーとクライアントのセットアップに関する基本的な理解
Note
これらのサンプルでは、認証に DefaultAzureCredential を使用します。 Azure で認証されていることを確認します (たとえば、 az login経由)。 詳細については、 Azure ID のドキュメントを参照してください。
バックエンド ツールレンダリングとは
バックエンド ツールのレンダリングとは、次のことを意味します。
- 関数ツールがサーバーで定義されている
- AI エージェントは、これらのツールを呼び出すタイミングを決定します
- ツールはバックエンドで実行されます (サーバー側)
- ツール呼び出しイベントと結果がリアルタイムでクライアントにストリーミングされる
- クライアントは、ツールの実行の進行状況に関する更新プログラムを受け取ります
このアプローチでは、次のことが可能になります。
- セキュリティ: 機密性の高い操作はサーバー上に留まる
- 整合性: すべてのクライアントが同じツール実装を使用する
- 透過性: クライアントはツールの実行の進行状況を表示できます
- 柔軟性: クライアント コードを変更せずにツールを更新する
関数ツールの作成
基本関数ツール
@toolデコレーターを使用して、任意の Python 関数をツールに変換できます。
from typing import Annotated
from pydantic import Field
from agent_framework import tool
@tool
def get_weather(
location: Annotated[str, Field(description="The city")],
) -> str:
"""Get the current weather for a location."""
# In a real application, you would call a weather API
return f"The weather in {location} is sunny with a temperature of 22°C."
主な概念
-
@toolデコレーター: エージェントで使用できる関数をマークします - 型注釈: パラメーターの型情報を指定する
-
AnnotatedとField: エージェントがパラメーターを理解するのに役立つ説明を追加する - Docstring: 関数の動作について説明します (エージェントが関数を使用するタイミングを決定するのに役立ちます)
- 戻り値: エージェントに返された結果 (およびクライアントにストリーミング)
多機能ツール
エージェントにさらに多くの機能を提供する複数のツールを提供できます。
from typing import Any
from agent_framework import tool
@tool
def get_weather(
location: Annotated[str, Field(description="The city.")],
) -> str:
"""Get the current weather for a location."""
return f"The weather in {location} is sunny with a temperature of 22°C."
@tool
def get_forecast(
location: Annotated[str, Field(description="The city.")],
days: Annotated[int, Field(description="Number of days to forecast")] = 3,
) -> dict[str, Any]:
"""Get the weather forecast for a location."""
return {
"location": location,
"days": days,
"forecast": [
{"day": 1, "weather": "Sunny", "high": 24, "low": 18},
{"day": 2, "weather": "Partly cloudy", "high": 22, "low": 17},
{"day": 3, "weather": "Rainy", "high": 19, "low": 15},
],
}
関数ツールを使用した AG-UI サーバーの作成
関数ツールを使用した完全なサーバー実装を次に示します。
"""AG-UI server with backend tool rendering."""
import os
from typing import Annotated, Any
from agent_framework import Agent, tool
from agent_framework.openai import OpenAIChatCompletionClient
from agent_framework_ag_ui import add_agent_framework_fastapi_endpoint
from azure.identity import AzureCliCredential
from fastapi import FastAPI
from pydantic import Field
# Define function tools
@tool
def get_weather(
location: Annotated[str, Field(description="The city")],
) -> str:
"""Get the current weather for a location."""
# Simulated weather data
return f"The weather in {location} is sunny with a temperature of 22°C."
@tool
def search_restaurants(
location: Annotated[str, Field(description="The city to search in")],
cuisine: Annotated[str, Field(description="Type of cuisine")] = "any",
) -> dict[str, Any]:
"""Search for restaurants in a location."""
# Simulated restaurant data
return {
"location": location,
"cuisine": cuisine,
"results": [
{"name": "The Golden Fork", "rating": 4.5, "price": "$$"},
{"name": "Bella Italia", "rating": 4.2, "price": "$$$"},
{"name": "Spice Garden", "rating": 4.7, "price": "$$"},
],
}
# Read required configuration
endpoint = os.environ.get("AZURE_OPENAI_ENDPOINT")
deployment_name = os.environ.get("AZURE_OPENAI_CHAT_COMPLETION_MODEL")
if not endpoint:
raise ValueError("AZURE_OPENAI_ENDPOINT environment variable is required")
if not deployment_name:
raise ValueError("AZURE_OPENAI_CHAT_COMPLETION_MODEL environment variable is required")
chat_client = OpenAIChatCompletionClient(
model=deployment_name,
azure_endpoint=endpoint,
api_version=os.getenv("AZURE_OPENAI_API_VERSION"),
credential=AzureCliCredential(),
)
# Create agent with tools
agent = Agent(
name="TravelAssistant",
instructions="You are a helpful travel assistant. Use the available tools to help users plan their trips.",
client=chat_client,
tools=[get_weather, search_restaurants],
)
# Create FastAPI app
app = FastAPI(title="AG-UI Travel Assistant")
add_agent_framework_fastapi_endpoint(app, agent, "/")
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="127.0.0.1", port=8888)
ツール イベントについて
エージェントがツールを呼び出すと、クライアントはいくつかのイベントを受け取ります。
ツール呼び出しイベント
# 1. TOOL_CALL_START - Tool execution begins
{
"type": "TOOL_CALL_START",
"toolCallId": "call_abc123",
"toolCallName": "get_weather"
}
# 2. TOOL_CALL_ARGS - Tool arguments (may stream in chunks)
{
"type": "TOOL_CALL_ARGS",
"toolCallId": "call_abc123",
"delta": "{\"location\": \"Paris, France\"}"
}
# 3. TOOL_CALL_END - Arguments complete
{
"type": "TOOL_CALL_END",
"toolCallId": "call_abc123"
}
# 4. TOOL_CALL_RESULT - Tool execution result
{
"type": "TOOL_CALL_RESULT",
"toolCallId": "call_abc123",
"content": "The weather in Paris, France is sunny with a temperature of 22°C."
}
ツール イベント用の拡張クライアント
ツールの実行を表示する AGUIChatClient を使用した拡張クライアントを次に示します。
"""AG-UI client with tool event handling."""
import asyncio
import os
from agent_framework import Agent
from agent_framework_ag_ui import AGUIChatClient
async def main():
"""Main client loop with tool event display."""
server_url = os.environ.get("AGUI_SERVER_URL", "http://127.0.0.1:8888/")
print(f"Connecting to AG-UI server at: {server_url}\n")
# Create AG-UI chat client
chat_client = AGUIChatClient(endpoint=server_url)
# Create agent with the chat client
agent = Agent(
name="ClientAgent",
client=chat_client,
instructions="You are a helpful assistant.",
)
# Get a thread for conversation continuity
thread = agent.create_session()
try:
while True:
message = input("\nUser (:q or quit to exit): ")
if not message.strip():
continue
if message.lower() in (":q", "quit"):
break
print("\nAssistant: ", end="", flush=True)
async for update in agent.run(message, session=thread, stream=True):
# Display text content
if update.text:
print(f"\033[96m{update.text}\033[0m", end="", flush=True)
# Display tool calls and results
for content in update.contents:
if content.type == "function_call":
print(f"\n\033[95m[Calling tool: {content.name}]\033[0m")
elif content.type == "function_result":
result_text = content.result if isinstance(content.result, str) else str(content.result)
print(f"\033[94m[Tool result: {result_text}]\033[0m")
print("\n")
except KeyboardInterrupt:
print("\n\nExiting...")
except Exception as e:
print(f"\n\033[91mError: {e}\033[0m")
if __name__ == "__main__":
asyncio.run(main())
相互作用の例
強化されたサーバーとクライアントが動作している状態で:
User (:q or quit to exit): What's the weather like in Paris and suggest some Italian restaurants?
[Run Started]
[Tool Call: get_weather]
[Tool Result: The weather in Paris, France is sunny with a temperature of 22°C.]
[Tool Call: search_restaurants]
[Tool Result: {"location": "Paris", "cuisine": "Italian", "results": [...]}]
Based on the current weather in Paris (sunny, 22°C) and your interest in Italian cuisine,
I'd recommend visiting Bella Italia, which has a 4.2 rating. The weather is perfect for
outdoor dining!
[Run Finished]
ツール実装のベスト プラクティス
エラー処理
ツールでエラーを適切に処理します。
@tool
def get_weather(
location: Annotated[str, Field(description="The city.")],
) -> str:
"""Get the current weather for a location."""
try:
# Call weather API
result = call_weather_api(location)
return f"The weather in {location} is {result['condition']} with temperature {result['temp']}°C."
except Exception as e:
return f"Unable to retrieve weather for {location}. Error: {str(e)}"
豊富な戻り値の型
必要に応じて、構造化データを返します。
@tool
def analyze_sentiment(
text: Annotated[str, Field(description="The text to analyze")],
) -> dict[str, Any]:
"""Analyze the sentiment of text."""
# Perform sentiment analysis
return {
"text": text,
"sentiment": "positive",
"confidence": 0.87,
"scores": {
"positive": 0.87,
"neutral": 0.10,
"negative": 0.03,
},
}
説明ドキュメント
エージェントがツールを使用するタイミングを理解するのに役立つ明確な説明を提供します。
@tool
def book_flight(
origin: Annotated[str, Field(description="Departure city and airport code, e.g., 'New York, JFK'")],
destination: Annotated[str, Field(description="Arrival city and airport code, e.g., 'London, LHR'")],
date: Annotated[str, Field(description="Departure date in YYYY-MM-DD format")],
passengers: Annotated[int, Field(description="Number of passengers")] = 1,
) -> dict[str, Any]:
"""
Book a flight for specified passengers from origin to destination.
This tool should be used when the user wants to book or reserve airline tickets.
Do not use this for searching flights - use search_flights instead.
"""
# Implementation
pass
クラスを使用したツールの編成
関連するツールの場合は、クラスで整理します。
from agent_framework import tool
class WeatherTools:
"""Collection of weather-related tools."""
def __init__(self, api_key: str):
self.api_key = api_key
@tool
def get_current_weather(
self,
location: Annotated[str, Field(description="The city.")],
) -> str:
"""Get current weather for a location."""
# Use self.api_key to call API
return f"Current weather in {location}: Sunny, 22°C"
@tool
def get_forecast(
self,
location: Annotated[str, Field(description="The city.")],
days: Annotated[int, Field(description="Number of days")] = 3,
) -> dict[str, Any]:
"""Get weather forecast for a location."""
# Use self.api_key to call API
return {"location": location, "forecast": [...]}
# Create tools instance
weather_tools = WeatherTools(api_key="your-api-key")
# Create agent with class-based tools
agent = Agent(
name="WeatherAgent",
instructions="You are a weather assistant.",
client=OpenAIChatCompletionClient(...),
tools=[
weather_tools.get_current_weather,
weather_tools.get_forecast,
],
)
次のステップ
バックエンド ツールのレンダリングについて理解したら、次のことができます。
- 高度なツールの作成: Agent Framework を使用した関数ツールの作成の詳細
その他のリソース
Go AG-UI サーバーは、通常の Agent Framework 関数ツールを公開できます。
tool/functoolを使用してツールを作成し、ホストされているエージェントにアタッチし、aguiprovider.NewJSONHTTPHandlerを使用してエージェントにサービスを提供します。
searchRestaurants := functool.MustNew(functool.Config{
Name: "search_restaurants",
Description: "Search for restaurants in a location.",
}, func(ctx context.Context, in restaurantSearchRequest) (restaurantSearchResponse, error) {
return restaurantSearchResponse{
Location: in.Location,
Cuisine: in.Cuisine,
Results: []restaurantInfo{{Name: "The Golden Fork", Cuisine: in.Cuisine}},
}, nil
})
a := foundryprovider.NewAgent(endpoint, token, foundryprovider.ModelDeployment(model), foundryprovider.AgentConfig{
Config: agent.Config{
Tools: []tool.Tool{searchRestaurants},
},
})
Tip
完全な実行可能な例については、 AG-UI バックエンド ツールのサンプル を参照してください。