生成AIエージェントでのSDKを使用したAPIエンドポイント・コール

このガイドでは、OCI Java SDKを使用してAPIエンドポイント・コールをアプリケーションに統合することについて理解します。次のステップでは、APIエンドポイント・コール・ツールを作成してから、チャットを使用してツールを起動するためのOCI Java SDKの例を示します。

前提条件

始める前に、次のリソースが設定されていることを確認してください。

IAMポリシー

ポリシーを追加して、エージェントがコールするOCIサービスのAPI操作にアクセスするための適切な権限を付与します。

この例では、APIエンドポイント・コール・ツールがオブジェクト・ストレージ・バケットと相互作用します。次のポリシーを使用して、テナンシ内のすべてのコンパートメントのオブジェクト・ストレージへのアクセスを有効にするか、特定のコンパートメントへのアクセスを制限できます。

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

<compartment-name>を、使用するコンパートメントに置き換えます。

APIエンドポイント・コール・ツールの作成

次のステップでは、OCI Java SDKを使用して、エージェントのAPIエンドポイント・コール・ツールを作成する方法を示します。

  1. 生成AIエージェントと対話するようにクライアントを構成します。例:
    // Configure your client
    GenerativeAiAgentRuntimeClient agentClient = GenerativeAiAgentRuntimeClient.builder()
           .endpoint(endpoint)
           .configuration(clientConfiguration)
           .build(provider);

    コードで、endpointおよびclientConfigurationを、設定に適した値に置き換えます。

  2. ツールのHttpEndpointToolConfigを作成します。例:
    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();
    }
    

    コードの内容は次のとおりです。

    • apiSchemaは、対話するHTTP APIのOpenAPI指定を定義します。
    • httpEndpointAuthConfigは、HTTPエンドポイントの認証構成を指定します。この例では、OCIサービスをコールしているため、認証はOCIリソース・プリンシパルに設定され、<namespace>はテナンシのオブジェクト・ストレージ・ネームスペースです。
    • subnetIdは、APIエンドポイント・コールの実行に使用するサブネットのIDです。
  3. CreateToolDetailsリクエストを作成して、ツールを定義します。
    // 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);

    コードの内容は次のとおりです。

    • agentIdおよびCOMPARTMENT_IDを、設定に適した値に置き換えます。
    • toolConfigの場合は、ステップ2で作成したHttpEndpointToolConfigを渡します。

エージェントとのチャット

エージェントとの会話を開始し、HTTPエンドポイント・ツールを使用するには、次のステップに従います。

  1. セッションを作成して会話を開始します。例:
    // 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();

    コードで、agentEndpointIdを、使用するエージェント・エンドポイントのOCIDに置き換えます。

  2. チャット・リクエストを送信して、HTTPエンドポイント・ツールを起動します。
    // 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);

    この例では、メッセージ"List all the objects under mydepartment bucketによってHTTPエンドポイント・ツールがトリガーされ、APIと対話してオブジェクトのリストが取得されます。