Partager via


Configuration des agents avec les plugins du noyau sémantique

Important

Cette fonctionnalité se trouve dans la phase candidate de mise en production. Les fonctionnalités à ce stade sont presque complètes et généralement stables, bien qu’elles puissent subir des améliorations mineures ou des optimisations avant d’atteindre une disponibilité générale complète.

Fonctions et Plugins dans le noyau sémantique

La fonction d'appel est un outil puissant qui permet aux développeurs d'ajouter des fonctionnalités personnalisées et d'étendre les capacités des applications d'intelligence artificielle. L'architecture des plugins du Semantic Kernel offre un cadre flexible pour prendre en charge l'« appel de fonction ». Pour un Agent, l'intégration des Plugins et de l'Appel de fonction repose sur cette caractéristique fondamentale du noyau sémantique.

Une fois configuré, un agent choisira quand et comment appeler une fonction disponible, comme il le ferait dans toute utilisation en dehors de Agent Framework.

Conseil / Astuce

Informations de référence sur l’API :

Conseil / Astuce

Informations de référence sur l’API :

Conseil / Astuce

Informations de référence sur l’API :

Ajout de plugins à un agent

Tout plugin disponible pour un Agent est géré au sein de son instance Kernel respective. Cette configuration permet à chaque Agent d'accéder à des fonctionnalités distinctes en fonction de son rôle spécifique.

Les plugins peuvent être ajoutés au Kernel soit avant, soit après la création du Agent. Le processus d'initialisation des Plugins suit les mêmes schémas utilisés pour toute implémentation du Semantic Kernel, permettant ainsi une cohérence et une facilité d'utilisation dans la gestion des capacités d'IA.

Remarque

Pour un ChatCompletionAgent, le mode d’appel de fonction doit être activé explicitement. OpenAIAssistant agent est toujours basé sur l'appel automatique de fonctions.

// Factory method to produce an agent with a specific role.
// Could be incorporated into DI initialization.
ChatCompletionAgent CreateSpecificAgent(Kernel kernel, string credentials)
{
    // Clone kernel instance to allow for agent specific plug-in definition
    Kernel agentKernel = kernel.Clone();

    // Import plug-in from type
    agentKernel.ImportPluginFromType<StatelessPlugin>();

    // Import plug-in from object
    agentKernel.ImportPluginFromObject(new StatefulPlugin(credentials));

    // Create the agent
    return
        new ChatCompletionAgent()
        {
            Name = "<agent name>",
            Instructions = "<agent instructions>",
            Kernel = agentKernel,
            Arguments = new KernelArguments(
                new OpenAIPromptExecutionSettings()
                {
                    FunctionChoiceBehavior = FunctionChoiceBehavior.Auto()
                })
        };
}

Il existe deux façons de créer un ChatCompletionAgent avec des plugins.

Méthode 1 : Spécifier les plugins via le constructeur

Vous pouvez directement passer une liste de plugins au constructeur.

from semantic_kernel.agents import ChatCompletionAgent

# Create the Chat Completion Agent instance by specifying a list of plugins
agent = ChatCompletionAgent(
    service=AzureChatCompletion(),
    instructions="<instructions>",
    plugins=[SamplePlugin()]
)

Conseil / Astuce

Par défaut, l'appel automatique de fonction est activé. Pour le désactiver, définissez l'argument function_choice_behavior à function_choice_behavior=FunctionChoiceBehavior.Auto(auto_invoke=False) dans le constructeur. Avec ce paramètre, les plugins sont diffusés vers le modèle, mais ils ne sont pas automatiquement invoqués. Si les paramètres d’exécution spécifient le même service_id ou ai_model_id que la configuration du service IA, le comportement d’appel de fonction défini dans les paramètres d’exécution (via KernelArguments) est prioritaire sur le comportement de choix de fonction défini dans le constructeur.

Méthode 2 : Configurer le noyau manuellement

Si aucun noyau n'est fourni via le constructeur, un noyau est automatiquement créé lors de la validation du modèle. Les plugins transmis ont priorité et sont ajoutés au noyau. Pour un contrôle plus précis de l'état du noyau, suivez ces étapes :

from semantic_kernel.agents import ChatCompletionAgent
from semantic_kernel.connectors.ai import FunctionChoiceBehavior
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion, AzureChatPromptExecutionSettings
from semantic_kernel.functions import KernelFunctionFromPrompt
from semantic_kernel.kernel import Kernel

# Create the instance of the Kernel
kernel = Kernel()

# Add the chat completion service to the Kernel
kernel.add_service(AzureChatCompletion())

# Get the AI Service settings
settings = kernel.get_prompt_execution_settings_from_service_id()

# Configure the function choice behavior to auto invoke kernel functions
settings.function_choice_behavior = FunctionChoiceBehavior.Auto()

# Add the Plugin to the Kernel
kernel.add_plugin(SamplePlugin(), plugin_name="<plugin name>")

# Create the agent
agent = ChatCompletionAgent(
    kernel=kernel,
    name=<agent name>,
    instructions=<agent instructions>,
    arguments=KernelArguments(settings=settings),
)

Conseil / Astuce

Si un service_id n'est pas spécifié lors de l'ajout d'un service au noyau, il sera par défaut default. Lors de la configuration de plusieurs services d'IA sur le noyau, il est recommandé de les différencier en utilisant l'argument service_id. Ceci vous permet de récupérer les paramètres d'exécution pour un service_id spécifique et de lier ces paramètres au service souhaité.

var chatCompletion = OpenAIChatCompletion.builder()
    .withModelId("<model-id>")
    .withOpenAIAsyncClient(new OpenAIClientBuilder()
            .credential(new AzureKeyCredential("<api-key>"))
            .endpoint("<endpoint>")
            .buildAsyncClient())
    .build();

Kernel kernel = Kernel.builder()
    .withAIService(ChatCompletionService.class, chatCompletion)
    .withPlugin(KernelPluginFactory.createFromObject(new SamplePlugin(), "<plugin name>"))
    .build();

var agent = ChatCompletionAgent.builder()
    .withKernel(kernel)
    .withName("<agent name>")
    .withInstructions("<agent instructions>")
    .build();

Ajout de fonctions à un agent

Un plugin est l'approche la plus courante pour configurer l'appel de fonction. Cependant, les fonctions individuelles peuvent également être fournies de manière indépendante, y compris les fonctions d'invite.

// Factory method to product an agent with a specific role.
// Could be incorporated into DI initialization.
ChatCompletionAgent CreateSpecificAgent(Kernel kernel)
{
    // Clone kernel instance to allow for agent specific plug-in definition
    Kernel agentKernel = kernel.Clone();

    // Create plug-in from a static function
    var functionFromMethod = agentKernel.CreateFunctionFromMethod(StatelessPlugin.AStaticMethod);

    // Create plug-in from a prompt
    var functionFromPrompt = agentKernel.CreateFunctionFromPrompt("<your prompt instructions>");

    // Add to the kernel
    agentKernel.ImportPluginFromFunctions("my_plugin", [functionFromMethod, functionFromPrompt]);

    // Create the agent
    return
        new ChatCompletionAgent()
        {
            Name = "<agent name>",
            Instructions = "<agent instructions>",
            Kernel = agentKernel,
            Arguments = new KernelArguments(
                new OpenAIPromptExecutionSettings()
                {
                    FunctionChoiceBehavior = FunctionChoiceBehavior.Auto()
                })
        };
}
from semantic_kernel.agents import ChatCompletionAgent
from semantic_kernel.connectors.ai import FunctionChoiceBehavior
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion, AzureChatPromptExecutionSettings
from semantic_kernel.functions import KernelFunctionFromPrompt
from semantic_kernel.kernel import Kernel

# Create the instance of the Kernel
kernel = Kernel()

# Add the chat completion service to the Kernel
kernel.add_service(AzureChatCompletion())

# Create the AI Service settings
settings = AzureChatPromptExecutionSettings()

# Configure the function choice behavior to auto invoke kernel functions
settings.function_choice_behavior = FunctionChoiceBehavior.Auto()

# Add the Plugin to the Kernel
kernel.add_function(
    plugin_name="<plugin_name>",
    function=KernelFunctionFromPrompt(
        function_name="<function_name>",
        prompt="<your prompt instructions>",
    )
)

# Create the agent
agent = ChatCompletionAgent(
    kernel=kernel,
    name=<agent name>,
    instructions=<agent instructions>,
    arguments=KernelArguments(settings=settings),
)
var chatCompletion = OpenAIChatCompletion.builder()
    .withModelId("<model-id>")
    .withOpenAIAsyncClient(new OpenAIClientBuilder()
            .credential(new AzureKeyCredential("<api-key>"))
            .endpoint("<endpoint>")
            .buildAsyncClient())
    .build();

// Create function from method
var functionFromMethod = KernelFunction.createFromMethod(SamplePlugin.class.getMethod("method"), new SamplePlugin());

// Create function from prompt
var functionFromPrompt = KernelFunction.createFromPrompt("<your prompt instructions>");

// Create the kernel with a plugin from the two functions
Kernel kernel = Kernel.builder()
    .withAIService(ChatCompletionService.class, chatCompletion)
    .withPlugin(KernelPluginFactory.createFromFunctions("SamplePlugin", List.of(functionFromMethod, functionFromPrompt)))
    .build();

InvocationContext invocationContext = InvocationContext.builder()
    .withFunctionChoiceBehavior(FunctionChoiceBehavior.auto(true))
    .build();

// Create the agent
var agent = ChatCompletionAgent.builder()
    .withKernel(kernel)
    .withName("<agent name>")
    .withInstructions("<agent instructions>")
    .withInvocationContext(invocationContext)
    .build();

Limitations pour l’appel de fonction de l'agent

Lors de l'invocation directe d'unChatCompletionAgent, tous les comportements de choix de fonction sont pris en charge. Toutefois, lors de l'utilisation d'un OpenAIAssistant, seul l'appel de fonction automatique est actuellement disponible.

Mode d'emploi

Pour un exemple complet de l'utilisation de l'appel de fonction, voir :

Étapes suivantes