Llamada de función con SDK en agentes de IA generativa

Utilice esta guía para familiarizarse con el uso del SDK de Java de OCI para integrar la llamada de función en una aplicación. En los siguientes pasos se muestra un ejemplo de SDK de Java de OCI para crear una herramienta de llamada de función y, a continuación, utilizar el chat para llamar a la herramienta de llamada de función.

Creación de una herramienta de llamada de función

En los siguientes pasos se muestra cómo utilizar el SDK de Java de OCI para crear una herramienta de llamada de función para un agente.

  1. Configure el cliente. Por ejemplo:.
    GenerativeAiAgentRuntimeClient agentClient = GenerativeAiAgentRuntimeClient.builder()
           .endpoint(endpoint)
           .configuration(clientConfiguration)
           .build(provider);
  2. Defina una función y, a continuación, embeba la función en ToolConfig. Por ejemplo, aquí hay una función que crea un cubo de OCI Object Storage:
    private static Function prepareFunction() throws JsonProcessingException {
    
            String payload="{\n" +
            "                \"type\": \"object\",\n" +
            "                \"properties\": {\n" +
            "                    \"bucket_name\": {\n" +
            "                        \"type\": \"string\",\n" +
            "                        \"description\": \"The name of the bucket to create.\"\n" +
            "                    },\n" +
            "                    \"compartment_ocid\": {\n" +
            "                        \"type\": \"string\",\n" +
            "                        \"description\": \"The OCID of the compartment where the bucket will be created.\"\n" +
            "                    },\n" +
            "                    \"storage_tier\": {\n" +
            "                        \"type\": \"string\",\n" +
            "                        \"enum\": [\"Standard\", \"Archive\"],\n" +
            "                        \"description\": \"The storage tier for the bucket.\"\n" +
            "                    }\n" +
            "                },\n" +
            "                \"required\": [\"bucket_name\", \"compartment_ocid\"],\n" +
            "                \"additionalProperties\": \"false\" \n" +
            "            }\n";
    
            ObjectMapper objectMapper = new ObjectMapper();
            
            Map<String,String> parameters = objectMapper.readValue(payload, HashMap.class);
    
            for (Map.Entry entry : parameters.entrySet()) {
                    String jsonString = objectMapper.writeValueAsString(entry.getValue());
                    entry.setValue(jsonString);
            }
            return Function.builder()
                    .name("object_storage")
                    .description("A function to create object storage bucket")
                    .parameters(parameters)
                    .build();            
    }
     
    private static ToolConfig createFunctionToolConfig() {
            return FunctionCallingToolConfig.builder()
                    .function(prepareFunction())
                    .build();
    }
  3. Cree una solicitud de herramienta y, a continuación, cree la herramienta con el cliente. Por ejemplo:.
    CreateToolDetails createToolDetails = CreateToolDetails.builder()
                    .agentId(agentId)
                    .compartmentId(COMPARTMENT_ID)
                    .toolConfig(toolConfig)
                    .displayName("tool-sdk")
                    .description("tool description")
                    .build();
     CreateToolRequest toolRequest = CreateToolRequest.builder()
                     .createToolDetails(createToolDetails)
                     .build();
    client.createTool(toolRequest);

Chat con un agente

Para chatear con un agente que tiene una herramienta de llamada de función, primero cree una sesión y, en la sesión, llame a la función. A continuación se muestran algunos ejemplos de estos pasos.
  1. Crear una sesión. Por ejemplo:.
    GenerativeAiAgentRuntimeClient agentClient = GenerativeAiAgentRuntimeClient.builder()
            .endpoint(endpoint)
            .configuration(clientConfiguration)
            .build(provider);
     
    // Create a new chat session request
    CreateSessionRequest request = CreateSessionRequest.builder()
            .agentEndpointId(<agentEndpointId>)
            .createSessionDetails(CreateSessionDetails.builder()
                    .description("description")
                    .displayName("display_name")
                    .build())
            .build();
    String sessionId = agentClient.createSession(request)
            .getSession()
            .getId();
    

    Sustituya <agentEndpointId> por el OCID del punto final del agente de la sección de requisitos.

  2. Utilice la sesión para realizar una llamada de chat que llame a la función. En este ejemplo, se envía un mensaje al agente y se espera una respuesta que incluya una llamada de función
    String message = "Create an Object Store.";
     
    // Create Chat request
    final ChatDetails chatDetails = ChatDetails.builder()
            .shouldStream(shouldStream)
            .userMessage(message)
            .sessionId(sessionId)
            .build();
    final ChatRequest chatRequest = ChatRequest.builder()
            .chatDetails(chatDetails)
            .agentEndpointId(agentEndpointId)
            .build();
     
    final ChatResult chatResult = agentClient.chat(chatRequest);
     

    La respuesta del agente incluye un campo required-actions, que contiene los detalles de la función que se va a llamar.

    chatResult(message=null, traces=[], usageDetails=null, 
    requiredActions=[FunctionCallingRequiredAction(super=RequiredAction(super=BmcModel
    (__explicitlySet__=[functionCall, actionId])
    actionId=<some-action-id>),
    functionCall=FunctionCall(super=BmcModel(__explicitlySet__=[name, arguments])name=object_storage,
    arguments=
    {"bucket_name": "my_object_store", 
    "compartment_ocid": "ocid1.compartment.oc1..xxx",
    "storage_tier": "Standard"
    }))], 
    toolResults=null)

    A partir de la respuesta, extraiga el action-id asociado a la llamada de función. Este ID se utiliza en el siguiente paso para realizar la acción.

    String actionId = "<some-action-id>";
    
  3. Realice la acción. La respuesta contiene la respuesta final del agente, que incluye el resultado de la llamada de función. Por ejemplo:.
    String actionId = chatResponse.getChatResult().getRequiredActions().get(0).getActionId();
    String functionCallOutput = "{"bucket_name": "test_bucket", "compartment_ocid": "<compartment_OCID>",
    "storage_tier":"Standard"}";
     
    PerformedAction performedAction = FunctionCallingPerformedAction.builder()
        .actionId(actionId)
        .functionCallOutput(functionCallOutput)
        .build();
     
    // Execute the chat session with the performed action
    final ChatDetails chatDetails = ChatDetails.builder()
            .shouldStream(shouldStream)
            .userMessage(userMessage)
            .performedActions(List.of(performedAction))
            .sessionId(sessionId)
            .build();
    final ChatRequest chatRequest = ChatRequest.builder()
            .chatDetails(chatDetails)
            .agentEndpointId(agentEndpointId)
            .build();
    ChatResult chatResult = agentClient.chat(chatRequest);
     
    # Chat Result:
    # ChatResult(message=The object store 'my_object_store' has been successfully created 
    in the specified compartment with the 'Standard' storage tier., 
    traces=[], usageDetails=null, toolResults=null)