Chiamata di funzioni con SDK in agenti AI generativi

Utilizzare questa guida per acquisire familiarità con l'uso dell'SDK Java OCI per integrare le chiamate delle funzioni in un'applicazione. I passi riportati di seguito mostrano un esempio di SDK Java OCI per la creazione di uno strumento di chiamata delle funzioni e quindi per l'utilizzo della chat per richiamare lo strumento di chiamata delle funzioni.

Creazione di uno strumento chiamata funzione

I passi riportati di seguito mostrano come utilizzare l'SDK Java OCI per creare uno strumento di chiamata funzione per un agente.

  1. Configurazione del client. Esempio:
    GenerativeAiAgentRuntimeClient agentClient = GenerativeAiAgentRuntimeClient.builder()
           .endpoint(endpoint)
           .configuration(clientConfiguration)
           .build(provider);
  2. Definire una funzione, quindi incorporarla nel file ToolConfig. Ad esempio, ecco una funzione che crea un bucket di storage degli oggetti OCI:
    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. Creare una richiesta di strumento e quindi creare lo strumento utilizzando il client. Esempio:
    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);

Chiacchierare con un agente

Per chattare con un agente che dispone di uno strumento di chiamata funzione, creare prima una sessione e, nella sessione, richiamare la funzione. Di seguito vengono riportati alcuni esempi per questi passi.
  1. Creare una sessione. Esempio:
    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();
    

    Sostituire <agentEndpointId> con l'OCID dell'endpoint agente dalla sezione dei prerequisiti.

  2. Utilizzare la sessione per effettuare una chiamata in chat che richiama la funzione. In questo esempio viene inviato un messaggio all'agente e si prevede una risposta che includa una chiamata di funzione
    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 risposta dell'agente include un campo required-actions che contiene i dettagli della funzione da richiamare.

    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)

    Dalla risposta, estrarre il valore action-id associato alla chiamata di funzione. Questo ID viene utilizzato nel passo successivo per eseguire l'azione.

    String actionId = "<some-action-id>";
    
  3. Eseguire l'azione. La risposta contiene la risposta finale dell'agente, che include il risultato della chiamata di funzione. Esempio:
    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)