Chiamata dell'endpoint API con SDK negli agenti AI generativa

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

Criteri IAM

Assicurarsi di aggiungere criteri per concedere le autorizzazioni appropriate per accedere alle operazioni API del servizio OCI che si desidera vengano richiamate dall'agente.

Nell'esempio, lo strumento di chiamata dell'endpoint API interagisce con i bucket di storage degli oggetti. Puoi utilizzare i criteri riportati di seguito per abilitare l'accesso allo storage degli oggetti in tutti i compartimenti della tenancy o limitare l'accesso a un compartimento specifico.

// To enable access to all compartments in the tenancy
allow any-user to manage object-family in tenancy where any {request.principal.type='genaiagent'} 
// To enable access to a specific compartment in the tenancy
allow any-user to manage object-family in compartment <compartment-name> where any {request.principal.type='genaiagent'} 

Sostituire <compartment-name> con il compartimento che si desidera utilizzare.

Creazione di uno strumento di chiamata endpoint API

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

  1. Configurare un client per interagire con gli agenti AI generativa. Ad esempio:
    // Configure your client
    GenerativeAiAgentRuntimeClient agentClient = GenerativeAiAgentRuntimeClient.builder()
           .endpoint(endpoint)
           .configuration(clientConfiguration)
           .build(provider);

    Nel codice sostituire endpoint e clientConfiguration con i valori appropriati per l'impostazione.

  2. Creare HttpEndpointToolConfig per lo strumento. Ad esempio:
    private static ToolConfig createHttpEndpointToolConfig() {
        return HttpEndpointToolConfig.builder()
                .apiSchema(ApiSchemaInlineInputLocation.builder()
                        .content("{\"openapi\":\"3.0.3\",\"info\":{\"title\":\"OCIObjectStorageAPI\",\"version\":\"1.0.0\",\"description\":\"API for interacting with Oracle Cloud Infrastructure (OCI) Object Storage.\"},\"servers\":[{\"url\":\"https://<namespace>.objectstorage.us-chicago-1.oci.customer-oci.com\"}],\"paths\":{\"/n/<namespace>/b/{bucketName}/o\":{\"get\":{\"summary\":\"List objects in a bucket\",\"description\":\"Retrieves a list of objects stored in the specified bucket.\",\"operationId\":\"listObjects\",\"parameters\":[{\"name\":\"bucketName\",\"in\":\"path\",\"required\":true,\"description\":\"The name of the bucket.\",\"schema\":{\"type\":\"string\"}},{\"name\":\"prefix\",\"in\":\"query\",\"required\":false,\"description\":\"Filter objects by prefix.\",\"schema\":{\"type\":\"string\"}},{\"name\":\"limit\",\"in\":\"query\",\"required\":false,\"description\":\"Maximum number of objects to return.\",\"schema\":{\"type\":\"integer\",\"format\":\"int32\"}},{\"name\":\"start\",\"in\":\"query\",\"required\":false,\"description\":\"Pagination token to start listing from.\",\"schema\":{\"type\":\"string\"}}],\"responses\":{\"200\":{\"description\":\"A list of objects in the bucket.\",\"content\":{\"application/json\":{\"schema\":{\"type\":\"object\",\"properties\":{\"objects\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"properties\":{\"name\":{\"type\":\"string\"},\"size\":{\"type\":\"integer\",\"format\":\"int64\"},\"md5\":{\"type\":\"string\"},\"timeCreated\":{\"type\":\"string\",\"format\":\"date-time\"},\"etag\":{\"type\":\"string\"}}}}}}}}},\"400\":{\"description\":\"Bad request.\"},\"401\":{\"description\":\"Unauthorized request.\"},\"404\":{\"description\":\"Bucket not found.\"},\"500\":{\"description\":\"Internal server error.\"}}},\"/n/<namespace>/b/{bucketName}/o/{objectName}\":{\"delete\":{\"summary\":\"Delete an object from a bucket\",\"description\":\"Deletes a specified object from the given bucket.\",\"operationId\":\"deleteObject\",\"parameters\":[{\"name\":\"bucketName\",\"in\":\"path\",\"required\":true,\"description\":\"The name of the bucket.\",\"schema\":{\"type\":\"string\"}},{\"name\":\"objectName\",\"in\":\"path\",\"required\":true,\"description\":\"The name of the object to delete.\",\"schema\":{\"type\":\"string\"}},{\"name\":\"versionId\",\"in\":\"query\",\"required\":false,\"description\":\"The version ID of the object (if versioning is enabled).\",\"schema\":{\"type\":\"string\"}}],\"responses\":{\"204\":{\"description\":\"Object deleted successfully.\"},\"400\":{\"description\":\"Bad request.\"},\"401\":{\"description\":\"Unauthorized request.\"},\"404\":{\"description\":\"Object not found.\"},\"500\":{\"description\":\"Internal server error.\"}}}}}}")
                        .build())
                .httpEndpointAuthConfig(HttpEndpointAuthConfig.builder()
            .httpEndpointAuthSources(
                    Collections.singletonList(
                            HttpEndpointAuthSource.builder()
                                    .httpEndpointAuthScope(
                                            HttpEndpointAuthSource.HttpEndpointAuthScope.Agent)
                                    .httpEndpointAuthScopeConfig(
                                            HttpEndpointOciAuthScopeConfig.builder().build())
                                    .build()))
            .build());
                .subnetId("ocid1.subnet.oc1.us-chicago-1.aaaaaaaal7lmb2rnugbljkchadorxub7463ggill2onyt74v3l5dqhgsojcq")
                .build();
    }
    

    Nel codice, procedere come segue.

    • apiSchema definisce la specifica OpenAPI per l'API HTTP con cui si desidera interagire.
    • httpEndpointAuthConfig specifica la configurazione di autenticazione per l'endpoint HTTP. Nell'esempio, stiamo chiamando un servizio OCI, quindi l'autenticazione è impostata su OCI Resource Principal e <namespace> è lo spazio di nomi dello storage degli oggetti della tenancy.
    • subnetId è l'ID della subnet che si desidera utilizzare per effettuare chiamate all'endpoint API.
  3. Creare una richiesta CreateToolDetails per definire lo strumento.
    // Create a CreateToolDetails request
    CreateToolDetails createToolDetails = CreateToolDetails.builder()
                    .agentId(agentId)
                    .compartmentId(COMPARTMENT_ID)
                    .toolConfig(createHttpEndpointToolConfig())
                    .displayName("tool-sdk")
                    .description("tool description")
                    .build();
    
    // Build the CreateToolRequest
    CreateToolRequest toolRequest = CreateToolRequest.builder()
                     .createToolDetails(createToolDetails)
                     .build();
    
    // Create the tool
    client.createTool(toolRequest);

    Nel codice, procedere come segue.

    • Sostituire agentId e COMPARTMENT_ID con i valori appropriati per l'impostazione.
    • Per toolConfig, passare il valore HttpEndpointToolConfig creato al passo 2.

Chat con un agente

Per avviare una conversazione con l'agente e utilizzare lo strumento endpoint HTTP, effettuare le operazioni riportate di seguito.

  1. Creare una sessione per avviare una conversazione. Ad esempio:
    // 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();

    Nel codice sostituire agentEndpointId con l'OCID dell'endpoint dell'agente che si desidera utilizzare.

  2. Richiama lo strumento endpoint HTTP inviando una richiesta di chat.
    // Create a chat request
    String message = "List all the objects under mydepartment bucket";
    final ChatDetails chatDetails = ChatDetails.builder()
            .shouldStream(shouldStream)
            .userMessage(message)
            .sessionId(sessionId)
            .build();
    final ChatRequest chatRequest = ChatRequest.builder()
            .chatDetails(chatDetails)
            .agentEndpointId(agentEndpointId)
            .build();
    
    // Send the chat request
    agentClient.chat(chatRequest);

    In questo esempio, il messaggio "List all the objects under mydepartment bucket attiva lo strumento endpoint HTTP per interagire con l'API e recupera la lista di oggetti.