Примечание.
Для доступа к этой странице требуется авторизация. Вы можете попробовать войти или изменить каталоги.
Для доступа к этой странице требуется авторизация. Вы можете попробовать изменить каталоги.
На этом шаге руководства показано, как использовать инструменты функций с агентом, который работает на базе службы завершения чата Azure OpenAI.
Это важно
Не все типы агентов поддерживают средства функций. Некоторые могут поддерживать только пользовательские встроенные средства, не позволяя вызывающему предоставлять свои собственные функции. На этом шаге используется ChatClientAgent, который поддерживает инструменты функций.
Предпосылки
Предварительные требования и установка пакетов NuGet см. в разделе "Создание и запуск простого агента " в этом руководстве.
Создание агента с помощью средств функций
Средства функций — это просто пользовательский код, который нужно, чтобы агент мог вызывать при необходимости.
Вы можете превратить любой метод C# в инструмент функции, используя AIFunctionFactory.Create метод для создания AIFunction экземпляра из метода.
Если вам нужно предоставить дополнительные описания функции или его параметров агенту, чтобы он был более точно выбирать между разными функциями, можно использовать System.ComponentModel.DescriptionAttribute атрибут в методе и его параметрах.
Вот пример простой функции, которая имитирует получение данных о погоде для указанного местоположения. Он снабжен атрибутами описания для предоставления дополнительных сведений о себе и его параметре расположения агенту.
using System.ComponentModel;
[Description("Get the weather for a given location.")]
static string GetWeather([Description("The location to get the weather for.")] string location)
=> $"The weather in {location} is cloudy with a high of 15°C.";
При создании агента теперь можно предоставить агенту функциональное средство, передав список инструментов в метод AsAIAgent.
using System;
using Azure.AI.OpenAI;
using Azure.Identity;
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;
using OpenAI;
AIAgent agent = new AzureOpenAIClient(
new Uri("https://<myresource>.openai.azure.com"),
new DefaultAzureCredential())
.GetChatClient("gpt-4o-mini")
.AsAIAgent(instructions: "You are a helpful assistant", tools: [AIFunctionFactory.Create(GetWeather)]);
Предупреждение
DefaultAzureCredential удобно для разработки, но требует тщательного рассмотрения в рабочей среде. В рабочей среде рекомендуется использовать определенные учетные данные (например, ManagedIdentityCredential), чтобы избежать проблем с задержкой, непреднамеренной проверки данных аутентификации и потенциальных рисков безопасности из-за резервных механизмов.
Теперь вы можете просто запустить агент как обычно, и агент сможет вызывать инструмент функции GetWeather при необходимости.
Console.WriteLine(await agent.RunAsync("What is the weather like in Amsterdam?"));
Подсказка
Полные примеры запуска см. в примерах .NET .
Это важно
Не все типы агентов поддерживают средства функций. Некоторые могут поддерживать только пользовательские встроенные средства, не позволяя вызывающему предоставлять свои собственные функции. На этом шаге используются агенты, созданные с помощью клиентов чата, которые поддерживают функциональные инструменты.
Предпосылки
Для предварительных требований и установки пакетов Python см. шаг Создание и запуск простого агента в этом учебном пособии.
Создание агента с помощью средств функций
Средства функций — это просто пользовательский код, который нужно, чтобы агент мог вызывать при необходимости.
Вы можете превратить любую функцию Python в средство-функцию, передав его параметру агента tools при создании агента.
Если вам нужно указать дополнительные описания функции или её параметров агенту, чтобы он мог более точно выбирать между разными функциями, можно использовать аннотации типов Python с Annotated и возможности Pydantic Field для предоставления описаний.
Вот пример простой функции, которая имитирует получение данных о погоде для указанного местоположения. В нем используются аннотации типов для предоставления дополнительных описаний об функции и ее параметре "расположение" агенту.
from typing import Annotated
from pydantic import Field
def get_weather(
location: Annotated[str, Field(description="The location to get the weather for.")],
) -> str:
"""Get the weather for a given location."""
return f"The weather in {location} is cloudy with a high of 15°C."
Вы также можете использовать @tool декоратор для явного указания имени и описания функции:
from typing import Annotated
from pydantic import Field
from agent_framework import tool
@tool(name="weather_tool", description="Retrieves weather information for any location")
def get_weather(
location: Annotated[str, Field(description="The location to get the weather for.")],
) -> str:
return f"The weather in {location} is cloudy with a high of 15°C."
Если в декораторе не указаны параметры name и description, фреймворк автоматически будет использовать имя функции и docstring в качестве резервных вариантов.
Использование явных схем с @tool
Если вам нужен полный контроль над схемой, предоставляемой модели, передайте параметр schema в @tool.
Вы можете указать модель Pydantic или необработанный словарь схемы JSON.
# Load environment variables from .env file
load_dotenv()
# Approach 1: Pydantic model as explicit schema
class WeatherInput(BaseModel):
"""Input schema for the weather tool."""
location: Annotated[str, Field(description="The city name to get weather for")]
unit: Annotated[str, Field(description="Temperature unit: celsius or fahrenheit")] = "celsius"
@tool(
name="get_weather",
description="Get the current weather for a given location.",
schema=WeatherInput,
approval_mode="never_require",
"""Get the current weather for a location."""
return f"The weather in {location} is 22 degrees {unit}."
# Approach 2: JSON schema dictionary as explicit schema
get_current_time_schema = {
"type": "object",
"properties": {
"timezone": {"type": "string", "description": "The timezone to get the current time for", "default": "UTC"},
},
}
@tool(
name="get_current_time",
description="Get the current time in a given timezone.",
Создание инструментов, предназначенных исключительно для деклараций
Если средство реализуется за пределами фреймворка (например, на стороне клиента в пользовательском интерфейсе), его можно объявить без реализации, используя FunctionTool(..., func=None).
Модель по-прежнему может анализировать и вызвать инструмент, а приложение может предоставить результат позже.
# Load environment variables from .env file
load_dotenv()
# A declaration-only tool: the schema is sent to the LLM, but the framework
# has no implementation to execute. The caller must supply the result.
get_user_location = FunctionTool(
name="get_user_location",
func=None,
description="Get the user's current city. Only the client application can resolve this.",
input_model={
"type": "object",
"properties": {
"reason": {"type": "string", "description": "Why the location is needed"},
При создании агента теперь можно предоставить ему функциональный инструмент, передав его в параметр tools.
import asyncio
from agent_framework.azure import AzureOpenAIChatClient
from azure.identity import AzureCliCredential
agent = AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
instructions="You are a helpful assistant",
tools=get_weather
)
Теперь вы можете просто запустить агент как обычно, и агент сможет вызывать инструмент функции get_weather при необходимости.
async def main():
result = await agent.run("What is the weather like in Amsterdam?")
print(result.text)
asyncio.run(main())
Создание класса с несколькими инструментами функций
Вы также можете создать класс, содержащий несколько инструментов функций в качестве методов. Это может быть полезно для упорядочивания связанных функций или для передачи состояния между ними.
class WeatherTools:
def __init__(self):
self.last_location = None
def get_weather(
self,
location: Annotated[str, Field(description="The location to get the weather for.")],
) -> str:
"""Get the weather for a given location."""
return f"The weather in {location} is cloudy with a high of 15°C."
def get_weather_details(self) -> int:
"""Get the detailed weather for the last requested location."""
if self.last_location is None:
return "No location specified yet."
return f"The detailed weather in {self.last_location} is cloudy with a high of 15°C, low of 7°C, and 60% humidity."
При создании агента теперь можно указать все методы класса в качестве функций:
tools = WeatherTools()
agent = AzureOpenAIChatClient(credential=AzureCliCredential()).as_agent(
instructions="You are a helpful assistant",
tools=[tools.get_weather, tools.get_weather_details]
)
Функции также могут быть декорированы тем же @tool декоратором, что и раньше.
Полный пример
# Copyright (c) Microsoft. All rights reserved.
import asyncio
from typing import Annotated, Any
from agent_framework import tool
from agent_framework.openai import OpenAIResponsesClient
from pydantic import Field
"""
AI Function with kwargs Example
This example demonstrates how to inject custom keyword arguments (kwargs) into an AI function
from the agent's run method, without exposing them to the AI model.
This is useful for passing runtime information like access tokens, user IDs, or
request-specific context that the tool needs but the model shouldn't know about
or provide.
"""
# Define the function tool with **kwargs to accept injected arguments
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/02-agents/tools/function_tool_with_approval.py and samples/02-agents/tools/function_tool_with_approval_and_sessions.py.
@tool(approval_mode="never_require")
def get_weather(
location: Annotated[str, Field(description="The location to get the weather for.")],
**kwargs: Any,
) -> str:
"""Get the weather for a given location."""
# Extract the injected argument from kwargs
user_id = kwargs.get("user_id", "unknown")
# Simulate using the user_id for logging or personalization
print(f"Getting weather for user: {user_id}")
return f"The weather in {location} is cloudy with a high of 15°C."
async def main() -> None:
agent = OpenAIResponsesClient().as_agent(
name="WeatherAgent",
instructions="You are a helpful weather assistant.",
tools=[get_weather],
)
# Pass the injected argument when running the agent
# The 'user_id' kwarg will be passed down to the tool execution via **kwargs
response = await agent.run("What is the weather like in Amsterdam?", user_id="user_123")
print(f"Agent: {response.text}")
if __name__ == "__main__":
asyncio.run(main())
# Copyright (c) Microsoft. All rights reserved.
import asyncio
from typing import Annotated, Any
from agent_framework import tool
from agent_framework.openai import OpenAIResponsesClient
from pydantic import Field
"""
AI Function with kwargs Example
This example demonstrates how to inject custom keyword arguments (kwargs) into an AI function
from the agent's run method, without exposing them to the AI model.
This is useful for passing runtime information like access tokens, user IDs, or
request-specific context that the tool needs but the model shouldn't know about
or provide.
"""
# Define the function tool with **kwargs to accept injected arguments
# NOTE: approval_mode="never_require" is for sample brevity. Use "always_require" in production; see samples/02-agents/tools/function_tool_with_approval.py and samples/02-agents/tools/function_tool_with_approval_and_sessions.py.
@tool(approval_mode="never_require")
def get_weather(
location: Annotated[str, Field(description="The location to get the weather for.")],
**kwargs: Any,
) -> str:
"""Get the weather for a given location."""
# Extract the injected argument from kwargs
user_id = kwargs.get("user_id", "unknown")
# Simulate using the user_id for logging or personalization
print(f"Getting weather for user: {user_id}")
return f"The weather in {location} is cloudy with a high of 15°C."
async def main() -> None:
agent = OpenAIResponsesClient().as_agent(
name="WeatherAgent",
instructions="You are a helpful weather assistant.",
tools=[get_weather],
)
# Pass the injected argument when running the agent
# The 'user_id' kwarg will be passed down to the tool execution via **kwargs
response = await agent.run("What is the weather like in Amsterdam?", user_id="user_123")
print(f"Agent: {response.text}")
if __name__ == "__main__":
asyncio.run(main())