Appel d'adresse d'API avec des kits SDK dans les agents d'IA générative

Utilisez ce guide pour vous familiariser avec l'utilisation du kit SDK Java OCI afin d'intégrer les appels d'adresse d'API dans une application. Les étapes suivantes présentent un exemple de kit SDK Java OCI permettant de créer un outil d'appel d'adresse d'API, puis d'utiliser la discussion pour appeler l'outil.

Stratégies IAM

Veillez à ajouter des stratégies afin d'accorder les droits d'accès appropriés pour accéder aux opérations d'API du service OCI que l'agent doit appeler.

Dans l'exemple, l'outil d'appel d'adresse d'API interagit avec les buckets Object Storage. Vous pouvez utiliser les stratégies suivantes pour activer l'accès à Object Storage dans tous les compartiments de la location ou pour restreindre l'accès à un compartiment spécifique.

// 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'} 

Remplacez <compartment-name> par le compartiment à utiliser.

Création d'un outil d'appel d'adresse d'API

Les étapes suivantes indiquent comment utiliser le kit SDK Java OCI pour créer un outil d'appel d'adresse d'API pour un agent.

  1. Configurer un client pour interagir avec les agents d'IA générative. Par exemple :
    // Configure your client
    GenerativeAiAgentRuntimeClient agentClient = GenerativeAiAgentRuntimeClient.builder()
           .endpoint(endpoint)
           .configuration(clientConfiguration)
           .build(provider);

    Dans le code, remplacez endpoint et clientConfiguration par les valeurs appropriées pour votre configuration.

  2. Créez le fichier HttpEndpointToolConfig pour votre outil. Par exemple :
    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();
    }
    

    Dans le code :

    • apiSchema définit la spécification OpenAPI pour l'API HTTP avec laquelle vous souhaitez interagir.
    • httpEndpointAuthConfig indique la configuration d'authentification pour l'adresse HTTP. Dans l'exemple, nous appelons un service OCI. L'authentification est donc définie sur le principal de ressource OCI et <namespace> est l'espace de noms Object Storage de la location.
    • subnetId est l'ID du sous-réseau à utiliser pour effectuer des appels d'adresse d'API.
  3. Créez une demande CreateToolDetails pour définir votre outil.
    // 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);

    Dans le code :

    • Remplacez agentId et COMPARTMENT_ID par les valeurs appropriées pour votre configuration.
    • Pour toolConfig, transmettez le fichier HttpEndpointToolConfig que vous avez créé à l'étape 2.

Discuter avec un agent

Pour lancer une conversation avec l'agent et utiliser l'outil d'adresse HTTP, procédez comme suit :

  1. Créez une session pour démarrer une conversation. Par exemple :
    // 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();

    Dans le code, remplacez agentEndpointId par l'OCID de l'adresse d'agent à utiliser.

  2. Appelez l'outil d'adresse HTTP en envoyant une demande de discussion.
    // 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);

    Dans cet exemple, le message "List all the objects under mydepartment bucket déclenche l'outil d'adresse HTTP pour interagir avec l'API et extrait la liste des objets.