From a2e1155eead55c703df033428ba61faad8c18086 Mon Sep 17 00:00:00 2001 From: Theo Windebank Date: Wed, 25 Nov 2026 14:40:45 +0000 Subject: [PATCH 1/2] [api-sync] sync the client to the public API contract Brings the client in line with public API contract 3e9c6fa0a27454d8d5300c42e4215c475c3954b085dae9901f429d0c531e50f3 and records it in PUBLIC_API_VERSION. New operations: customer memories (list, batch create v2, deprecated v1 batch create), files (begin upload, create, list), knowledge bases (list, create, read, update), notes (list, read), the conversation read endpoint, and reading a given tool version. New webhook events: conversation.start and the three back-office task events; unknown event types now come back as UNKNOWN instead of throwing. Fixes on main: requests now go to the configured base URL, query parameters are sent and encoded, readConversation uses the /read endpoint, the tool and terminology substitution lists read their wrapped responses, deleting a hand-off target sends its ID as a query parameter, timestamps are sent as RFC 3339 strings, participant types use the API's values, unknown response fields no longer fail parsing, and conversation.hand_off webhooks parse again. Carries over the customer memories batch-create work from #34. --- DESIGN.md | 1 - PUBLIC_API_VERSION | 1 + .../examples/BasicConversationExample.java | 13 +- .../examples/ProceduresExample.java | 1 - .../examples/WebhookHandlerExample.java | 20 +- .../springboot/ConversationController.java | 5 - .../springboot/ConversationService.java | 1 - .../client/GradientLabsClient.java | 446 ++++++++++++++---- .../client/ListProcedureVersionsResponse.java | 2 +- .../client/internal/HttpClientWrapper.java | 143 +++--- .../ai/gradientlabs/client/internal/Json.java | 32 ++ .../internal/NanosDurationDeserializer.java | 25 + .../internal/NanosDurationSerializer.java | 25 + .../gradientlabs/client/model/Attachment.java | 32 ++ .../client/model/AttachmentTransferMode.java | 34 ++ .../client/model/AttachmentType.java | 18 +- .../ai/gradientlabs/client/model/Channel.java | 7 +- .../client/model/Conversation.java | 38 +- .../model/CustomerMemoriesListResponse.java | 29 ++ .../client/model/CustomerMemory.java | 119 +++++ ...CustomerSupportPlatformIdentifierType.java | 27 +- .../client/model/FileListResponse.java | 41 ++ .../gradientlabs/client/model/FileUpload.java | 90 ++++ .../client/model/ForwardPagination.java | 14 + .../client/model/GatedConfig.java | 2 +- .../client/model/HTTPBodyDefinition.java | 59 ++- .../client/model/HTTPDefinition.java | 98 +++- .../client/model/HandOffTarget.java | 12 + .../client/model/KnowledgeBase.java | 77 +++ .../model/KnowledgeBasesListResponse.java | 29 ++ .../client/model/ListTopicsResponse.java | 2 +- .../client/model/ManagedResourceSource.java | 39 ++ .../ai/gradientlabs/client/model/Memory.java | 135 ++++++ .../client/model/MemoryCustomType.java | 70 +++ .../ai/gradientlabs/client/model/Message.java | 15 - .../ai/gradientlabs/client/model/Note.java | 14 + .../client/model/NoteListResponse.java | 41 ++ .../client/model/ParticipantType.java | 13 +- .../gradientlabs/client/model/Procedure.java | 22 - .../client/model/ProcedureStatus.java | 22 +- .../client/model/ProcedureVersion.java | 16 +- .../client/model/PublicationStatus.java | 18 +- .../client/model/RefreshMechanismHTTP.java | 44 +- .../client/model/ResourceSource.java | 37 ++ .../model/ResourceSourceSchemaUpdate.java | 12 + .../client/model/RetryPolicy.java | 70 +++ .../client/model/SecretRefreshRequest.java | 16 + .../client/model/SecretRefreshRetry.java | 10 + .../client/model/SupportPlatform.java | 64 ++- .../TerminologySubstitutionsListResponse.java | 29 ++ .../ai/gradientlabs/client/model/Tool.java | 138 +++++- .../client/model/ToolAsyncDefinition.java | 101 ++++ .../client/model/ToolExecutionDefinition.java | 70 +++ .../client/model/ToolMcpDefinition.java | 39 ++ .../client/model/ToolParameter.java | 166 +++++++ .../client/model/ToolParameterOption.java | 70 +++ .../client/model/ToolParameterSet.java | 95 ++++ .../client/model/ToolParameterSource.java | 39 ++ .../client/model/ToolParameterType.java | 74 +++ .../client/model/ToolWebhookDefinition.java | 47 ++ .../client/model/ToolsListResponse.java | 29 ++ .../ai/gradientlabs/client/model/Topic.java | 30 +- .../client/model/TrafficGroup.java | 12 + .../gradientlabs/client/model/Visibility.java | 18 +- .../client/model/VoiceCallContext.java | 12 + .../client/model/WorkspaceFile.java | 89 ++++ .../client/request/AddMessageRequest.java | 76 ++- .../client/request/AssignmentRequest.java | 52 ++ .../BatchCreateCustomerMemoriesRequest.java | 65 +++ .../BatchCreateCustomerMemoriesV2Request.java | 73 +++ .../request/BeginFileUploadRequest.java | 67 +++ .../request/CreateBackOfficeTaskRequest.java | 13 +- .../client/request/CreateFileRequest.java | 123 +++++ .../request/CreateKnowledgeBaseRequest.java | 98 ++++ .../client/request/CreateNoteRequest.java | 52 ++ .../request/CreateResourceSourceRequest.java | 50 ++ .../request/CreateResourceTypeRequest.java | 50 ++ .../client/request/CreateToolRequest.java | 259 +++++++++- .../CreateTrafficGroupTargetRequest.java | 3 - .../client/request/EventRequest.java | 3 + .../request/FinishConversationRequest.java | 27 ++ .../request/ReadConversationRequest.java | 33 +- .../request/ReturnAsyncToolResultRequest.java | 12 +- .../request/StartConversationRequest.java | 37 -- .../client/request/ToolExecuteRequest.java | 18 + .../request/UpdateKnowledgeBaseRequest.java | 70 +++ .../client/request/UpdateNoteRequest.java | 52 ++ .../request/UpdateResourceSourceRequest.java | 11 +- ...ResourceSourceSchemaByExamplesRequest.java | 7 +- .../request/UpdateResourceTypeRequest.java | 2 + .../client/request/UpdateToolRequest.java | 170 ++++++- .../client/request/UpsertArticleRequest.java | 70 ++- .../request/UpsertArticleTopicRequest.java | 49 +- .../request/UpsertHandOffTargetRequest.java | 25 + .../client/request/WriteSecretRequest.java | 2 + .../gradientlabs/client/webhook/Webhook.java | 40 +- .../client/webhook/WebhookType.java | 45 +- .../client/webhook/WebhookVerifier.java | 21 +- .../webhook/event/ActionExecuteEvent.java | 14 +- .../webhook/event/AgentMessageEvent.java | 24 + .../event/BackOfficeTaskCompleteEvent.java | 15 + .../webhook/event/BackOfficeTaskEvent.java | 27 ++ .../event/BackOfficeTaskFailEvent.java | 15 + .../event/BackOfficeTaskHandOffEvent.java | 15 + .../webhook/event/ConversationStartEvent.java | 87 ++++ .../webhook/event/ResourcePullEvent.java | 15 +- .../webhook/event/WebhookBackOfficeTask.java | 27 ++ .../webhook/event/WebhookConversation.java | 12 + .../client/ClientRequestsTest.java | 301 ++++++++++++ .../client/OperationListTest.java | 125 +++++ .../gradientlabs/client/StubHttpClient.java | 202 ++++++++ ...atchCreateCustomerMemoriesRequestTest.java | 95 ++++ .../client/webhook/WebhookVerifierTest.java | 140 ++++++ 113 files changed, 5429 insertions(+), 519 deletions(-) create mode 100644 PUBLIC_API_VERSION create mode 100644 gradient-labs-client/src/main/java/ai/gradientlabs/client/internal/Json.java create mode 100644 gradient-labs-client/src/main/java/ai/gradientlabs/client/internal/NanosDurationDeserializer.java create mode 100644 gradient-labs-client/src/main/java/ai/gradientlabs/client/internal/NanosDurationSerializer.java create mode 100644 gradient-labs-client/src/main/java/ai/gradientlabs/client/model/AttachmentTransferMode.java create mode 100644 gradient-labs-client/src/main/java/ai/gradientlabs/client/model/CustomerMemoriesListResponse.java create mode 100644 gradient-labs-client/src/main/java/ai/gradientlabs/client/model/CustomerMemory.java create mode 100644 gradient-labs-client/src/main/java/ai/gradientlabs/client/model/FileListResponse.java create mode 100644 gradient-labs-client/src/main/java/ai/gradientlabs/client/model/FileUpload.java create mode 100644 gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ForwardPagination.java create mode 100644 gradient-labs-client/src/main/java/ai/gradientlabs/client/model/KnowledgeBase.java create mode 100644 gradient-labs-client/src/main/java/ai/gradientlabs/client/model/KnowledgeBasesListResponse.java create mode 100644 gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ManagedResourceSource.java create mode 100644 gradient-labs-client/src/main/java/ai/gradientlabs/client/model/Memory.java create mode 100644 gradient-labs-client/src/main/java/ai/gradientlabs/client/model/MemoryCustomType.java create mode 100644 gradient-labs-client/src/main/java/ai/gradientlabs/client/model/NoteListResponse.java create mode 100644 gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ResourceSourceSchemaUpdate.java create mode 100644 gradient-labs-client/src/main/java/ai/gradientlabs/client/model/RetryPolicy.java create mode 100644 gradient-labs-client/src/main/java/ai/gradientlabs/client/model/SecretRefreshRequest.java create mode 100644 gradient-labs-client/src/main/java/ai/gradientlabs/client/model/SecretRefreshRetry.java create mode 100644 gradient-labs-client/src/main/java/ai/gradientlabs/client/model/TerminologySubstitutionsListResponse.java create mode 100644 gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ToolAsyncDefinition.java create mode 100644 gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ToolExecutionDefinition.java create mode 100644 gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ToolMcpDefinition.java create mode 100644 gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ToolParameter.java create mode 100644 gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ToolParameterOption.java create mode 100644 gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ToolParameterSet.java create mode 100644 gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ToolParameterSource.java create mode 100644 gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ToolParameterType.java create mode 100644 gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ToolWebhookDefinition.java create mode 100644 gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ToolsListResponse.java create mode 100644 gradient-labs-client/src/main/java/ai/gradientlabs/client/model/WorkspaceFile.java create mode 100644 gradient-labs-client/src/main/java/ai/gradientlabs/client/request/BatchCreateCustomerMemoriesRequest.java create mode 100644 gradient-labs-client/src/main/java/ai/gradientlabs/client/request/BatchCreateCustomerMemoriesV2Request.java create mode 100644 gradient-labs-client/src/main/java/ai/gradientlabs/client/request/BeginFileUploadRequest.java create mode 100644 gradient-labs-client/src/main/java/ai/gradientlabs/client/request/CreateFileRequest.java create mode 100644 gradient-labs-client/src/main/java/ai/gradientlabs/client/request/CreateKnowledgeBaseRequest.java create mode 100644 gradient-labs-client/src/main/java/ai/gradientlabs/client/request/UpdateKnowledgeBaseRequest.java create mode 100644 gradient-labs-client/src/main/java/ai/gradientlabs/client/webhook/event/BackOfficeTaskCompleteEvent.java create mode 100644 gradient-labs-client/src/main/java/ai/gradientlabs/client/webhook/event/BackOfficeTaskEvent.java create mode 100644 gradient-labs-client/src/main/java/ai/gradientlabs/client/webhook/event/BackOfficeTaskFailEvent.java create mode 100644 gradient-labs-client/src/main/java/ai/gradientlabs/client/webhook/event/BackOfficeTaskHandOffEvent.java create mode 100644 gradient-labs-client/src/main/java/ai/gradientlabs/client/webhook/event/ConversationStartEvent.java create mode 100644 gradient-labs-client/src/main/java/ai/gradientlabs/client/webhook/event/WebhookBackOfficeTask.java create mode 100644 gradient-labs-client/src/test/java/ai/gradientlabs/client/ClientRequestsTest.java create mode 100644 gradient-labs-client/src/test/java/ai/gradientlabs/client/OperationListTest.java create mode 100644 gradient-labs-client/src/test/java/ai/gradientlabs/client/StubHttpClient.java create mode 100644 gradient-labs-client/src/test/java/ai/gradientlabs/client/request/BatchCreateCustomerMemoriesRequestTest.java create mode 100644 gradient-labs-client/src/test/java/ai/gradientlabs/client/webhook/WebhookVerifierTest.java diff --git a/DESIGN.md b/DESIGN.md index 8446e69..6ceaa50 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -100,7 +100,6 @@ StartConversationRequest request = StartConversationRequest.builder() .id("conversation-1234") .customerId("user-1234") .channel(Channel.CHAT) - .metadata(Map.of("source", "web")) .build(); Conversation conv = client.startConversation(request); diff --git a/PUBLIC_API_VERSION b/PUBLIC_API_VERSION new file mode 100644 index 0000000..c5a26d7 --- /dev/null +++ b/PUBLIC_API_VERSION @@ -0,0 +1 @@ +3e9c6fa0a27454d8d5300c42e4215c475c3954b085dae9901f429d0c531e50f3 diff --git a/gradient-labs-client/examples/BasicConversationExample.java b/gradient-labs-client/examples/BasicConversationExample.java index b48ffa9..7e07eee 100644 --- a/gradient-labs-client/examples/BasicConversationExample.java +++ b/gradient-labs-client/examples/BasicConversationExample.java @@ -24,8 +24,6 @@ public static void main(String[] args) { .id("conversation-" + System.currentTimeMillis()) .customerId("user-1234") .channel(Channel.CHAT) - .addMetadata("source", "web") - .addMetadata("entrypoint", "home-page") .addResource("user_profile", Map.of( "name", "Jane Doe", "email", "jane@example.com", @@ -51,8 +49,6 @@ public static void main(String[] args) { .participantId("user-1234") .participantType(ParticipantType.CUSTOMER) .created(Instant.now()) - .addMetadata("device_os", "iOS 17") - .addMetadata("app_version", "2.1.0") .addAttachment(new Attachment( AttachmentType.IMAGE, "order-receipt.jpg", @@ -78,7 +74,7 @@ public static void main(String[] args) { EventRequest eventRequest = EventRequest.builder() .type("internal_note") .participantId("system") - .participantType(ParticipantType.HUMAN) + .participantType(ParticipantType.AGENT) .body("Customer has premium subscription - prioritize response") .build(); @@ -91,12 +87,7 @@ public static void main(String[] args) { // Read the conversation System.out.println("\nReading conversation..."); - Conversation updatedConv = client.readConversation( - conversation.getId(), - ReadConversationRequest.builder() - .includeMessages(true) - .build() - ); + Conversation updatedConv = client.readConversation(conversation.getId()); System.out.println("✓ Conversation read"); System.out.println(" Status: " + updatedConv.getStatus()); System.out.println(" Agent active: " + updatedConv.isAgentActive()); diff --git a/gradient-labs-client/examples/ProceduresExample.java b/gradient-labs-client/examples/ProceduresExample.java index 1762590..749d602 100644 --- a/gradient-labs-client/examples/ProceduresExample.java +++ b/gradient-labs-client/examples/ProceduresExample.java @@ -82,7 +82,6 @@ public static void main(String[] args) { System.out.println("Name: " + proc.getName()); System.out.println("Description: " + proc.getDescription()); System.out.println("Status: " + proc.getStatus()); - System.out.println("Author: " + (proc.getAuthor() != null ? proc.getAuthor().getEmail() : "N/A")); System.out.println("Created: " + proc.getCreated()); System.out.println("Updated: " + proc.getUpdated()); System.out.println("Has Daily Limit: " + proc.isDailyLimited()); diff --git a/gradient-labs-client/examples/WebhookHandlerExample.java b/gradient-labs-client/examples/WebhookHandlerExample.java index 34c5195..2faf777 100644 --- a/gradient-labs-client/examples/WebhookHandlerExample.java +++ b/gradient-labs-client/examples/WebhookHandlerExample.java @@ -55,10 +55,6 @@ protected void doPost(HttpServletRequest request, HttpServletResponse response) handleActionExecute(webhook.asActionExecute()); break; - case RESOURCE_PULL: - handleResourcePull(webhook.asResourcePull()); - break; - default: System.out.println("Unknown webhook type: " + webhook.getType()); } @@ -146,23 +142,9 @@ private void handleActionExecute(ActionExecuteEvent event) { // AddMessageRequest.builder() // .id("action-result-" + System.currentTimeMillis()) // .body("Action result: " + result) - // .participantType(ParticipantType.HUMAN) + // .participantType(ParticipantType.AGENT) // .build() // ); } - private void handleResourcePull(ResourcePullEvent event) { - System.out.println("\n=== Resource Pull ==="); - System.out.println("Conversation: " + event.getConversation().getId()); - System.out.println("Resource Type: " + event.getResourceType()); - - // TODO: Fetch the requested resource and add it to the conversation - // Object resource = fetchResource(event.getResourceType()); - // - // client.addConversationResource( - // event.getConversation().getId(), - // event.getResourceType(), - // resource - // ); - } } diff --git a/gradient-labs-client/examples/spring-boot-example/src/main/java/ai/gradientlabs/example/springboot/ConversationController.java b/gradient-labs-client/examples/spring-boot-example/src/main/java/ai/gradientlabs/example/springboot/ConversationController.java index 247ba2a..544e6fa 100644 --- a/gradient-labs-client/examples/spring-boot-example/src/main/java/ai/gradientlabs/example/springboot/ConversationController.java +++ b/gradient-labs-client/examples/spring-boot-example/src/main/java/ai/gradientlabs/example/springboot/ConversationController.java @@ -110,11 +110,6 @@ public ResponseEntity handleWebhook(HttpServletRequest request) { // Execute the requested action break; - case RESOURCE_PULL: - System.out.println("Resource pull event received"); - // Fetch and return requested resource - break; - default: System.out.println("Unknown webhook type: " + webhook.getType()); } diff --git a/gradient-labs-client/examples/spring-boot-example/src/main/java/ai/gradientlabs/example/springboot/ConversationService.java b/gradient-labs-client/examples/spring-boot-example/src/main/java/ai/gradientlabs/example/springboot/ConversationService.java index 99e9936..5bcb707 100644 --- a/gradient-labs-client/examples/spring-boot-example/src/main/java/ai/gradientlabs/example/springboot/ConversationService.java +++ b/gradient-labs-client/examples/spring-boot-example/src/main/java/ai/gradientlabs/example/springboot/ConversationService.java @@ -43,7 +43,6 @@ public Conversation startConversation(String customerId) { .id("conv-" + UUID.randomUUID()) .customerId(customerId) .channel(Channel.CHAT) - .addMetadata("source", "spring-boot-example") .build(); return client.startConversation(request); diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/GradientLabsClient.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/GradientLabsClient.java index ecd4134..11e53e9 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/GradientLabsClient.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/GradientLabsClient.java @@ -11,7 +11,9 @@ import jakarta.servlet.http.HttpServletRequest; import java.net.http.HttpClient; import java.time.Duration; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; /** * Main client for interacting with the Gradient Labs API. @@ -44,7 +46,7 @@ private GradientLabsClient(String baseUrl, String apiKey, HttpClient httpClient, WebhookVerifier webhookVerifier) { this.baseUrl = baseUrl; this.apiKey = apiKey; - this.httpClient = new HttpClientWrapper(httpClient, apiKey, getUserAgent()); + this.httpClient = new HttpClientWrapper(httpClient, baseUrl, apiKey, getUserAgent()); this.webhookVerifier = webhookVerifier; this.userAgent = getUserAgent(); } @@ -149,13 +151,42 @@ public StartOutboundConversationResponse startOutboundPhoneConversation(StartOut * Retrieves a conversation by ID. * * @param conversationId the conversation ID - * @param request optional read parameters + * @param request optional read parameters, or null * @return the conversation * @throws GradientLabsException if the request fails */ public Conversation readConversation(String conversationId, ReadConversationRequest request) { - String path = String.format("/conversations/%s", conversationId); - return httpClient.get(path, request, Conversation.class); + String path = String.format("/conversations/%s/read", seg(conversationId)); + Map query = new LinkedHashMap<>(); + if (request != null) { + query.put("support_platform", request.getSupportPlatform()); + } + return httpClient.get(path, query, Conversation.class); + } + + /** + * Retrieves a conversation by ID. + * + * @param conversationId the conversation ID + * @return the conversation + * @throws GradientLabsException if the request fails + */ + public Conversation readConversation(String conversationId) { + return readConversation(conversationId, null); + } + + /** + * Retrieves a conversation by ID using the older {@code GET /conversations/{id}} endpoint. + * + * @param conversationId the conversation ID + * @return the conversation + * @throws GradientLabsException if the request fails + * @deprecated use {@link #readConversation(String)} + */ + @Deprecated + public Conversation readConversationDeprecated(String conversationId) { + String path = String.format("/conversations/%s", seg(conversationId)); + return httpClient.get(path, null, Conversation.class); } /** @@ -167,7 +198,7 @@ public Conversation readConversation(String conversationId, ReadConversationRequ * @throws GradientLabsException if the request fails */ public Message addMessage(String conversationId, AddMessageRequest request) { - String path = String.format("/conversations/%s/messages", conversationId); + String path = String.format("/conversations/%s/messages", seg(conversationId)); return httpClient.post(path, request, Message.class); } @@ -179,7 +210,7 @@ public Message addMessage(String conversationId, AddMessageRequest request) { * @throws GradientLabsException if the request fails */ public void assignConversation(String conversationId, AssignmentRequest request) { - String path = String.format("/conversations/%s/assignee", conversationId); + String path = String.format("/conversations/%s/assignee", seg(conversationId)); httpClient.put(path, request, Void.class); } @@ -191,7 +222,7 @@ public void assignConversation(String conversationId, AssignmentRequest request) * @throws GradientLabsException if the request fails */ public void addConversationEvent(String conversationId, EventRequest request) { - String path = String.format("/conversations/%s/events", conversationId); + String path = String.format("/conversations/%s/events", seg(conversationId)); httpClient.post(path, request, Void.class); } @@ -203,7 +234,7 @@ public void addConversationEvent(String conversationId, EventRequest request) { * @throws GradientLabsException if the request fails */ public void finishConversation(String conversationId, FinishConversationRequest request) { - String path = String.format("/conversations/%s/finish", conversationId); + String path = String.format("/conversations/%s/finish", seg(conversationId)); httpClient.put(path, request, Void.class); } @@ -215,7 +246,7 @@ public void finishConversation(String conversationId, FinishConversationRequest * @throws GradientLabsException if the request fails */ public void cancelConversation(String conversationId, CancelConversationRequest request) { - String path = String.format("/conversations/%s/cancel", conversationId); + String path = String.format("/conversations/%s/cancel", seg(conversationId)); httpClient.put(path, request, Void.class); } @@ -227,7 +258,7 @@ public void cancelConversation(String conversationId, CancelConversationRequest * @throws GradientLabsException if the request fails */ public void resumeConversation(String conversationId, ResumeConversationRequest request) { - String path = String.format("/conversations/%s/resume", conversationId); + String path = String.format("/conversations/%s/resume", seg(conversationId)); httpClient.put(path, request, Void.class); } @@ -239,7 +270,7 @@ public void resumeConversation(String conversationId, ResumeConversationRequest * @throws GradientLabsException if the request fails */ public void rateConversation(String conversationId, RateConversationRequest request) { - String path = String.format("/conversations/%s/rate", conversationId); + String path = String.format("/conversations/%s/rate", seg(conversationId)); httpClient.put(path, request, Void.class); } @@ -268,7 +299,7 @@ public void rateConversation(String conversationId, RateConversationRequest requ * @throws GradientLabsException if the request fails */ public void returnAsyncToolResult(String conversationId, ReturnAsyncToolResultRequest request) { - String path = String.format("/conversations/%s/return-async-tool-result", conversationId); + String path = String.format("/conversations/%s/return-async-tool-result", seg(conversationId)); httpClient.put(path, request, Void.class); } @@ -284,10 +315,68 @@ public void returnAsyncToolResult(String conversationId, ReturnAsyncToolResultRe * @throws GradientLabsException if the request fails */ public void deleteConversation(String conversationId) { - String path = String.format("/conversations/%s", conversationId); + String path = String.format("/conversations/%s", seg(conversationId)); httpClient.delete(path, Void.class); } + // ==================== Customer Memory Operations ==================== + + /** + * Experimental. Available to selected workspaces. + *

+ * Lists the memories stored for a customer. + * + * @param customerId your identifier for the customer + * @return the customer's memories + * @throws GradientLabsException if the request fails + */ + public List listCustomerMemories(String customerId) { + String path = String.format("/customers/%s/memories", seg(customerId)); + CustomerMemoriesListResponse response = httpClient.get(path, null, CustomerMemoriesListResponse.class); + return response.getMemories(); + } + + /** + * Experimental. Available to selected workspaces. + *

+ * Batch-creates a set of memories scoped to a customer. + *

+ * Each memory's {@code data} payload is stored verbatim as arbitrary JSON for + * the AI agent to search over on demand. The batch is created asynchronously: + * the call returns as soon as the job is accepted and yields no result. A + * {@link GradientLabsException} carrying HTTP 409 is thrown when a batch is + * already being created for the same customer. + * + * @param customerId the customer ID + * @param request the memories to create + * @throws GradientLabsException if the request fails + * @deprecated use {@link #batchCreateCustomerMemoriesV2(String, BatchCreateCustomerMemoriesV2Request)}, + * which also takes a category description + */ + @Deprecated + public void batchCreateCustomerMemories(String customerId, BatchCreateCustomerMemoriesRequest request) { + String path = String.format("/customers/%s/memories", seg(customerId)); + httpClient.post(path, request, Void.class); + } + + /** + * Experimental. Available to selected workspaces. + *

+ * Batch-creates a set of memories scoped to a customer, each with a category name and description. + *

+ * The batch is created asynchronously: the call returns as soon as the job is accepted. A + * {@link GradientLabsException} carrying HTTP 409 is thrown when a batch is already being + * created for the same customer. + * + * @param customerId your identifier for the customer + * @param request the memories to create + * @throws GradientLabsException if the request fails + */ + public void batchCreateCustomerMemoriesV2(String customerId, BatchCreateCustomerMemoriesV2Request request) { + String path = String.format("/customers/%s/memories/v2", seg(customerId)); + httpClient.post(path, request, Void.class); + } + // ==================== Tool Operations ==================== /** @@ -297,7 +386,8 @@ public void deleteConversation(String conversationId) { * @throws GradientLabsException if the request fails */ public List listTools() { - return httpClient.getList("/tools", null, Tool.class); + ToolsListResponse response = httpClient.get("/tools", null, ToolsListResponse.class); + return response.getTools(); } /** @@ -319,8 +409,22 @@ public Tool createTool(CreateToolRequest request) { * @throws GradientLabsException if the request fails */ public Tool readTool(String toolId) { - String path = String.format("/tools/%s", toolId); - return httpClient.get(path, null, Tool.class); + return readTool(toolId, null); + } + + /** + * Retrieves a given version of a tool. + * + * @param toolId the tool ID + * @param version the version to read, or null for the latest + * @return the tool + * @throws GradientLabsException if the request fails + */ + public Tool readTool(String toolId, Long version) { + String path = String.format("/tools/%s", seg(toolId)); + Map query = new LinkedHashMap<>(); + query.put("version", version); + return httpClient.get(path, query, Tool.class); } /** @@ -332,7 +436,7 @@ public Tool readTool(String toolId) { * @throws GradientLabsException if the request fails */ public Tool updateTool(String toolId, UpdateToolRequest request) { - String path = String.format("/tools/%s", toolId); + String path = String.format("/tools/%s", seg(toolId)); return httpClient.put(path, request, Tool.class); } @@ -343,7 +447,7 @@ public Tool updateTool(String toolId, UpdateToolRequest request) { * @throws GradientLabsException if the request fails */ public void deleteTool(String toolId) { - String path = String.format("/tools/%s", toolId); + String path = String.format("/tools/%s", seg(toolId)); httpClient.delete(path, Void.class); } @@ -358,12 +462,53 @@ public void deleteTool(String toolId) { * @throws GradientLabsException if the request fails */ public ToolExecuteResult executeTool(String toolId, ToolExecuteRequest request) { - String path = String.format("/tools/%s/execute", toolId); + String path = String.format("/tools/%s/execute", seg(toolId)); return httpClient.post(path, request, ToolExecuteResult.class); } // ==================== Note Operations ==================== + /** + * Lists the first page of notes. + *

+ * Note: Requires a Management API key. + * + * @return the first page of notes + * @throws GradientLabsException if the request fails + */ + public NoteListResponse listNotes() { + return listNotes(null); + } + + /** + * Lists a page of notes. + *

+ * Note: Requires a Management API key. + * + * @param cursor the cursor from a previous page's pagination, or null for the first page + * @return the page of notes + * @throws GradientLabsException if the request fails + */ + public NoteListResponse listNotes(String cursor) { + Map query = new LinkedHashMap<>(); + query.put("cursor", cursor); + return httpClient.get("/notes", query, NoteListResponse.class); + } + + /** + * Reads a note. + *

+ * Note: Requires a Management API key. + * + * @param noteId your identifier for the note + * @return the note + * @throws GradientLabsException if the request fails + */ + public Note readNote(String noteId) { + String path = String.format("/notes/%s", seg(noteId)); + return httpClient.get(path, null, Note.class); + } + /** * Creates a new note. * @@ -384,7 +529,7 @@ public Note createNote(CreateNoteRequest request) { * @throws GradientLabsException if the request fails */ public Note updateNote(String noteId, UpdateNoteRequest request) { - String path = String.format("/notes/%s", noteId); + String path = String.format("/notes/%s", seg(noteId)); return httpClient.post(path, request, Note.class); } @@ -395,7 +540,7 @@ public Note updateNote(String noteId, UpdateNoteRequest request) { * @throws GradientLabsException if the request fails */ public void deleteNote(String noteId) { - String path = String.format("/notes/%s", noteId); + String path = String.format("/notes/%s", seg(noteId)); httpClient.delete(path, Void.class); } @@ -407,7 +552,7 @@ public void deleteNote(String noteId) { * @throws GradientLabsException if the request fails */ public void setNoteStatus(String noteId, SetNoteStatusRequest request) { - String path = String.format("/notes/%s/status", noteId); + String path = String.format("/notes/%s/status", seg(noteId)); httpClient.post(path, request, Void.class); } @@ -427,7 +572,7 @@ public void setNoteStatus(String noteId, SetNoteStatusRequest request) { * @throws GradientLabsException if the request fails */ public Secret writeSecret(WriteSecretRequest request) { - String path = String.format("/secrets/%s", request.getName()); + String path = String.format("/secrets/%s", seg(request.getName())); return httpClient.put(path, request, Secret.class); } @@ -458,7 +603,7 @@ public List listSecrets() { * @throws GradientLabsException if the request fails */ public void revokeSecret(RevokeSecretRequest request) { - String path = String.format("/secrets/%s", request.getName()); + String path = String.format("/secrets/%s", seg(request.getName())); httpClient.delete(path, Void.class); } @@ -505,7 +650,7 @@ public List listResourceSources() { * @throws GradientLabsException if the request fails */ public ResourceSource readResourceSource(ReadResourceSourceRequest request) { - String path = String.format("/resource-sources/%s", request.getId()); + String path = String.format("/resource-sources/%s", seg(request.getId())); return httpClient.get(path, null, ResourceSource.class); } @@ -522,7 +667,7 @@ public ResourceSource readResourceSource(ReadResourceSourceRequest request) { * @throws GradientLabsException if the request fails */ public ResourceSource updateResourceSource(UpdateResourceSourceRequest request) { - String path = String.format("/resource-sources/%s", request.getId()); + String path = String.format("/resource-sources/%s", seg(request.getId())); return httpClient.put(path, request, ResourceSource.class); } @@ -540,7 +685,12 @@ public ResourceSource updateResourceSource(UpdateResourceSourceRequest request) * @throws GradientLabsException if the request fails */ public ResourceSource updateResourceSourceSchemaByExamples(UpdateResourceSourceSchemaByExamplesRequest request) { - String path = String.format("/resource-sources/%s/schema-by-examples", request.getId()); + return updateResourceSourceSchemaByExamples(request.getId(), request); + } + + /** Updates a resource source schema from example payloads. */ + public ResourceSource updateResourceSourceSchemaByExamples(String id, UpdateResourceSourceSchemaByExamplesRequest request) { + String path = String.format("/resource-sources/%s/schema-by-examples", seg(id)); return httpClient.post(path, request, ResourceSource.class); } @@ -555,7 +705,7 @@ public ResourceSource updateResourceSourceSchemaByExamples(UpdateResourceSourceS * @throws GradientLabsException if the request fails */ public void deleteResourceSource(DeleteResourceSourceRequest request) { - String path = String.format("/resource-sources/%s", request.getId()); + String path = String.format("/resource-sources/%s", seg(request.getId())); httpClient.delete(path, Void.class); } @@ -603,7 +753,7 @@ public List listResourceTypes() { * @throws GradientLabsException if the request fails */ public ResourceType readResourceType(ReadResourceTypeRequest request) { - String path = String.format("/resource-types/%s", request.getId()); + String path = String.format("/resource-types/%s", seg(request.getId())); return httpClient.get(path, null, ResourceType.class); } @@ -620,7 +770,7 @@ public ResourceType readResourceType(ReadResourceTypeRequest request) { * @throws GradientLabsException if the request fails */ public ResourceType updateResourceType(UpdateResourceTypeRequest request) { - String path = String.format("/resource-types/%s", request.getId()); + String path = String.format("/resource-types/%s", seg(request.getId())); return httpClient.put(path, request, ResourceType.class); } @@ -635,7 +785,7 @@ public ResourceType updateResourceType(UpdateResourceTypeRequest request) { * @throws GradientLabsException if the request fails */ public void deleteResourceType(DeleteResourceTypeRequest request) { - String path = String.format("/resource-types/%s", request.getId()); + String path = String.format("/resource-types/%s", seg(request.getId())); httpClient.delete(path, Void.class); } @@ -683,7 +833,7 @@ public void upsertHandOffTarget(UpsertHandOffTargetRequest request) { * @throws GradientLabsException if the request fails (including if the target is in use) */ public void deleteHandOffTarget(DeleteHandOffTargetRequest request) { - httpClient.delete("/hand-off-targets", request, Void.class); + httpClient.delete("/hand-off-targets", Map.of("id", request.getId()), Void.class); } /** @@ -715,8 +865,8 @@ public void setDefaultHandOffTarget(SetDefaultHandOffTargetRequest request) { * @throws GradientLabsException if the request fails */ public GetDefaultHandOffTargetResponse getDefaultHandOffTarget(GetDefaultHandOffTargetRequest request) { - String path = "/hand-off-targets/default?channel=" + request.getChannel().getValue(); - return httpClient.get(path, null, GetDefaultHandOffTargetResponse.class); + return httpClient.get("/hand-off-targets/default", Map.of("channel", request.getChannel().getValue()), + GetDefaultHandOffTargetResponse.class); } // ==================== Article Operations ==================== @@ -767,7 +917,7 @@ public void upsertArticleTopic(UpsertArticleTopicRequest request) { * @throws GradientLabsException if the request fails */ public void setArticleUsageStatus(String articleId, SetArticleUsageStatusRequest request) { - String path = String.format("/articles/%s/usage-status", articleId); + String path = String.format("/articles/%s/usage-status", seg(articleId)); httpClient.post(path, request, Void.class); } @@ -783,7 +933,7 @@ public void setArticleUsageStatus(String articleId, SetArticleUsageStatusRequest * @throws GradientLabsException if the request fails */ public void deleteArticle(String articleId) { - String path = String.format("/articles/%s", articleId); + String path = String.format("/articles/%s", seg(articleId)); httpClient.delete(path, Void.class); } @@ -799,13 +949,11 @@ public void deleteArticle(String articleId) { * @throws GradientLabsException if the request fails */ public ListTopicsResponse listTopics(ListTopicsRequest request) { - StringBuilder path = new StringBuilder("/topics"); - - if (request.getSupportPlatform() != null) { - path.append("?support_platform=").append(request.getSupportPlatform()); + Map query = new LinkedHashMap<>(); + if (request != null) { + query.put("support_platform", request.getSupportPlatform()); } - - return httpClient.get(path.toString(), null, ListTopicsResponse.class); + return httpClient.get("/topics", query, ListTopicsResponse.class); } /** @@ -819,13 +967,12 @@ public ListTopicsResponse listTopics(ListTopicsRequest request) { * @throws GradientLabsException if the request fails */ public Topic readTopic(String topicId, ReadTopicRequest request) { - StringBuilder path = new StringBuilder(String.format("/topic/%s", topicId)); - - if (request.getSupportPlatform() != null) { - path.append("?support_platform=").append(request.getSupportPlatform()); + String path = String.format("/topic/%s", seg(topicId)); + Map query = new LinkedHashMap<>(); + if (request != null) { + query.put("support_platform", request.getSupportPlatform()); } - - return httpClient.get(path.toString(), null, Topic.class); + return httpClient.get(path, query, Topic.class); } // ==================== Procedure Operations ==================== @@ -840,20 +987,12 @@ public Topic readTopic(String topicId, ReadTopicRequest request) { * @throws GradientLabsException if the request fails */ public ProcedureListResponse listProcedures(ListProceduresRequest request) { - StringBuilder path = new StringBuilder("/procedures"); - boolean hasQueryParam = false; - - if (request.getCursor() != null) { - path.append("?cursor=").append(request.getCursor()); - hasQueryParam = true; - } - - if (request.getStatus() != null) { - path.append(hasQueryParam ? "&" : "?"); - path.append("status=").append(request.getStatus().getValue()); + Map query = new LinkedHashMap<>(); + if (request != null) { + query.put("cursor", request.getCursor()); + query.put("status", request.getStatus() == null ? null : request.getStatus().getValue()); } - - return httpClient.get(path.toString(), null, ProcedureListResponse.class); + return httpClient.get("/procedures", query, ProcedureListResponse.class); } /** @@ -866,7 +1005,7 @@ public ProcedureListResponse listProcedures(ListProceduresRequest request) { * @throws GradientLabsException if the request fails */ public Procedure readProcedure(String procedureId) { - String path = String.format("/procedure/%s", procedureId); + String path = String.format("/procedure/%s", seg(procedureId)); return httpClient.get(path, null, Procedure.class); } @@ -883,8 +1022,8 @@ public Procedure readProcedure(String procedureId) { * @throws GradientLabsException if the request fails */ public Procedure setProcedureLimit(String procedureId, SetProcedureLimitRequest request) { - String path = String.format("/procedure/%s/limit", procedureId); - return httpClient.post(path, request, Procedure.class); + String path = String.format("/procedure/%s/limit", seg(procedureId)); + return httpClient.post(path, request, ProcedureLimitResponse.class).procedure(); } /** @@ -897,7 +1036,7 @@ public Procedure setProcedureLimit(String procedureId, SetProcedureLimitRequest * @throws GradientLabsException if the request fails */ public ListProcedureVersionsResponse listProcedureVersions(String procedureId) { - String path = String.format("/procedures/%s/versions", procedureId); + String path = String.format("/procedures/%s/versions", seg(procedureId)); return httpClient.get(path, null, ListProcedureVersionsResponse.class); } @@ -915,7 +1054,7 @@ public ListProcedureVersionsResponse listProcedureVersions(String procedureId) { * @throws GradientLabsException if the request fails */ public void setProcedureGatedVersion(String procedureId, int version, SetProcedureGatedVersionRequest request) { - String path = String.format("/procedures/%s/versions/%d/set-gated", procedureId, version); + String path = String.format("/procedures/%s/versions/%d/set-gated", seg(procedureId), version); httpClient.post(path, request, Void.class); } @@ -929,7 +1068,7 @@ public void setProcedureGatedVersion(String procedureId, int version, SetProcedu * @throws GradientLabsException if the request fails */ public void unsetProcedureGatedVersion(String procedureId, int version) { - String path = String.format("/procedures/%s/versions/%d/unset-gated", procedureId, version); + String path = String.format("/procedures/%s/versions/%d/unset-gated", seg(procedureId), version); httpClient.post(path, null, Void.class); } @@ -946,7 +1085,7 @@ public void unsetProcedureGatedVersion(String procedureId, int version) { * @throws GradientLabsException if the request fails */ public void setProcedureLiveVersion(String procedureId, int version) { - String path = String.format("/procedures/%s/versions/%d/set-live", procedureId, version); + String path = String.format("/procedures/%s/versions/%d/set-live", seg(procedureId), version); httpClient.post(path, null, Void.class); } @@ -960,7 +1099,7 @@ public void setProcedureLiveVersion(String procedureId, int version) { * @throws GradientLabsException if the request fails */ public void unsetProcedureLiveVersion(String procedureId, int version) { - String path = String.format("/procedures/%s/versions/%d/unset-live", procedureId, version); + String path = String.format("/procedures/%s/versions/%d/unset-live", seg(procedureId), version); httpClient.post(path, null, Void.class); } @@ -1002,7 +1141,7 @@ public List listTrafficGroups() { * @throws GradientLabsException if the request fails */ public TrafficGroup updateTrafficGroup(UpdateTrafficGroupRequest request) { - String path = String.format("/traffic-groups/%s", request.getId()); + String path = String.format("/traffic-groups/%s", seg(request.getId())); return httpClient.put(path, request, TrafficGroup.class); } @@ -1015,7 +1154,7 @@ public TrafficGroup updateTrafficGroup(UpdateTrafficGroupRequest request) { * @throws GradientLabsException if the request fails */ public void deleteTrafficGroup(String trafficGroupId) { - String path = String.format("/traffic-groups/%s", trafficGroupId); + String path = String.format("/traffic-groups/%s", seg(trafficGroupId)); httpClient.delete(path, Void.class); } @@ -1029,7 +1168,12 @@ public void deleteTrafficGroup(String trafficGroupId) { * @throws GradientLabsException if the request fails */ public TrafficGroupTarget createTrafficGroupTarget(CreateTrafficGroupTargetRequest request) { - String path = String.format("/traffic-groups/%s/targets", request.getGroupId()); + return createTrafficGroupTarget(request.getGroupId(), request); + } + + /** Adds a target to a traffic group. */ + public TrafficGroupTarget createTrafficGroupTarget(String groupId, CreateTrafficGroupTargetRequest request) { + String path = String.format("/traffic-groups/%s/targets", seg(groupId)); return httpClient.post(path, request, TrafficGroupTarget.class); } @@ -1043,7 +1187,7 @@ public TrafficGroupTarget createTrafficGroupTarget(CreateTrafficGroupTargetReque * @throws GradientLabsException if the request fails */ public void deleteTrafficGroupTarget(String trafficGroupId, String targetId) { - String path = String.format("/traffic-groups/%s/targets/%s", trafficGroupId, targetId); + String path = String.format("/traffic-groups/%s/targets/%s", seg(trafficGroupId), seg(targetId)); httpClient.delete(path, Void.class); } @@ -1058,7 +1202,7 @@ public void deleteTrafficGroupTarget(String trafficGroupId, String targetId) { * @throws GradientLabsException if the request fails */ public TrafficGroupTarget createTrafficGroupExclusion(String groupId, CreateTrafficGroupExclusionRequest request) { - String path = String.format("/traffic-groups/%s/exclusions", groupId); + String path = String.format("/traffic-groups/%s/exclusions", seg(groupId)); return httpClient.post(path, request, TrafficGroupTarget.class); } @@ -1072,7 +1216,7 @@ public TrafficGroupTarget createTrafficGroupExclusion(String groupId, CreateTraf * @throws GradientLabsException if the request fails */ public void deleteTrafficGroupExclusion(String groupId, String targetId) { - String path = String.format("/traffic-groups/%s/exclusions/%s", groupId, targetId); + String path = String.format("/traffic-groups/%s/exclusions/%s", seg(groupId), seg(targetId)); httpClient.delete(path, Void.class); } @@ -1090,6 +1234,121 @@ public IPAddresses listIpAddresses() { return httpClient.get("/ip-addresses", null, IPAddresses.class); } + // ==================== Knowledge Base Operations ==================== + + /** + * Lists the knowledge bases created through the API. + *

+ * Note: Works with an Integration or a Management API key. + * + * @return the knowledge bases + * @throws GradientLabsException if the request fails + */ + public List listKnowledgeBases() { + KnowledgeBasesListResponse response = httpClient.get("/knowledge-bases", null, KnowledgeBasesListResponse.class); + return response.getKnowledgeBases(); + } + + /** + * Creates a knowledge base that articles and notes can be attached to. + *

+ * Note: Works with an Integration or a Management API key. + * + * @param request the knowledge base parameters + * @return the created knowledge base + * @throws GradientLabsException if the request fails + */ + public KnowledgeBase createKnowledgeBase(CreateKnowledgeBaseRequest request) { + return httpClient.post("/knowledge-bases", request, KnowledgeBase.class); + } + + /** + * Reads a knowledge base by your identifier for it. + *

+ * Note: Works with an Integration or a Management API key. + * + * @param knowledgeBaseId your identifier for the knowledge base + * @return the knowledge base + * @throws GradientLabsException if the request fails + */ + public KnowledgeBase readKnowledgeBase(String knowledgeBaseId) { + String path = String.format("/knowledge-bases/%s", seg(knowledgeBaseId)); + return httpClient.get(path, null, KnowledgeBase.class); + } + + /** + * Renames a knowledge base. + *

+ * Note: Works with an Integration or a Management API key. + * + * @param knowledgeBaseId your identifier for the knowledge base + * @param request the update parameters + * @return the updated knowledge base + * @throws GradientLabsException if the request fails + */ + public KnowledgeBase updateKnowledgeBase(String knowledgeBaseId, UpdateKnowledgeBaseRequest request) { + String path = String.format("/knowledge-bases/%s", seg(knowledgeBaseId)); + return httpClient.post(path, request, KnowledgeBase.class); + } + + // ==================== File Operations ==================== + + /** + * Starts uploading a file to the workspace. + *

+ * PUT the file to the returned {@link FileUpload#getUploadUrl()} with its headers, then call + * {@link #createFile(CreateFileRequest)} with the upload ID. + *

+ * Note: Requires a Management API key. + * + * @param request the upload parameters + * @return where and how to upload the file + * @throws GradientLabsException if the request fails + */ + public FileUpload beginFileUpload(BeginFileUploadRequest request) { + return httpClient.post("/file-uploads", request, FileUpload.class); + } + + /** + * Turns a finished upload into a workspace file. + *

+ * Note: Requires a Management API key. + * + * @param request the file parameters + * @return the created file + * @throws GradientLabsException if the request fails + */ + public WorkspaceFile createFile(CreateFileRequest request) { + return httpClient.post("/files", request, WorkspaceFile.class); + } + + /** + * Lists the first page of workspace files. + *

+ * Note: Requires a Management API key. + * + * @return the first page of files + * @throws GradientLabsException if the request fails + */ + public FileListResponse listFiles() { + return listFiles(null); + } + + /** + * Lists a page of workspace files. + *

+ * Note: Requires a Management API key. + * + * @param cursor the cursor from a previous page's pagination, or null for the first page + * @return the page of files + * @throws GradientLabsException if the request fails + */ + public FileListResponse listFiles(String cursor) { + Map query = new LinkedHashMap<>(); + query.put("cursor", cursor); + return httpClient.get("/files", query, FileListResponse.class); + } + // ==================== Terminology Substitution Operations ==================== /** @@ -1114,7 +1373,9 @@ public TerminologySubstitution createTerminologySubstitution(CreateTerminologySu * @throws GradientLabsException if the request fails */ public List listTerminologySubstitutions() { - return httpClient.getList("/terminology-substitutions", null, TerminologySubstitution.class); + TerminologySubstitutionsListResponse response = httpClient.get("/terminology-substitutions", null, + TerminologySubstitutionsListResponse.class); + return response.getSubstitutions(); } /** @@ -1127,7 +1388,7 @@ public List listTerminologySubstitutions() { * @throws GradientLabsException if the request fails */ public TerminologySubstitution readTerminologySubstitution(String substitutionId) { - String path = String.format("/terminology-substitutions/%s", substitutionId); + String path = String.format("/terminology-substitutions/%s", seg(substitutionId)); return httpClient.get(path, null, TerminologySubstitution.class); } @@ -1142,7 +1403,7 @@ public TerminologySubstitution readTerminologySubstitution(String substitutionId * @throws GradientLabsException if the request fails */ public TerminologySubstitution updateTerminologySubstitution(String substitutionId, UpdateTerminologySubstitutionRequest request) { - String path = String.format("/terminology-substitutions/%s", substitutionId); + String path = String.format("/terminology-substitutions/%s", seg(substitutionId)); return httpClient.put(path, request, TerminologySubstitution.class); } @@ -1155,7 +1416,7 @@ public TerminologySubstitution updateTerminologySubstitution(String substitution * @throws GradientLabsException if the request fails */ public void deleteTerminologySubstitution(String substitutionId) { - String path = String.format("/terminology-substitutions/%s", substitutionId); + String path = String.format("/terminology-substitutions/%s", seg(substitutionId)); httpClient.delete(path, Void.class); } @@ -1180,7 +1441,7 @@ public BackOfficeTask createBackOfficeTask(CreateBackOfficeTaskRequest request) * @throws GradientLabsException if the request fails */ public BackOfficeTask readBackOfficeTask(String taskId) { - String path = String.format("/back-office-tasks/%s/read", taskId); + String path = String.format("/back-office-tasks/%s/read", seg(taskId)); return httpClient.get(path, null, BackOfficeTask.class); } @@ -1196,7 +1457,7 @@ public BackOfficeTask readBackOfficeTask(String taskId) { * @throws GradientLabsException if the request fails */ public void deleteBackOfficeTask(String taskId) { - String path = String.format("/back-office-tasks/%s", taskId); + String path = String.format("/back-office-tasks/%s", seg(taskId)); httpClient.delete(path, Void.class); } @@ -1211,19 +1472,13 @@ public void deleteBackOfficeTask(String taskId) { * @throws GradientLabsException if the request fails */ public VoiceCallContext readVoiceCallContext(String phoneNumber, ReadVoiceCallContextRequest request) { - StringBuilder path = new StringBuilder(String.format("/voice/latest-call-context/%s", phoneNumber)); + String path = String.format("/voice/latest-call-context/%s", seg(phoneNumber)); + Map query = new LinkedHashMap<>(); if (request != null) { - boolean hasParam = false; - if (request.getLookbackSeconds() != null) { - path.append("?lookback_seconds=").append(request.getLookbackSeconds()); - hasParam = true; - } - if (request.getIncludeLargeFields() != null) { - path.append(hasParam ? "&" : "?"); - path.append("include_large_fields=").append(request.getIncludeLargeFields()); - } + query.put("lookback_seconds", request.getLookbackSeconds()); + query.put("include_large_fields", request.getIncludeLargeFields()); } - return httpClient.get(path.toString(), null, VoiceCallContext.class); + return httpClient.get(path, query, VoiceCallContext.class); } // ==================== Webhook Operations ==================== @@ -1261,6 +1516,13 @@ public void verifyWebhook(HttpServletRequest request) { webhookVerifier.verify(request); } + private record ProcedureLimitResponse(Procedure procedure) { + } + + private static String seg(String value) { + return HttpClientWrapper.pathSegment(value); + } + /** * Builder for constructing {@link GradientLabsClient} instances. */ diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/ListProcedureVersionsResponse.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/ListProcedureVersionsResponse.java index f90c734..ccd011c 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/ListProcedureVersionsResponse.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/ListProcedureVersionsResponse.java @@ -10,7 +10,7 @@ */ public class ListProcedureVersionsResponse { - @JsonProperty("versions") + @JsonProperty("Versions") private List versions; /** diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/internal/HttpClientWrapper.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/internal/HttpClientWrapper.java index ebb7b73..542e6d3 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/internal/HttpClientWrapper.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/internal/HttpClientWrapper.java @@ -4,15 +4,16 @@ import ai.gradientlabs.client.exception.ResponseException; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import java.net.URI; +import java.net.URLEncoder; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; import java.time.Duration; -import java.util.List; import java.util.Map; +import java.util.StringJoiner; /** * Internal HTTP client wrapper for making API requests. @@ -22,111 +23,107 @@ public class HttpClientWrapper { private final HttpClient httpClient; + private final String baseUrl; private final String apiKey; private final String userAgent; private final ObjectMapper objectMapper; - public HttpClientWrapper(HttpClient httpClient, String apiKey, String userAgent) { + /** + * Creates a wrapper that sends every request to {@code baseUrl} followed by the request path. + * + * @param httpClient the underlying HTTP client + * @param baseUrl the API base URL, such as {@code https://api.gradient-labs.ai} + * @param apiKey the API key sent as a bearer token + * @param userAgent the User-Agent header value + */ + public HttpClientWrapper(HttpClient httpClient, String baseUrl, String apiKey, String userAgent) { this.httpClient = httpClient; + this.baseUrl = stripTrailingSlash(baseUrl == null ? "" : baseUrl); this.apiKey = apiKey; this.userAgent = userAgent; - this.objectMapper = new ObjectMapper(); - this.objectMapper.registerModule(new JavaTimeModule()); + this.objectMapper = Json.newMapper(); } - public T get(String path, Object queryParams, Class responseType) { - try { - HttpRequest request = buildRequest("GET", path, null) - .build(); + /** + * Creates a wrapper whose request paths are absolute URLs. + * + * @param httpClient the underlying HTTP client + * @param apiKey the API key sent as a bearer token + * @param userAgent the User-Agent header value + */ + public HttpClientWrapper(HttpClient httpClient, String apiKey, String userAgent) { + this(httpClient, "", apiKey, userAgent); + } - HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); - return handleResponse(response, responseType); - } catch (Exception e) { - throw new GradientLabsException("Request failed", e); + /** + * Encodes a value for use as one path segment. + * + * @param value the raw value + * @return the encoded segment + */ + public static String pathSegment(String value) { + if (value == null) { + throw new IllegalArgumentException("path parameter must not be null"); } + return URLEncoder.encode(value, StandardCharsets.UTF_8).replace("+", "%20"); } - public List getList(String path, Object queryParams, Class itemType) { - try { - HttpRequest request = buildRequest("GET", path, null) - .build(); - - HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); - - if (response.statusCode() < 200 || response.statusCode() >= 300) { - throw parseError(response); - } - - return objectMapper.readValue( - response.body(), - objectMapper.getTypeFactory().constructCollectionType(List.class, itemType) - ); - } catch (ResponseException e) { - throw e; - } catch (Exception e) { - throw new GradientLabsException("Request failed", e); - } + public T get(String path, Map queryParams, Class responseType) { + return send("GET", withQuery(path, queryParams), null, responseType); } public T post(String path, Object body, Class responseType) { - try { - HttpRequest request = buildRequest("POST", path, body) - .build(); - - HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); - return handleResponse(response, responseType); - } catch (ResponseException e) { - throw e; - } catch (Exception e) { - throw new GradientLabsException("Request failed", e); - } + return send("POST", path, body, responseType); } public T put(String path, Object body, Class responseType) { - try { - HttpRequest request = buildRequest("PUT", path, body) - .build(); - - HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); - return handleResponse(response, responseType); - } catch (ResponseException e) { - throw e; - } catch (Exception e) { - throw new GradientLabsException("Request failed", e); - } + return send("PUT", path, body, responseType); } public T delete(String path, Class responseType) { - try { - HttpRequest request = buildRequest("DELETE", path, null) - .build(); + return send("DELETE", path, null, responseType); + } - HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); - return handleResponse(response, responseType); - } catch (ResponseException e) { - throw e; - } catch (Exception e) { - throw new GradientLabsException("Request failed", e); - } + public T delete(String path, Map queryParams, Class responseType) { + return send("DELETE", withQuery(path, queryParams), null, responseType); } - public T delete(String path, Object body, Class responseType) { + private T send(String method, String path, Object body, Class responseType) { try { - HttpRequest request = buildRequest("DELETE", path, body) - .build(); - + HttpRequest request = buildRequest(method, path, body).build(); HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); return handleResponse(response, responseType); - } catch (ResponseException e) { + } catch (GradientLabsException e) { throw e; + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new GradientLabsException("Request interrupted", e); } catch (Exception e) { throw new GradientLabsException("Request failed", e); } } + static String withQuery(String path, Map queryParams) { + if (queryParams == null || queryParams.isEmpty()) { + return path; + } + StringJoiner query = new StringJoiner("&"); + for (Map.Entry entry : queryParams.entrySet()) { + if (entry.getValue() == null) { + continue; + } + query.add(URLEncoder.encode(entry.getKey(), StandardCharsets.UTF_8) + "=" + + URLEncoder.encode(String.valueOf(entry.getValue()), StandardCharsets.UTF_8)); + } + if (query.length() == 0) { + return path; + } + return path + (path.contains("?") ? "&" : "?") + query; + } + private HttpRequest.Builder buildRequest(String method, String path, Object body) { try { - URI uri = URI.create(path); + URI uri = URI.create(baseUrl + path); HttpRequest.Builder builder = HttpRequest.newBuilder() .uri(uri) @@ -187,4 +184,8 @@ private ResponseException parseError(HttpResponse response) { ); } } + + private static String stripTrailingSlash(String url) { + return url.endsWith("/") ? url.substring(0, url.length() - 1) : url; + } } diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/internal/Json.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/internal/Json.java new file mode 100644 index 0000000..316ce8f --- /dev/null +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/internal/Json.java @@ -0,0 +1,32 @@ +package ai.gradientlabs.client.internal; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; + +/** + * Builds the JSON mapper shared by the HTTP client and the webhook verifier. + *

+ * This class is not part of the public API and may change without notice. + */ +public final class Json { + + private Json() { + } + + /** + * Returns a mapper that writes timestamps as RFC 3339 strings and tolerates fields and enum + * values the API adds later. + * + * @return a new mapper + */ + public static ObjectMapper newMapper() { + ObjectMapper mapper = new ObjectMapper(); + mapper.registerModule(new JavaTimeModule()); + mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); + mapper.enable(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL); + return mapper; + } +} diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/internal/NanosDurationDeserializer.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/internal/NanosDurationDeserializer.java new file mode 100644 index 0000000..fe9229f --- /dev/null +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/internal/NanosDurationDeserializer.java @@ -0,0 +1,25 @@ +package ai.gradientlabs.client.internal; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.DeserializationContext; +import com.fasterxml.jackson.databind.deser.std.StdDeserializer; + +import java.io.IOException; +import java.time.Duration; + +/** + * Reads a {@link Duration} from a whole number of nanoseconds, the API's wire format for durations. + *

+ * This class is not part of the public API and may change without notice. + */ +public class NanosDurationDeserializer extends StdDeserializer { + + public NanosDurationDeserializer() { + super(Duration.class); + } + + @Override + public Duration deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { + return Duration.ofNanos(p.getLongValue()); + } +} diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/internal/NanosDurationSerializer.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/internal/NanosDurationSerializer.java new file mode 100644 index 0000000..250007e --- /dev/null +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/internal/NanosDurationSerializer.java @@ -0,0 +1,25 @@ +package ai.gradientlabs.client.internal; + +import com.fasterxml.jackson.core.JsonGenerator; +import com.fasterxml.jackson.databind.SerializerProvider; +import com.fasterxml.jackson.databind.ser.std.StdSerializer; + +import java.io.IOException; +import java.time.Duration; + +/** + * Writes a {@link Duration} as a whole number of nanoseconds, the API's wire format for durations. + *

+ * This class is not part of the public API and may change without notice. + */ +public class NanosDurationSerializer extends StdSerializer { + + public NanosDurationSerializer() { + super(Duration.class); + } + + @Override + public void serialize(Duration value, JsonGenerator gen, SerializerProvider provider) throws IOException { + gen.writeNumber(value.toNanos()); + } +} diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/Attachment.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/Attachment.java index 48b23e8..3afd500 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/Attachment.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/Attachment.java @@ -16,6 +16,12 @@ public class Attachment { @JsonProperty("description") private String description; + @JsonProperty("summary") + private String summary; + + @JsonProperty("url") + private String url; + /** * Default constructor for Jackson. */ @@ -70,6 +76,32 @@ public void setDescription(String description) { this.description = description; } + /** + * Returns a summary of the attachment's contents. + * + * @return the summary + */ + public String getSummary() { + return summary; + } + + public void setSummary(String summary) { + this.summary = summary; + } + + /** + * Returns the URL the attachment can be downloaded from. + * + * @return the url + */ + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + @Override public String toString() { return "Attachment{" + diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/AttachmentTransferMode.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/AttachmentTransferMode.java new file mode 100644 index 0000000..6dcae42 --- /dev/null +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/AttachmentTransferMode.java @@ -0,0 +1,34 @@ +package ai.gradientlabs.client.model; + +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * How an attachment parameter is sent to a tool. + */ +public enum AttachmentTransferMode { + /** + * The file contents, base64-encoded. + */ + BASE64("base64"), + + /** + * A temporary URL the tool can download the file from. + */ + TEMPORARY_URL("temporary_url"); + + private final String value; + + AttachmentTransferMode(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return value; + } +} diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/AttachmentType.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/AttachmentType.java index 476357b..33c644d 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/AttachmentType.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/AttachmentType.java @@ -3,28 +3,18 @@ import com.fasterxml.jackson.annotation.JsonValue; /** - * The type of attachment. + * The type of a message attachment. */ public enum AttachmentType { /** - * Image attachment. + * An image. */ IMAGE("image"), /** - * Document attachment. + * Any other kind of file. */ - DOCUMENT("document"), - - /** - * Video attachment. - */ - VIDEO("video"), - - /** - * Audio attachment. - */ - AUDIO("audio"); + FILE("file"); private final String value; diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/Channel.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/Channel.java index 8c39e2d..ea3e6e2 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/Channel.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/Channel.java @@ -16,7 +16,12 @@ public enum Channel { /** * Email conversation. */ - EMAIL("email"); + EMAIL("email"), + + /** + * Voice (phone) conversation. + */ + VOICE("voice"); private final String value; diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/Conversation.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/Conversation.java index a9d4f3d..486273f 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/Conversation.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/Conversation.java @@ -19,9 +19,6 @@ public class Conversation { @JsonProperty("channel") private Channel channel; - @JsonProperty("metadata") - private Map metadata; - @JsonProperty("created") private Instant created; @@ -37,6 +34,12 @@ public class Conversation { @JsonProperty("latest_agent_metadata") private AgentMetadata agentMetadata; + @JsonProperty("latest_handoff_target") + private String latestHandoffTarget; + + @JsonProperty("latest_intent") + private String latestIntent; + /** * Default constructor for Jackson. */ @@ -77,17 +80,6 @@ public Channel getChannel() { return channel; } - /** - * Returns arbitrary metadata attached to the conversation. - *

- * This metadata will be passed along with webhooks and can be used as action parameters. - * - * @return the metadata, or null if none - */ - public Map getMetadata() { - return metadata; - } - /** * Returns the time at which the conversation was created. * @@ -133,6 +125,24 @@ public AgentMetadata getAgentMetadata() { return agentMetadata; } + /** + * Returns the hand-off target the conversation was last handed off to. + * + * @return the latest handoff target + */ + public String getLatestHandoffTarget() { + return latestHandoffTarget; + } + + /** + * Returns the intent most recently detected in the conversation. + * + * @return the latest intent + */ + public String getLatestIntent() { + return latestIntent; + } + @Override public String toString() { return "Conversation{" + diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/CustomerMemoriesListResponse.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/CustomerMemoriesListResponse.java new file mode 100644 index 0000000..d02295c --- /dev/null +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/CustomerMemoriesListResponse.java @@ -0,0 +1,29 @@ +package ai.gradientlabs.client.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.List; + +/** + * The response from listing a customer's memories. + */ +public class CustomerMemoriesListResponse { + + @JsonProperty("memories") + private List memories; + + /** + * Default constructor for Jackson. + */ + public CustomerMemoriesListResponse() { + } + + /** + * Returns the customer's memories. + * + * @return the memories + */ + public List getMemories() { + return memories; + } +} diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/CustomerMemory.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/CustomerMemory.java new file mode 100644 index 0000000..982f092 --- /dev/null +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/CustomerMemory.java @@ -0,0 +1,119 @@ +package ai.gradientlabs.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.time.Instant; + +/** + * A memory scoped to a customer, which the AI agent can search on demand. + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public class CustomerMemory { + + @JsonProperty("external_id") + private String externalId; + + @JsonProperty("custom_type") + private MemoryCustomType customType; + + @JsonProperty("created_at") + private Instant createdAt; + + @JsonInclude(JsonInclude.Include.ALWAYS) + @JsonProperty("data") + private Object data; + + /** + * Default constructor for Jackson. + */ + public CustomerMemory() { + } + + /** + * Creates a new instance. + * + * @param externalId your identifier for the memory, unique within your company. + * @param customType the memory's category. + * @param createdAt when the memory's underlying event happened. + * @param data the memory's payload, stored verbatim. + */ + public CustomerMemory(String externalId, MemoryCustomType customType, Instant createdAt, Object data) { + this.externalId = externalId; + this.customType = customType; + this.createdAt = createdAt; + this.data = data; + } + + /** + * Returns your identifier for the memory, unique within your company. + * + * @return the external id + */ + public String getExternalId() { + return externalId; + } + + /** + * Sets your identifier for the memory, unique within your company. + * + * @param externalId the external id + */ + public void setExternalId(String externalId) { + this.externalId = externalId; + } + + /** + * Returns the memory's category. + * + * @return the custom type + */ + public MemoryCustomType getCustomType() { + return customType; + } + + /** + * Sets the memory's category. + * + * @param customType the custom type + */ + public void setCustomType(MemoryCustomType customType) { + this.customType = customType; + } + + /** + * Returns when the memory's underlying event happened. + * + * @return the created at + */ + public Instant getCreatedAt() { + return createdAt; + } + + /** + * Sets when the memory's underlying event happened. + * + * @param createdAt the created at + */ + public void setCreatedAt(Instant createdAt) { + this.createdAt = createdAt; + } + + /** + * Returns the memory's payload, stored verbatim. + * + * @return the data + */ + public Object getData() { + return data; + } + + /** + * Sets the memory's payload, stored verbatim. + * + * @param data the data + */ + public void setData(Object data) { + this.data = data; + } +} diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/CustomerSupportPlatformIdentifierType.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/CustomerSupportPlatformIdentifierType.java index 436fa3d..10eb881 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/CustomerSupportPlatformIdentifierType.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/CustomerSupportPlatformIdentifierType.java @@ -3,39 +3,48 @@ import com.fasterxml.jackson.annotation.JsonValue; /** - * The kind of identifier a {@link CustomerSupportPlatformIdentifier} represents, for - * platforms that have more than one kind of customer identifier. + * The kind of identifier a customer has on a support platform. */ public enum CustomerSupportPlatformIdentifierType { /** - * An Intercom lead ID. + * An Intercom lead. */ INTERCOM_LEAD("intercom_lead"), /** - * An Intercom user ID. + * An Intercom user. */ INTERCOM_USER("intercom_user"), /** - * A Zendesk end-user ID from a messaging conversation. + * A Zendesk conversations (messaging) user. */ ZENDESK_CONVERSATION_USER("zendesk_conversation_user"), /** - * A Zendesk support (ticketing) user ID. + * A Zendesk Support user. */ ZENDESK_SUPPORT_USER("zendesk_support_user"), /** - * A Salesforce Contact ID. + * A Salesforce contact ID. */ SALESFORCE_CONTACT_ID("salesforce_contact_id"), /** - * A Salesforce Account ID. + * A Salesforce account ID. */ - SALESFORCE_ACCOUNT_ID("salesforce_account_id"); + SALESFORCE_ACCOUNT_ID("salesforce_account_id"), + + /** + * The email address on a Salesforce contact. + */ + SALESFORCE_CONTACT_EMAIL("salesforce_contact_email"), + + /** + * An email address supplied on a Salesforce case. + */ + SALESFORCE_SUPPLIED_EMAIL("salesforce_supplied_email"); private final String value; diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/FileListResponse.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/FileListResponse.java new file mode 100644 index 0000000..687f589 --- /dev/null +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/FileListResponse.java @@ -0,0 +1,41 @@ +package ai.gradientlabs.client.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.List; + +/** + * A page of workspace files. + */ +public class FileListResponse { + + @JsonProperty("files") + private List files; + + @JsonProperty("pagination") + private ForwardPagination pagination; + + /** + * Default constructor for Jackson. + */ + public FileListResponse() { + } + + /** + * Returns the files on this page. + * + * @return the files + */ + public List getFiles() { + return files; + } + + /** + * Returns the cursors for the next and previous pages. + * + * @return the pagination + */ + public ForwardPagination getPagination() { + return pagination; + } +} diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/FileUpload.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/FileUpload.java new file mode 100644 index 0000000..bae43bf --- /dev/null +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/FileUpload.java @@ -0,0 +1,90 @@ +package ai.gradientlabs.client.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.time.Instant; +import java.util.Map; + +/** + * An upload started with {@code beginFileUpload}. PUT the file to {@link #getUploadUrl()} with {@link #getHeaders()}, then call {@code createFile}. + */ +public class FileUpload { + + @JsonProperty("upload_id") + private String uploadId; + + @JsonProperty("upload_url") + private String uploadUrl; + + @JsonProperty("headers") + private Map headers; + + @JsonProperty("content_type") + private String contentType; + + @JsonProperty("max_bytes") + private Long maxBytes; + + @JsonProperty("expires_at") + private Instant expiresAt; + + /** + * Default constructor for Jackson. + */ + public FileUpload() { + } + + /** + * Returns the upload's ID, passed to {@code createFile}. + * + * @return the upload id + */ + public String getUploadId() { + return uploadId; + } + + /** + * Returns the URL to PUT the file to. + * + * @return the upload url + */ + public String getUploadUrl() { + return uploadUrl; + } + + /** + * Returns the headers to send with the PUT. + * + * @return the headers + */ + public Map getHeaders() { + return headers; + } + + /** + * Returns the content type to upload with. + * + * @return the content type + */ + public String getContentType() { + return contentType; + } + + /** + * Returns the largest file allowed, in bytes. + * + * @return the max bytes + */ + public Long getMaxBytes() { + return maxBytes; + } + + /** + * Returns when the upload URL stops working. + * + * @return the expires at + */ + public Instant getExpiresAt() { + return expiresAt; + } +} diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ForwardPagination.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ForwardPagination.java new file mode 100644 index 0000000..1a72254 --- /dev/null +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ForwardPagination.java @@ -0,0 +1,14 @@ +package ai.gradientlabs.client.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** Cursor for fetching the next page of results. */ +public class ForwardPagination { + + @JsonProperty("next") + private String next; + + public String getNext() { + return next; + } +} diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/GatedConfig.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/GatedConfig.java index 31ee455..c700db4 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/GatedConfig.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/GatedConfig.java @@ -9,7 +9,7 @@ */ public class GatedConfig { - @JsonProperty("max_daily_conversations") + @JsonProperty("MaxDailyConversations") private int maxDailyConversations; /** diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/HTTPBodyDefinition.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/HTTPBodyDefinition.java index 312938b..1772428 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/HTTPBodyDefinition.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/HTTPBodyDefinition.java @@ -1,12 +1,14 @@ package ai.gradientlabs.client.model; +import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Map; /** - * Defines how the HTTP body should be encoded. + * The body of an HTTP request made by a tool or a secret refresh. */ +@JsonInclude(JsonInclude.Include.NON_NULL) public class HTTPBodyDefinition { @JsonProperty("encoding") @@ -24,15 +26,70 @@ public class HTTPBodyDefinition { public HTTPBodyDefinition() { } + /** + * Creates a new instance. + * + * @param encoding the body encoding: {@code application/json} or {@code application/x-www-form-urlencoded}. + * @param jsonTemplate the template for a JSON body. + * @param formFieldTemplates the templates for form fields, by field name. + */ + public HTTPBodyDefinition(String encoding, String jsonTemplate, Map formFieldTemplates) { + this.encoding = encoding; + this.jsonTemplate = jsonTemplate; + this.formFieldTemplates = formFieldTemplates; + } + + /** + * Returns the body encoding: {@code application/json} or {@code application/x-www-form-urlencoded}. + * + * @return the encoding + */ public String getEncoding() { return encoding; } + /** + * Sets the body encoding: {@code application/json} or {@code application/x-www-form-urlencoded}. + * + * @param encoding the encoding + */ + public void setEncoding(String encoding) { + this.encoding = encoding; + } + + /** + * Returns the template for a JSON body. + * + * @return the json template + */ public String getJsonTemplate() { return jsonTemplate; } + /** + * Sets the template for a JSON body. + * + * @param jsonTemplate the json template + */ + public void setJsonTemplate(String jsonTemplate) { + this.jsonTemplate = jsonTemplate; + } + + /** + * Returns the templates for form fields, by field name. + * + * @return the form field templates + */ public Map getFormFieldTemplates() { return formFieldTemplates; } + + /** + * Sets the templates for form fields, by field name. + * + * @param formFieldTemplates the form field templates + */ + public void setFormFieldTemplates(Map formFieldTemplates) { + this.formFieldTemplates = formFieldTemplates; + } } diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/HTTPDefinition.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/HTTPDefinition.java index 7f99f3c..0a0cd51 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/HTTPDefinition.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/HTTPDefinition.java @@ -1,12 +1,14 @@ package ai.gradientlabs.client.model; +import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Map; /** - * Defines an HTTP request configuration. + * Defines an HTTP request made by a tool. */ +@JsonInclude(JsonInclude.Include.NON_NULL) public class HTTPDefinition { @JsonProperty("method") @@ -21,25 +23,119 @@ public class HTTPDefinition { @JsonProperty("body") private HTTPBodyDefinition body; + @JsonProperty("retry") + private RetryPolicy retry; + /** * Default constructor for Jackson. */ public HTTPDefinition() { } + /** + * Creates a new instance. + * + * @param method the HTTP method. + * @param urlTemplate the URL template. + * @param headerTemplates the header templates, by header name. + * @param body the request body definition. + * @param retry the retry policy override, or null for the default. + */ + public HTTPDefinition(String method, String urlTemplate, Map headerTemplates, HTTPBodyDefinition body, RetryPolicy retry) { + this.method = method; + this.urlTemplate = urlTemplate; + this.headerTemplates = headerTemplates; + this.body = body; + this.retry = retry; + } + + /** + * Returns the HTTP method. + * + * @return the method + */ public String getMethod() { return method; } + /** + * Sets the HTTP method. + * + * @param method the method + */ + public void setMethod(String method) { + this.method = method; + } + + /** + * Returns the URL template. + * + * @return the url template + */ public String getUrlTemplate() { return urlTemplate; } + /** + * Sets the URL template. + * + * @param urlTemplate the url template + */ + public void setUrlTemplate(String urlTemplate) { + this.urlTemplate = urlTemplate; + } + + /** + * Returns the header templates, by header name. + * + * @return the header templates + */ public Map getHeaderTemplates() { return headerTemplates; } + /** + * Sets the header templates, by header name. + * + * @param headerTemplates the header templates + */ + public void setHeaderTemplates(Map headerTemplates) { + this.headerTemplates = headerTemplates; + } + + /** + * Returns the request body definition. + * + * @return the body + */ public HTTPBodyDefinition getBody() { return body; } + + /** + * Sets the request body definition. + * + * @param body the body + */ + public void setBody(HTTPBodyDefinition body) { + this.body = body; + } + + /** + * Returns the retry policy override, or null for the default. + * + * @return the retry + */ + public RetryPolicy getRetry() { + return retry; + } + + /** + * Sets the retry policy override, or null for the default. + * + * @param retry the retry + */ + public void setRetry(RetryPolicy retry) { + this.retry = retry; + } } diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/HandOffTarget.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/HandOffTarget.java index 69c3e90..0f61137 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/HandOffTarget.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/HandOffTarget.java @@ -16,6 +16,9 @@ public class HandOffTarget { @JsonProperty("name") private String name; + @JsonProperty("ref") + private String ref; + /** * Default constructor for Jackson. */ @@ -42,6 +45,15 @@ public String getName() { return name; } + /** + * Returns the reference used to point to this target from procedures. + * + * @return the ref + */ + public String getRef() { + return ref; + } + @Override public String toString() { return "HandOffTarget{" + diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/KnowledgeBase.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/KnowledgeBase.java new file mode 100644 index 0000000..60640b7 --- /dev/null +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/KnowledgeBase.java @@ -0,0 +1,77 @@ +package ai.gradientlabs.client.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.time.Instant; + +/** + * A knowledge base that articles and notes can be attached to. + */ +public class KnowledgeBase { + + @JsonProperty("id") + private String id; + + @JsonProperty("gradient_labs_id") + private String gradientLabsId; + + @JsonProperty("name") + private String name; + + @JsonProperty("created") + private Instant created; + + @JsonProperty("updated") + private Instant updated; + + /** + * Default constructor for Jackson. + */ + public KnowledgeBase() { + } + + /** + * Returns your identifier for the knowledge base. + * + * @return the id + */ + public String getId() { + return id; + } + + /** + * Returns the identifier Gradient Labs gave the knowledge base. + * + * @return the gradient labs id + */ + public String getGradientLabsId() { + return gradientLabsId; + } + + /** + * Returns the knowledge base's name. + * + * @return the name + */ + public String getName() { + return name; + } + + /** + * Returns when the knowledge base was created. + * + * @return the created + */ + public Instant getCreated() { + return created; + } + + /** + * Returns when the knowledge base was last updated. + * + * @return the updated + */ + public Instant getUpdated() { + return updated; + } +} diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/KnowledgeBasesListResponse.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/KnowledgeBasesListResponse.java new file mode 100644 index 0000000..2baa508 --- /dev/null +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/KnowledgeBasesListResponse.java @@ -0,0 +1,29 @@ +package ai.gradientlabs.client.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.List; + +/** + * The response from listing knowledge bases. + */ +public class KnowledgeBasesListResponse { + + @JsonProperty("knowledge_bases") + private List knowledgeBases; + + /** + * Default constructor for Jackson. + */ + public KnowledgeBasesListResponse() { + } + + /** + * Returns the knowledge bases. + * + * @return the knowledge bases + */ + public List getKnowledgeBases() { + return knowledgeBases; + } +} diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ListTopicsResponse.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ListTopicsResponse.java index 9bdbbc3..30f6e51 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ListTopicsResponse.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ListTopicsResponse.java @@ -9,7 +9,7 @@ */ public class ListTopicsResponse { - @JsonProperty("topics") + @JsonProperty("Topics") private List topics; /** diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ManagedResourceSource.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ManagedResourceSource.java new file mode 100644 index 0000000..d30d3b3 --- /dev/null +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ManagedResourceSource.java @@ -0,0 +1,39 @@ +package ai.gradientlabs.client.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Describes a resource source that Gradient Labs manages for you. + */ +public class ManagedResourceSource { + + @JsonProperty("enabled") + private Boolean enabled; + + @JsonProperty("key") + private String key; + + /** + * Default constructor for Jackson. + */ + public ManagedResourceSource() { + } + + /** + * Returns whether the managed source is enabled. + * + * @return the enabled + */ + public Boolean getEnabled() { + return enabled; + } + + /** + * Returns the key of the managed source. + * + * @return the key + */ + public String getKey() { + return key; + } +} diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/Memory.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/Memory.java new file mode 100644 index 0000000..16b036c --- /dev/null +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/Memory.java @@ -0,0 +1,135 @@ +package ai.gradientlabs.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.node.NullNode; + +import java.time.Instant; + +/** + * A single memory to create for a customer with the deprecated v1 batch-create endpoint. + *

+ * Use {@link CustomerMemory} with {@code batchCreateCustomerMemoriesV2} instead, which also takes a + * category description. + *

+ * The {@code data} payload is stored verbatim as arbitrary JSON for the AI agent + * to search over on demand. + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public class Memory { + + @JsonProperty("external_id") + private final String externalId; + + @JsonProperty("custom_type") + private final String customType; + + @JsonProperty("created_at") + private final Instant createdAt; + + @JsonProperty("data") + private final Object data; + + private Memory(Builder builder) { + this.externalId = builder.externalId; + this.customType = builder.customType; + this.createdAt = builder.createdAt; + this.data = builder.data; + } + + public static Builder builder() { + return new Builder(); + } + + public String getExternalId() { + return externalId; + } + + public String getCustomType() { + return customType; + } + + public Instant getCreatedAt() { + return createdAt; + } + + public Object getData() { + return data; + } + + public static class Builder { + private String externalId; + private String customType; + private Instant createdAt; + private Object data; + + private Builder() { + } + + /** + * Sets the caller's own identifier for this memory (required). + * + * @param externalId the external ID + * @return this builder + */ + public Builder externalId(String externalId) { + this.externalId = externalId; + return this; + } + + /** + * Sets the category name for this memory (required). {@code support_conversation} is reserved. + * + * @param customType the custom type + * @return this builder + */ + public Builder customType(String customType) { + this.customType = customType; + return this; + } + + /** + * Sets the time the memory was created (required). + * + * @param createdAt the creation timestamp + * @return this builder + */ + public Builder createdAt(Instant createdAt) { + this.createdAt = createdAt; + return this; + } + + /** + * Sets the arbitrary JSON payload stored verbatim as the memory (required). + * + * @param data the memory data + * @return this builder + */ + public Builder data(Object data) { + this.data = data == null ? NullNode.getInstance() : data; + return this; + } + + /** + * Builds the memory. + * + * @return a new memory instance + * @throws IllegalStateException if required fields are missing + */ + public Memory build() { + if (externalId == null || externalId.isBlank()) { + throw new IllegalStateException("externalId is required"); + } + if (customType == null || customType.isBlank()) { + throw new IllegalStateException("customType is required"); + } + if (createdAt == null) { + throw new IllegalStateException("createdAt is required"); + } + if (data == null) { + throw new IllegalStateException("data is required"); + } + return new Memory(this); + } + } +} diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/MemoryCustomType.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/MemoryCustomType.java new file mode 100644 index 0000000..bcc65c7 --- /dev/null +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/MemoryCustomType.java @@ -0,0 +1,70 @@ +package ai.gradientlabs.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * The category of a customer memory. + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public class MemoryCustomType { + + @JsonProperty("name") + private String name; + + @JsonProperty("description") + private String description; + + /** + * Default constructor for Jackson. + */ + public MemoryCustomType() { + } + + /** + * Creates a new instance. + * + * @param name the category name. {@code support_conversation} is reserved for Gradient Labs. + * @param description a description of the category, or null. + */ + public MemoryCustomType(String name, String description) { + this.name = name; + this.description = description; + } + + /** + * Returns the category name. {@code support_conversation} is reserved for Gradient Labs. + * + * @return the name + */ + public String getName() { + return name; + } + + /** + * Sets the category name. {@code support_conversation} is reserved for Gradient Labs. + * + * @param name the name + */ + public void setName(String name) { + this.name = name; + } + + /** + * Returns a description of the category, or null. + * + * @return the description + */ + public String getDescription() { + return description; + } + + /** + * Sets a description of the category, or null. + * + * @param description the description + */ + public void setDescription(String description) { + this.description = description; + } +} diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/Message.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/Message.java index 0ccdd3e..fef6af5 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/Message.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/Message.java @@ -14,9 +14,6 @@ public class Message { @JsonProperty("id") private String id; - @JsonProperty("conversation_id") - private String conversationId; - @JsonProperty("participant_id") private String participantId; @@ -29,9 +26,6 @@ public class Message { @JsonProperty("created") private Instant created; - @JsonProperty("metadata") - private Map metadata; - @JsonProperty("attachments") private List attachments; @@ -45,10 +39,6 @@ public String getId() { return id; } - public String getConversationId() { - return conversationId; - } - public String getParticipantId() { return participantId; } @@ -65,10 +55,6 @@ public Instant getCreated() { return created; } - public Map getMetadata() { - return metadata; - } - public List getAttachments() { return attachments; } @@ -77,7 +63,6 @@ public List getAttachments() { public String toString() { return "Message{" + "id='" + id + '\'' + - ", conversationId='" + conversationId + '\'' + ", participantId='" + participantId + '\'' + ", participantType=" + participantType + ", body='" + body + '\'' + diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/Note.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/Note.java index 297758c..b9fba71 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/Note.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/Note.java @@ -2,6 +2,8 @@ import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.Map; +import java.util.List; import java.time.Instant; /** @@ -42,6 +44,9 @@ public class Note { @JsonProperty("status") private NoteStatus status; + @JsonProperty("attributes") + private Map> attributes; + /** * Default constructor for Jackson. */ @@ -149,6 +154,15 @@ public NoteStatus getStatus() { return status; } + /** + * Returns the note's attributes, by attribute name. + * + * @return the attributes + */ + public Map> getAttributes() { + return attributes; + } + @Override public String toString() { return "Note{" + diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/NoteListResponse.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/NoteListResponse.java new file mode 100644 index 0000000..ceb0b3a --- /dev/null +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/NoteListResponse.java @@ -0,0 +1,41 @@ +package ai.gradientlabs.client.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.List; + +/** + * A page of notes. + */ +public class NoteListResponse { + + @JsonProperty("notes") + private List notes; + + @JsonProperty("pagination") + private ForwardPagination pagination; + + /** + * Default constructor for Jackson. + */ + public NoteListResponse() { + } + + /** + * Returns the notes on this page. + * + * @return the notes + */ + public List getNotes() { + return notes; + } + + /** + * Returns the cursors for the next and previous pages. + * + * @return the pagination + */ + public ForwardPagination getPagination() { + return pagination; + } +} diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ParticipantType.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ParticipantType.java index f347714..f4e88c3 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ParticipantType.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ParticipantType.java @@ -9,17 +9,22 @@ public enum ParticipantType { /** * The customer. */ - CUSTOMER("customer"), + CUSTOMER("Customer"), /** * A human agent. */ - HUMAN("human"), + AGENT("Agent"), /** - * The AI agent. + * The Gradient Labs AI agent. */ - AI_AGENT("ai_agent"); + AI_AGENT("AI Agent"), + + /** + * An automated system other than the Gradient Labs AI agent, such as a chatbot. + */ + BOT("Bot"); private final String value; diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/Procedure.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/Procedure.java index 86ebbf4..fa8d71c 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/Procedure.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/Procedure.java @@ -23,9 +23,6 @@ public class Procedure { @JsonProperty("status") private ProcedureStatus status; - @JsonProperty("author") - private UserDetails author; - @JsonProperty("created") private Instant created; @@ -110,24 +107,6 @@ public void setStatus(ProcedureStatus status) { this.status = status; } - /** - * Gets the user who originally created the procedure. - * - * @return the author details - */ - public UserDetails getAuthor() { - return author; - } - - /** - * Sets the procedure author. - * - * @param author the author details - */ - public void setAuthor(UserDetails author) { - this.author = author; - } - /** * Gets the time at which the procedure was originally created. * @@ -212,7 +191,6 @@ public String toString() { ", name='" + name + '\'' + ", description='" + description + '\'' + ", status=" + status + - ", author=" + author + ", created=" + created + ", updated=" + updated + ", isDailyLimited=" + isDailyLimited + diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ProcedureStatus.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ProcedureStatus.java index 71f479d..8ba7d8b 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ProcedureStatus.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ProcedureStatus.java @@ -3,22 +3,28 @@ import com.fasterxml.jackson.annotation.JsonValue; /** - * Status of a procedure. - *

- * Procedures can be in draft mode (saved but not used in real conversations) - * or live mode (actively used in conversations). + * The status of a procedure. */ public enum ProcedureStatus { /** - * The procedure has been saved as a draft, but won't be used in real - * conversations until it is promoted to live. + * The procedure has never been saved. + */ + UNSAVED("unsaved"), + + /** + * The procedure is a draft and not used by the AI agent. */ DRAFT("draft"), /** - * The procedure is live and will be used in real conversations. + * The procedure is live and used by the AI agent. + */ + LIVE("live"), + + /** + * The procedure has been archived. */ - LIVE("live"); + ARCHIVED("archived"); private final String value; diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ProcedureVersion.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ProcedureVersion.java index d0ac667..dbf9d58 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ProcedureVersion.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ProcedureVersion.java @@ -12,28 +12,28 @@ */ public class ProcedureVersion { - @JsonProperty("name") + @JsonProperty("Name") private String name; - @JsonProperty("description") + @JsonProperty("Description") private String description; - @JsonProperty("version") + @JsonProperty("Version") private int version; - @JsonProperty("author") + @JsonProperty("Author") private String author; - @JsonProperty("created") + @JsonProperty("Created") private Instant created; - @JsonProperty("gated") + @JsonProperty("Gated") private boolean gated; - @JsonProperty("gated_config") + @JsonProperty("GatedConfig") private GatedConfig gatedConfig; - @JsonProperty("live") + @JsonProperty("Live") private boolean live; /** diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/PublicationStatus.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/PublicationStatus.java index 2a4bae6..8f99894 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/PublicationStatus.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/PublicationStatus.java @@ -3,18 +3,28 @@ import com.fasterxml.jackson.annotation.JsonValue; /** - * Describes the publication status of a help article or topic. + * The publication status of an article or topic. */ public enum PublicationStatus { /** - * The article or topic is being written or edited and is not published. + * Not yet published. */ DRAFT("draft"), /** - * The article or topic is published. + * Published. */ - PUBLISHED("published"); + PUBLISHED("published"), + + /** + * Deleted. Only valid for articles. + */ + DELETED("deleted"), + + /** + * Excluded from use by the AI agent. Only valid for articles. + */ + EXCLUDED("excluded"); private final String value; diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/RefreshMechanismHTTP.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/RefreshMechanismHTTP.java index 9e5d022..51c3a54 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/RefreshMechanismHTTP.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/RefreshMechanismHTTP.java @@ -1,15 +1,16 @@ package ai.gradientlabs.client.model; +import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; /** - * Defines how to automatically refresh a secret's value using an HTTP request. - * This is commonly used for OAuth access tokens that need periodic renewal. + * Defines how a secret is refreshed with an HTTP request. */ +@JsonInclude(JsonInclude.Include.NON_NULL) public class RefreshMechanismHTTP { @JsonProperty("request_definition") - private HTTPDefinition requestDefinition; + private SecretRefreshRequest requestDefinition; @JsonProperty("response_param_name") private String responseParamName; @@ -21,20 +22,49 @@ public RefreshMechanismHTTP() { } /** - * Gets the HTTP request definition for refreshing the secret. + * Creates a new instance. + * + * @param requestDefinition the request that fetches the new secret value. + * @param responseParamName the response field that holds the new secret value. + */ + public RefreshMechanismHTTP(SecretRefreshRequest requestDefinition, String responseParamName) { + this.requestDefinition = requestDefinition; + this.responseParamName = responseParamName; + } + + /** + * Returns the request that fetches the new secret value. * * @return the request definition */ - public HTTPDefinition getRequestDefinition() { + public SecretRefreshRequest getRequestDefinition() { return requestDefinition; } /** - * Gets the JSON field name in the response that contains the new secret value. + * Sets the request that fetches the new secret value. * - * @return the response parameter name + * @param requestDefinition the request definition + */ + public void setRequestDefinition(SecretRefreshRequest requestDefinition) { + this.requestDefinition = requestDefinition; + } + + /** + * Returns the response field that holds the new secret value. + * + * @return the response param name */ public String getResponseParamName() { return responseParamName; } + + /** + * Sets the response field that holds the new secret value. + * + * @param responseParamName the response param name + */ + public void setResponseParamName(String responseParamName) { + this.responseParamName = responseParamName; + } } diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ResourceSource.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ResourceSource.java index 410c844..866f29e 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ResourceSource.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ResourceSource.java @@ -2,6 +2,7 @@ import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; import java.time.Instant; import java.util.Map; @@ -40,6 +41,15 @@ public class ResourceSource { @JsonProperty("updated") private Instant updated; + @JsonProperty("available_refresh_strategies") + private List availableRefreshStrategies; + + @JsonProperty("available_scopes") + private List availableScopes; + + @JsonProperty("managed") + private ManagedResourceSource managed; + /** * Default constructor for Jackson. */ @@ -225,4 +235,31 @@ public Instant getUpdated() { public void setUpdated(Instant updated) { this.updated = updated; } + + /** + * Returns the refresh strategies resource types using this source may choose. + * + * @return the available refresh strategies + */ + public List getAvailableRefreshStrategies() { + return availableRefreshStrategies; + } + + /** + * Returns the scopes resource types using this source may choose. + * + * @return the available scopes + */ + public List getAvailableScopes() { + return availableScopes; + } + + /** + * Returns details of the managed source, if Gradient Labs manages it. + * + * @return the managed + */ + public ManagedResourceSource getManaged() { + return managed; + } } diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ResourceSourceSchemaUpdate.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ResourceSourceSchemaUpdate.java new file mode 100644 index 0000000..8023309 --- /dev/null +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ResourceSourceSchemaUpdate.java @@ -0,0 +1,12 @@ +package ai.gradientlabs.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.Map; + +/** The JSON Schema to apply to a resource source. */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public record ResourceSourceSchemaUpdate( + @JsonProperty("raw") Map raw) { +} diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/RetryPolicy.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/RetryPolicy.java new file mode 100644 index 0000000..5ee65f3 --- /dev/null +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/RetryPolicy.java @@ -0,0 +1,70 @@ +package ai.gradientlabs.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Overrides how an HTTP request is retried. + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public class RetryPolicy { + + @JsonProperty("max_attempts") + private Integer maxAttempts; + + @JsonProperty("request_timeout_seconds") + private Integer requestTimeoutSeconds; + + /** + * Default constructor for Jackson. + */ + public RetryPolicy() { + } + + /** + * Creates a new instance. + * + * @param maxAttempts the maximum number of attempts, including the first. + * @param requestTimeoutSeconds how long to wait for each attempt, in seconds. + */ + public RetryPolicy(Integer maxAttempts, Integer requestTimeoutSeconds) { + this.maxAttempts = maxAttempts; + this.requestTimeoutSeconds = requestTimeoutSeconds; + } + + /** + * Returns the maximum number of attempts, including the first. + * + * @return the max attempts + */ + public Integer getMaxAttempts() { + return maxAttempts; + } + + /** + * Sets the maximum number of attempts, including the first. + * + * @param maxAttempts the max attempts + */ + public void setMaxAttempts(Integer maxAttempts) { + this.maxAttempts = maxAttempts; + } + + /** + * Returns how long to wait for each attempt, in seconds. + * + * @return the request timeout seconds + */ + public Integer getRequestTimeoutSeconds() { + return requestTimeoutSeconds; + } + + /** + * Sets how long to wait for each attempt, in seconds. + * + * @param requestTimeoutSeconds the request timeout seconds + */ + public void setRequestTimeoutSeconds(Integer requestTimeoutSeconds) { + this.requestTimeoutSeconds = requestTimeoutSeconds; + } +} diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/SecretRefreshRequest.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/SecretRefreshRequest.java new file mode 100644 index 0000000..2c5705f --- /dev/null +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/SecretRefreshRequest.java @@ -0,0 +1,16 @@ +package ai.gradientlabs.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.Map; + +/** The HTTP request used to refresh a secret. */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public record SecretRefreshRequest( + @JsonProperty("method") String method, + @JsonProperty("url_template") String urlTemplate, + @JsonProperty("header_templates") Map headerTemplates, + @JsonProperty("body") HTTPBodyDefinition body, + @JsonProperty("retry") SecretRefreshRetry retry) { +} diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/SecretRefreshRetry.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/SecretRefreshRetry.java new file mode 100644 index 0000000..6363cec --- /dev/null +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/SecretRefreshRetry.java @@ -0,0 +1,10 @@ +package ai.gradientlabs.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** Timeout for each attempt to refresh a secret. */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public record SecretRefreshRetry( + @JsonProperty("request_timeout_seconds") Integer requestTimeoutSeconds) { +} diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/SupportPlatform.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/SupportPlatform.java index a704c54..d1a72a8 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/SupportPlatform.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/SupportPlatform.java @@ -3,18 +3,53 @@ import com.fasterxml.jackson.annotation.JsonValue; /** - * A third-party customer support platform. + * A customer support platform. */ public enum SupportPlatform { + /** + * Dixa. + */ + DIXA("dixa"), + + /** + * Freshchat. + */ + FRESHCHAT("freshchat"), + + /** + * Freshdesk. + */ + FRESHDESK("freshdesk"), + + /** + * Gmail. + */ + GMAIL("gmail"), + /** * Intercom. */ INTERCOM("intercom"), /** - * Zendesk. + * Kustomer. */ - ZENDESK("zendesk"), + KUSTOMER("kustomer"), + + /** + * LiveChat. + */ + LIVECHAT("livechat"), + + /** + * The Gradient Labs public API. + */ + PUBLIC_API("public-api"), + + /** + * The Gradient Labs chat SDK. + */ + CHAT_SDK("chat-sdk"), /** * Salesforce. @@ -22,14 +57,29 @@ public enum SupportPlatform { SALESFORCE("salesforce"), /** - * Freshchat. + * Zendesk. */ - FRESHCHAT("freshchat"), + ZENDESK("zendesk"), /** - * Freshdesk. + * LiveKit. + */ + LIVEKIT("livekit"), + + /** + * Twilio. + */ + TWILIO("twilio"), + + /** + * Talkdesk. + */ + TALKDESK("talkdesk"), + + /** + * Intercom voice. */ - FRESHDESK("freshdesk"); + INTERCOM_VOICE("intercom-voice"); private final String value; diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/TerminologySubstitutionsListResponse.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/TerminologySubstitutionsListResponse.java new file mode 100644 index 0000000..7b00d74 --- /dev/null +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/TerminologySubstitutionsListResponse.java @@ -0,0 +1,29 @@ +package ai.gradientlabs.client.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.List; + +/** + * The response from listing terminology substitutions. + */ +public class TerminologySubstitutionsListResponse { + + @JsonProperty("substitutions") + private List substitutions; + + /** + * Default constructor for Jackson. + */ + public TerminologySubstitutionsListResponse() { + } + + /** + * Returns the terminology substitutions. + * + * @return the substitutions + */ + public List getSubstitutions() { + return substitutions; + } +} diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/Tool.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/Tool.java index df23cc6..cbe142d 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/Tool.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/Tool.java @@ -2,11 +2,10 @@ import com.fasterxml.jackson.annotation.JsonProperty; -import java.time.Instant; -import java.util.Map; +import java.util.List; /** - * Represents a tool that the AI agent can use. + * A tool the AI agent can use. */ public class Tool { @@ -19,14 +18,32 @@ public class Tool { @JsonProperty("description") private String description; - @JsonProperty("schema") - private Map schema; + @JsonProperty("parameters") + private List parameters; - @JsonProperty("created") - private Instant created; + @JsonProperty("parameter_sets") + private List parameterSets; - @JsonProperty("updated") - private Instant updated; + @JsonProperty("http") + private HTTPDefinition http; + + @JsonProperty("webhook") + private ToolWebhookDefinition webhook; + + @JsonProperty("async") + private ToolAsyncDefinition async; + + @JsonProperty("mcp") + private ToolMcpDefinition mcp; + + @JsonProperty("draft") + private Boolean draft; + + @JsonProperty("branch_id") + private String branchId; + + @JsonProperty("branch_name") + private String branchName; /** * Default constructor for Jackson. @@ -34,38 +51,111 @@ public class Tool { public Tool() { } + /** + * Returns the tool's ID. + * + * @return the id + */ public String getId() { return id; } + /** + * Returns the tool's name. + * + * @return the name + */ public String getName() { return name; } + /** + * Returns what the tool does and when to use it. + * + * @return the description + */ public String getDescription() { return description; } - public Map getSchema() { - return schema; + /** + * Returns the tool's input parameters. + * + * @return the parameters + */ + public List getParameters() { + return parameters; + } + + /** + * Returns conditional groups of parameters. + * + * @return the parameter sets + */ + public List getParameterSets() { + return parameterSets; + } + + /** + * Returns the HTTP request that runs the tool, if it runs over HTTP. + * + * @return the http + */ + public HTTPDefinition getHttp() { + return http; + } + + /** + * Returns the webhook that runs the tool, if it runs through a webhook. + * + * @return the webhook + */ + public ToolWebhookDefinition getWebhook() { + return webhook; + } + + /** + * Returns the asynchronous configuration, if the tool runs asynchronously. + * + * @return the async + */ + public ToolAsyncDefinition getAsync() { + return async; } - public Instant getCreated() { - return created; + /** + * Returns the MCP server configuration, if the tool runs on an MCP server. + * + * @return the mcp + */ + public ToolMcpDefinition getMcp() { + return mcp; + } + + /** + * Returns whether the tool is still a draft. + * + * @return the draft + */ + public Boolean getDraft() { + return draft; } - public Instant getUpdated() { - return updated; + /** + * Returns the ID of the branch the tool was created on. + * + * @return the branch id + */ + public String getBranchId() { + return branchId; } - @Override - public String toString() { - return "Tool{" + - "id='" + id + '\'' + - ", name='" + name + '\'' + - ", description='" + description + '\'' + - ", created=" + created + - ", updated=" + updated + - '}'; + /** + * Returns the name of the branch the tool was created on. + * + * @return the branch name + */ + public String getBranchName() { + return branchName; } } diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ToolAsyncDefinition.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ToolAsyncDefinition.java new file mode 100644 index 0000000..d6f0f67 --- /dev/null +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ToolAsyncDefinition.java @@ -0,0 +1,101 @@ +package ai.gradientlabs.client.model; + +import ai.gradientlabs.client.internal.NanosDurationDeserializer; +import ai.gradientlabs.client.internal.NanosDurationSerializer; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.annotation.JsonDeserialize; +import com.fasterxml.jackson.databind.annotation.JsonSerialize; + +import java.time.Duration; + +/** + * Configuration for running a tool asynchronously. + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public class ToolAsyncDefinition { + + @JsonProperty("start_execution_tool") + private ToolExecutionDefinition startExecutionTool; + + @JsonProperty("cancel_execution_tool") + private ToolExecutionDefinition cancelExecutionTool; + + @JsonSerialize(using = NanosDurationSerializer.class) + @JsonDeserialize(using = NanosDurationDeserializer.class) + @JsonProperty("timeout") + private Duration timeout; + + /** + * Default constructor for Jackson. + */ + public ToolAsyncDefinition() { + } + + /** + * Creates a new instance. + * + * @param startExecutionTool how the operation is started. + * @param cancelExecutionTool how the operation is cancelled, or null if it cannot be. + * @param timeout the longest to wait for the operation to finish. + */ + public ToolAsyncDefinition(ToolExecutionDefinition startExecutionTool, ToolExecutionDefinition cancelExecutionTool, Duration timeout) { + this.startExecutionTool = startExecutionTool; + this.cancelExecutionTool = cancelExecutionTool; + this.timeout = timeout; + } + + /** + * Returns how the operation is started. + * + * @return the start execution tool + */ + public ToolExecutionDefinition getStartExecutionTool() { + return startExecutionTool; + } + + /** + * Sets how the operation is started. + * + * @param startExecutionTool the start execution tool + */ + public void setStartExecutionTool(ToolExecutionDefinition startExecutionTool) { + this.startExecutionTool = startExecutionTool; + } + + /** + * Returns how the operation is cancelled, or null if it cannot be. + * + * @return the cancel execution tool + */ + public ToolExecutionDefinition getCancelExecutionTool() { + return cancelExecutionTool; + } + + /** + * Sets how the operation is cancelled, or null if it cannot be. + * + * @param cancelExecutionTool the cancel execution tool + */ + public void setCancelExecutionTool(ToolExecutionDefinition cancelExecutionTool) { + this.cancelExecutionTool = cancelExecutionTool; + } + + /** + * Returns the longest to wait for the operation to finish. + * + * @return the timeout + */ + public Duration getTimeout() { + return timeout; + } + + /** + * Sets the longest to wait for the operation to finish. + * + * @param timeout the timeout + */ + public void setTimeout(Duration timeout) { + this.timeout = timeout; + } +} diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ToolExecutionDefinition.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ToolExecutionDefinition.java new file mode 100644 index 0000000..26d0274 --- /dev/null +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ToolExecutionDefinition.java @@ -0,0 +1,70 @@ +package ai.gradientlabs.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * How one step of an asynchronous tool runs. Set exactly one of the fields. + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public class ToolExecutionDefinition { + + @JsonProperty("http") + private HTTPDefinition http; + + @JsonProperty("webhook") + private ToolWebhookDefinition webhook; + + /** + * Default constructor for Jackson. + */ + public ToolExecutionDefinition() { + } + + /** + * Creates a new instance. + * + * @param http the HTTP request that runs the step. + * @param webhook the webhook that runs the step. + */ + public ToolExecutionDefinition(HTTPDefinition http, ToolWebhookDefinition webhook) { + this.http = http; + this.webhook = webhook; + } + + /** + * Returns the HTTP request that runs the step. + * + * @return the http + */ + public HTTPDefinition getHttp() { + return http; + } + + /** + * Sets the HTTP request that runs the step. + * + * @param http the http + */ + public void setHttp(HTTPDefinition http) { + this.http = http; + } + + /** + * Returns the webhook that runs the step. + * + * @return the webhook + */ + public ToolWebhookDefinition getWebhook() { + return webhook; + } + + /** + * Sets the webhook that runs the step. + * + * @param webhook the webhook + */ + public void setWebhook(ToolWebhookDefinition webhook) { + this.webhook = webhook; + } +} diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ToolMcpDefinition.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ToolMcpDefinition.java new file mode 100644 index 0000000..c1c0c09 --- /dev/null +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ToolMcpDefinition.java @@ -0,0 +1,39 @@ +package ai.gradientlabs.client.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Runs a tool on a Model Context Protocol (MCP) server. Only returned when reading tools. + */ +public class ToolMcpDefinition { + + @JsonProperty("server_id") + private String serverId; + + @JsonProperty("external_tool_name") + private String externalToolName; + + /** + * Default constructor for Jackson. + */ + public ToolMcpDefinition() { + } + + /** + * Returns the ID of the MCP server. + * + * @return the server id + */ + public String getServerId() { + return serverId; + } + + /** + * Returns the name of the tool on the MCP server. + * + * @return the external tool name + */ + public String getExternalToolName() { + return externalToolName; + } +} diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ToolParameter.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ToolParameter.java new file mode 100644 index 0000000..78b7cc4 --- /dev/null +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ToolParameter.java @@ -0,0 +1,166 @@ +package ai.gradientlabs.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.List; + +/** + * An input parameter of a tool. + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public class ToolParameter { + + @JsonProperty("name") + private String name; + + @JsonProperty("description") + private String description; + + @JsonProperty("type") + private ToolParameterType type; + + @JsonProperty("required") + private Boolean required; + + @JsonProperty("options") + private List options; + + @JsonProperty("allowed_sources") + private List allowedSources; + + @JsonProperty("transfer_mode") + private AttachmentTransferMode transferMode; + + /** + * Default constructor for Jackson. + */ + public ToolParameter() { + } + + /** + * Returns the parameter name. + * + * @return the name + */ + public String getName() { + return name; + } + + /** + * Sets the parameter name. + * + * @param name the name + */ + public void setName(String name) { + this.name = name; + } + + /** + * Returns what the parameter is for. + * + * @return the description + */ + public String getDescription() { + return description; + } + + /** + * Sets what the parameter is for. + * + * @param description the description + */ + public void setDescription(String description) { + this.description = description; + } + + /** + * Returns the parameter type. + * + * @return the type + */ + public ToolParameterType getType() { + return type; + } + + /** + * Sets the parameter type. + * + * @param type the type + */ + public void setType(ToolParameterType type) { + this.type = type; + } + + /** + * Returns whether the parameter is required. + * + * @return the required + */ + public Boolean getRequired() { + return required; + } + + /** + * Sets whether the parameter is required. + * + * @param required the required + */ + public void setRequired(Boolean required) { + this.required = required; + } + + /** + * Returns the allowed values, or null if any value is allowed. + * + * @return the options + */ + public List getOptions() { + return options; + } + + /** + * Sets the allowed values, or null if any value is allowed. + * + * @param options the options + */ + public void setOptions(List options) { + this.options = options; + } + + /** + * Returns where the parameter value may come from. + * + * @return the allowed sources + */ + public List getAllowedSources() { + return allowedSources; + } + + /** + * Sets where the parameter value may come from. + * + * @param allowedSources the allowed sources + */ + public void setAllowedSources(List allowedSources) { + this.allowedSources = allowedSources; + } + + /** + * Returns how an attachment parameter is sent to the tool. + * + * @return the transfer mode + */ + public AttachmentTransferMode getTransferMode() { + return transferMode; + } + + /** + * Sets how an attachment parameter is sent to the tool. + * + * @param transferMode the transfer mode + */ + public void setTransferMode(AttachmentTransferMode transferMode) { + this.transferMode = transferMode; + } +} diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ToolParameterOption.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ToolParameterOption.java new file mode 100644 index 0000000..bb8caf8 --- /dev/null +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ToolParameterOption.java @@ -0,0 +1,70 @@ +package ai.gradientlabs.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * One allowed value for a tool parameter. + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public class ToolParameterOption { + + @JsonProperty("value") + private String value; + + @JsonProperty("text") + private String text; + + /** + * Default constructor for Jackson. + */ + public ToolParameterOption() { + } + + /** + * Creates a new instance. + * + * @param value the value passed to the tool. + * @param text the text the AI agent sees for this option. + */ + public ToolParameterOption(String value, String text) { + this.value = value; + this.text = text; + } + + /** + * Returns the value passed to the tool. + * + * @return the value + */ + public String getValue() { + return value; + } + + /** + * Sets the value passed to the tool. + * + * @param value the value + */ + public void setValue(String value) { + this.value = value; + } + + /** + * Returns the text the AI agent sees for this option. + * + * @return the text + */ + public String getText() { + return text; + } + + /** + * Sets the text the AI agent sees for this option. + * + * @param text the text + */ + public void setText(String text) { + this.text = text; + } +} diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ToolParameterSet.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ToolParameterSet.java new file mode 100644 index 0000000..821941b --- /dev/null +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ToolParameterSet.java @@ -0,0 +1,95 @@ +package ai.gradientlabs.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.List; + +/** + * A group of parameters that applies when a discriminator parameter has a given value. + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public class ToolParameterSet { + + @JsonProperty("discriminator_parameter_name") + private String discriminatorParameterName; + + @JsonProperty("discriminator_value") + private String discriminatorValue; + + @JsonProperty("parameters") + private List parameters; + + /** + * Default constructor for Jackson. + */ + public ToolParameterSet() { + } + + /** + * Creates a new instance. + * + * @param discriminatorParameterName the name of the discriminator parameter. + * @param discriminatorValue the discriminator value that activates this set. + * @param parameters the parameters in this set. + */ + public ToolParameterSet(String discriminatorParameterName, String discriminatorValue, List parameters) { + this.discriminatorParameterName = discriminatorParameterName; + this.discriminatorValue = discriminatorValue; + this.parameters = parameters; + } + + /** + * Returns the name of the discriminator parameter. + * + * @return the discriminator parameter name + */ + public String getDiscriminatorParameterName() { + return discriminatorParameterName; + } + + /** + * Sets the name of the discriminator parameter. + * + * @param discriminatorParameterName the discriminator parameter name + */ + public void setDiscriminatorParameterName(String discriminatorParameterName) { + this.discriminatorParameterName = discriminatorParameterName; + } + + /** + * Returns the discriminator value that activates this set. + * + * @return the discriminator value + */ + public String getDiscriminatorValue() { + return discriminatorValue; + } + + /** + * Sets the discriminator value that activates this set. + * + * @param discriminatorValue the discriminator value + */ + public void setDiscriminatorValue(String discriminatorValue) { + this.discriminatorValue = discriminatorValue; + } + + /** + * Returns the parameters in this set. + * + * @return the parameters + */ + public List getParameters() { + return parameters; + } + + /** + * Sets the parameters in this set. + * + * @param parameters the parameters + */ + public void setParameters(List parameters) { + this.parameters = parameters; + } +} diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ToolParameterSource.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ToolParameterSource.java new file mode 100644 index 0000000..cb9ffdc --- /dev/null +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ToolParameterSource.java @@ -0,0 +1,39 @@ +package ai.gradientlabs.client.model; + +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Where the value of a tool parameter may come from. + */ +public enum ToolParameterSource { + /** + * The AI agent chooses the value. + */ + LLM("llm"), + + /** + * A fixed value set in a procedure. + */ + LITERAL("literal"), + + /** + * A value read from a resource. + */ + RESOURCE("resource"); + + private final String value; + + ToolParameterSource(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return value; + } +} diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ToolParameterType.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ToolParameterType.java new file mode 100644 index 0000000..267096a --- /dev/null +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ToolParameterType.java @@ -0,0 +1,74 @@ +package ai.gradientlabs.client.model; + +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * The type of a tool parameter. + */ +public enum ToolParameterType { + /** + * A string. + */ + STRING("string"), + + /** + * A list of strings. + */ + STRING_ARRAY("string_array"), + + /** + * A JSON value. + */ + JSON("json"), + + /** + * A whole number. + */ + INTEGER("integer"), + + /** + * A decimal number. + */ + FLOAT("float"), + + /** + * True or false. + */ + BOOLEAN("boolean"), + + /** + * A date. + */ + DATE("date"), + + /** + * A date and time. + */ + TIMESTAMP("timestamp"), + + /** + * A duration. + */ + DURATION("duration"), + + /** + * A file attached to the conversation. + */ + ATTACHMENT("attachment"); + + private final String value; + + ToolParameterType(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return value; + } +} diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ToolWebhookDefinition.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ToolWebhookDefinition.java new file mode 100644 index 0000000..a48ed20 --- /dev/null +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ToolWebhookDefinition.java @@ -0,0 +1,47 @@ +package ai.gradientlabs.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Runs a tool by sending an {@code action.execute} webhook. + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public class ToolWebhookDefinition { + + @JsonProperty("name") + private String name; + + /** + * Default constructor for Jackson. + */ + public ToolWebhookDefinition() { + } + + /** + * Creates a new instance. + * + * @param name the action name sent in the webhook. + */ + public ToolWebhookDefinition(String name) { + this.name = name; + } + + /** + * Returns the action name sent in the webhook. + * + * @return the name + */ + public String getName() { + return name; + } + + /** + * Sets the action name sent in the webhook. + * + * @param name the name + */ + public void setName(String name) { + this.name = name; + } +} diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ToolsListResponse.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ToolsListResponse.java new file mode 100644 index 0000000..8cc11d2 --- /dev/null +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/ToolsListResponse.java @@ -0,0 +1,29 @@ +package ai.gradientlabs.client.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.List; + +/** + * The response from listing tools. + */ +public class ToolsListResponse { + + @JsonProperty("tools") + private List tools; + + /** + * Default constructor for Jackson. + */ + public ToolsListResponse() { + } + + /** + * Returns the tools. + * + * @return the tools + */ + public List getTools() { + return tools; + } +} diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/Topic.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/Topic.java index 49fd5da..61a591e 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/Topic.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/Topic.java @@ -9,37 +9,37 @@ */ public class Topic { - @JsonProperty("source") + @JsonProperty("Source") private String source; - @JsonProperty("external_id") + @JsonProperty("ExternalID") private String externalId; - @JsonProperty("name") + @JsonProperty("Name") private String name; - @JsonProperty("description") + @JsonProperty("Description") private String description; - @JsonProperty("visibility") + @JsonProperty("Visibility") private Visibility visibility; - @JsonProperty("parent_external_id") + @JsonProperty("ParentExternalID") private String parentExternalId; - @JsonProperty("created") + @JsonProperty("Created") private Instant created; - @JsonProperty("last_edited") + @JsonProperty("LastEdited") private Instant lastEdited; - @JsonProperty("last_seen") + @JsonProperty("LastSeen") private Instant lastSeen; - @JsonProperty("data") - private Object data; + @JsonProperty("Data") + private byte[] data; - @JsonProperty("public_url") + @JsonProperty("PublicURL") private String publicUrl; /** @@ -130,11 +130,11 @@ public Instant getLastSeen() { } /** - * Returns a raw representation of the topic from the support platform. + * Returns the topic as the support platform represents it (decoded from base64). * - * @return the data object + * @return the raw topic bytes */ - public Object getData() { + public byte[] getData() { return data; } diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/TrafficGroup.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/TrafficGroup.java index ae9f0d0..1f98bd9 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/TrafficGroup.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/TrafficGroup.java @@ -21,6 +21,9 @@ public class TrafficGroup { @JsonProperty("targets") private List targets; + @JsonProperty("excluded_targets") + private List excludedTargets; + /** * Default constructor for Jackson. */ @@ -54,6 +57,15 @@ public List getTargets() { return targets; } + /** + * Returns the targets excluded from this traffic group. + * + * @return the excluded targets + */ + public List getExcludedTargets() { + return excludedTargets; + } + @Override public String toString() { return "TrafficGroup{" + diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/Visibility.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/Visibility.java index 5109bfd..3ca7873 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/Visibility.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/Visibility.java @@ -3,26 +3,28 @@ import com.fasterxml.jackson.annotation.JsonValue; /** - * Describes who can view the given item (e.g., help article or topic). + * Who can see an article or topic. */ public enum Visibility { /** - * The item is available to the general public. - * For example, it is published on a public website. + * Anyone can see it. */ PUBLIC("public"), /** - * The item is only available to the company's customers. - * For example, it is only accessible via an app after sign-up. + * Only signed-in users can see it. */ USERS("users"), /** - * The item is only available to the company's employees. - * For example, it is a procedure or SOP that customers do not have access to. + * Only your staff can see it. */ - INTERNAL("internal"); + INTERNAL("internal"), + + /** + * The support platform did not say. Only returned when reading topics. + */ + UNKNOWN("unknown"); private final String value; diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/VoiceCallContext.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/VoiceCallContext.java index 4f06bf0..8342ec3 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/VoiceCallContext.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/VoiceCallContext.java @@ -30,6 +30,9 @@ public class VoiceCallContext { @JsonProperty("gradient_labs_url") private String gradientLabsUrl; + @JsonProperty("live_handoff_url") + private String liveHandoffUrl; + public Instant getStartedAt() { return startedAt; } @@ -57,4 +60,13 @@ public String getLastExecutedProcedureUrl() { public String getGradientLabsUrl() { return gradientLabsUrl; } + + /** + * Returns the URL of the live hand-off view for the call. + * + * @return the live handoff url + */ + public String getLiveHandoffUrl() { + return liveHandoffUrl; + } } diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/WorkspaceFile.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/WorkspaceFile.java new file mode 100644 index 0000000..c678690 --- /dev/null +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/model/WorkspaceFile.java @@ -0,0 +1,89 @@ +package ai.gradientlabs.client.model; + +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.time.Instant; + +/** + * A file uploaded to your workspace. + */ +public class WorkspaceFile { + + @JsonProperty("id") + private String id; + + @JsonProperty("file_name") + private String fileName; + + @JsonProperty("content_type") + private String contentType; + + @JsonProperty("size_bytes") + private Long sizeBytes; + + @JsonProperty("ref") + private String ref; + + @JsonProperty("created") + private Instant created; + + /** + * Default constructor for Jackson. + */ + public WorkspaceFile() { + } + + /** + * Returns the file's ID. + * + * @return the id + */ + public String getId() { + return id; + } + + /** + * Returns the file's name. + * + * @return the file name + */ + public String getFileName() { + return fileName; + } + + /** + * Returns the file's content type. + * + * @return the content type + */ + public String getContentType() { + return contentType; + } + + /** + * Returns the file's size in bytes. + * + * @return the size bytes + */ + public Long getSizeBytes() { + return sizeBytes; + } + + /** + * Returns the reference used to point to this file from procedures and tools. + * + * @return the ref + */ + public String getRef() { + return ref; + } + + /** + * Returns when the file was created. + * + * @return the created + */ + public Instant getCreated() { + return created; + } +} diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/AddMessageRequest.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/AddMessageRequest.java index c1ede07..b84b60b 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/AddMessageRequest.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/AddMessageRequest.java @@ -7,9 +7,7 @@ import java.time.Instant; import java.util.ArrayList; -import java.util.HashMap; import java.util.List; -import java.util.Map; /** * Parameters for adding a message to a conversation. @@ -32,19 +30,23 @@ public class AddMessageRequest { @JsonProperty("created") private final Instant created; - @JsonProperty("metadata") - private final Map metadata; - @JsonProperty("attachments") private final List attachments; + @JsonProperty("conversation_token") + private final String conversationToken; + + @JsonProperty("subject") + private final String subject; + private AddMessageRequest(Builder builder) { + this.conversationToken = builder.conversationToken; + this.subject = builder.subject; this.id = builder.id; this.body = builder.body; this.participantId = builder.participantId; this.participantType = builder.participantType; this.created = builder.created; - this.metadata = builder.metadata; this.attachments = builder.attachments; } @@ -52,13 +54,32 @@ public static Builder builder() { return new Builder(); } + /** + * Returns the conversation token, if your support platform uses one. + * + * @return the conversation token + */ + public String getConversationToken() { + return conversationToken; + } + + /** + * Returns the message subject, for emails. + * + * @return the subject + */ + public String getSubject() { + return subject; + } + public static class Builder { + private String conversationToken; + private String subject; private String id; private String body; private String participantId; private ParticipantType participantType; private Instant created; - private Map metadata; private List attachments; private Builder() { @@ -89,19 +110,6 @@ public Builder created(Instant created) { return this; } - public Builder metadata(Map metadata) { - this.metadata = metadata; - return this; - } - - public Builder addMetadata(String key, Object value) { - if (this.metadata == null) { - this.metadata = new HashMap<>(); - } - this.metadata.put(key, value); - return this; - } - public Builder attachments(List attachments) { this.attachments = attachments; return this; @@ -115,14 +123,34 @@ public Builder addAttachment(Attachment attachment) { return this; } + /** + * Sets the conversation token, if your support platform uses one. + * + * @param conversationToken the conversation token + * @return this builder + */ + public Builder conversationToken(String conversationToken) { + this.conversationToken = conversationToken; + return this; + } + + /** + * Sets the message subject, for emails. + * + * @param subject the subject + * @return this builder + */ + public Builder subject(String subject) { + this.subject = subject; + return this; + } + public AddMessageRequest build() { if (id == null || id.isBlank()) { throw new IllegalStateException("id is required"); } - if (body == null || body.isBlank()) { - throw new IllegalStateException("body is required"); - } - if (participantId == null || participantId.isBlank()) { + if ((participantType != ParticipantType.AI_AGENT || (body != null && !body.isEmpty())) + && (participantId == null || participantId.isBlank())) { throw new IllegalStateException("participantId is required"); } if (participantType == null) { diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/AssignmentRequest.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/AssignmentRequest.java index e307462..8d68e0d 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/AssignmentRequest.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/AssignmentRequest.java @@ -4,6 +4,8 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import java.time.Instant; + /** * Parameters for assigning a conversation to a participant. */ @@ -16,7 +18,15 @@ public class AssignmentRequest { @JsonProperty("assignee_type") private final ParticipantType assigneeType; + @JsonProperty("reason") + private final String reason; + + @JsonProperty("timestamp") + private final Instant timestamp; + private AssignmentRequest(Builder builder) { + this.reason = builder.reason; + this.timestamp = builder.timestamp; this.assigneeId = builder.assigneeId; this.assigneeType = builder.assigneeType; } @@ -33,7 +43,27 @@ public ParticipantType getAssigneeType() { return assigneeType; } + /** + * Returns why the conversation is being assigned. + * + * @return the reason + */ + public String getReason() { + return reason; + } + + /** + * Returns when the assignment happened. Defaults to now. + * + * @return the timestamp + */ + public Instant getTimestamp() { + return timestamp; + } + public static class Builder { + private String reason; + private Instant timestamp; private String assigneeId; private ParticipantType assigneeType; @@ -50,6 +80,28 @@ public Builder assigneeType(ParticipantType assigneeType) { return this; } + /** + * Sets why the conversation is being assigned. + * + * @param reason the reason + * @return this builder + */ + public Builder reason(String reason) { + this.reason = reason; + return this; + } + + /** + * Sets when the assignment happened. Defaults to now. + * + * @param timestamp the timestamp + * @return this builder + */ + public Builder timestamp(Instant timestamp) { + this.timestamp = timestamp; + return this; + } + public AssignmentRequest build() { return new AssignmentRequest(this); } diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/BatchCreateCustomerMemoriesRequest.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/BatchCreateCustomerMemoriesRequest.java new file mode 100644 index 0000000..23c479b --- /dev/null +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/BatchCreateCustomerMemoriesRequest.java @@ -0,0 +1,65 @@ +package ai.gradientlabs.client.request; + +import ai.gradientlabs.client.model.Memory; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.List; + +/** + * Parameters for batch-creating a set of memories scoped to a customer. + *

+ * The batch is created asynchronously: the call is accepted and returns nothing. + * + * @deprecated use {@link BatchCreateCustomerMemoriesV2Request}, which also takes a category description + */ +@Deprecated +@JsonInclude(JsonInclude.Include.NON_NULL) +public class BatchCreateCustomerMemoriesRequest { + + @JsonProperty("memories") + private final List memories; + + private BatchCreateCustomerMemoriesRequest(Builder builder) { + this.memories = builder.memories; + } + + public static Builder builder() { + return new Builder(); + } + + public List getMemories() { + return memories; + } + + public static class Builder { + private List memories; + + private Builder() { + } + + /** + * Sets the batch of memories to create (required, non-empty). + * + * @param memories the memories to create + * @return this builder + */ + public Builder memories(List memories) { + this.memories = memories; + return this; + } + + /** + * Builds the request. + * + * @return a new request instance + * @throws IllegalStateException if required fields are missing + */ + public BatchCreateCustomerMemoriesRequest build() { + if (memories == null || memories.isEmpty()) { + throw new IllegalStateException("memories is required and cannot be empty"); + } + return new BatchCreateCustomerMemoriesRequest(this); + } + } +} diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/BatchCreateCustomerMemoriesV2Request.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/BatchCreateCustomerMemoriesV2Request.java new file mode 100644 index 0000000..a71b868 --- /dev/null +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/BatchCreateCustomerMemoriesV2Request.java @@ -0,0 +1,73 @@ +package ai.gradientlabs.client.request; + +import ai.gradientlabs.client.model.CustomerMemory; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.List; + +/** + * Parameters for batch-creating memories scoped to a customer. + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public class BatchCreateCustomerMemoriesV2Request { + + @JsonProperty("memories") + private final List memories; + + private BatchCreateCustomerMemoriesV2Request(Builder builder) { + this.memories = builder.memories; + } + + /** + * Returns a new builder. + * + * @return a new builder + */ + public static Builder builder() { + return new Builder(); + } + + /** + * Returns the memories to create, at least one. + * + * @return the memories + */ + public List getMemories() { + return memories; + } + + /** + * Builder for {@link BatchCreateCustomerMemoriesV2Request}. + */ + public static class Builder { + private List memories; + + private Builder() { + } + + /** + * Sets the memories to create, at least one. Required. + * + * @param memories the memories + * @return this builder + */ + public Builder memories(List memories) { + this.memories = memories; + return this; + } + + /** + * Builds the request. + * + * @return the request + * @throws IllegalStateException if a required field is missing + */ + public BatchCreateCustomerMemoriesV2Request build() { + if (memories == null || memories.isEmpty()) { + throw new IllegalStateException("memories is required"); + } + return new BatchCreateCustomerMemoriesV2Request(this); + } + } +} diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/BeginFileUploadRequest.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/BeginFileUploadRequest.java new file mode 100644 index 0000000..34aaffd --- /dev/null +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/BeginFileUploadRequest.java @@ -0,0 +1,67 @@ +package ai.gradientlabs.client.request; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Parameters for starting a file upload. + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public class BeginFileUploadRequest { + + @JsonProperty("content_type") + private final String contentType; + + private BeginFileUploadRequest(Builder builder) { + this.contentType = builder.contentType; + } + + /** + * Returns a new builder. + * + * @return a new builder + */ + public static Builder builder() { + return new Builder(); + } + + /** + * Returns the content type of the file to upload. + * + * @return the content type + */ + public String getContentType() { + return contentType; + } + + /** + * Builder for {@link BeginFileUploadRequest}. + */ + public static class Builder { + private String contentType; + + private Builder() { + } + + /** + * Sets the content type of the file to upload. + * + * @param contentType the content type + * @return this builder + */ + public Builder contentType(String contentType) { + this.contentType = contentType; + return this; + } + + /** + * Builds the request. + * + * @return the request + * @throws IllegalStateException if a required field is missing + */ + public BeginFileUploadRequest build() { + return new BeginFileUploadRequest(this); + } + } +} diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/CreateBackOfficeTaskRequest.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/CreateBackOfficeTaskRequest.java index 420570b..56e6857 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/CreateBackOfficeTaskRequest.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/CreateBackOfficeTaskRequest.java @@ -2,6 +2,7 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.node.NullNode; import java.time.Instant; import java.util.ArrayList; @@ -27,7 +28,7 @@ public class CreateBackOfficeTaskRequest { private final String procedureId; @JsonProperty("input") - private final Map input; + private final Object input; @JsonProperty("created") private final Instant created; @@ -65,7 +66,7 @@ public static class Attachment { @JsonProperty("url") private final String url; - @JsonProperty("base64_contents") + @JsonProperty("base_64_contents") private final String base64Contents; private Attachment(String fileName, String url, String base64Contents) { @@ -112,7 +113,7 @@ public String getProcedureId() { return procedureId; } - public Map getInput() { + public Object getInput() { return input; } @@ -132,7 +133,7 @@ public static class Builder { private String id; private String agentId; private String procedureId; - private Map input; + private Object input; private Instant created; private Map metadata; private List attachments; @@ -183,8 +184,8 @@ public Builder procedureId(String procedureId) { * @param input the task input * @return this builder */ - public Builder input(Map input) { - this.input = input; + public Builder input(Object input) { + this.input = input == null ? NullNode.getInstance() : input; return this; } diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/CreateFileRequest.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/CreateFileRequest.java new file mode 100644 index 0000000..f1016d0 --- /dev/null +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/CreateFileRequest.java @@ -0,0 +1,123 @@ +package ai.gradientlabs.client.request; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Parameters for turning a finished upload into a workspace file. + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public class CreateFileRequest { + + @JsonProperty("upload_id") + private final String uploadId; + + @JsonProperty("file_name") + private final String fileName; + + @JsonProperty("ref") + private final String ref; + + private CreateFileRequest(Builder builder) { + this.uploadId = builder.uploadId; + this.fileName = builder.fileName; + this.ref = builder.ref; + } + + /** + * Returns a new builder. + * + * @return a new builder + */ + public static Builder builder() { + return new Builder(); + } + + /** + * Returns the ID returned by {@code beginFileUpload}. + * + * @return the upload id + */ + public String getUploadId() { + return uploadId; + } + + /** + * Returns the file's name. + * + * @return the file name + */ + public String getFileName() { + return fileName; + } + + /** + * Returns the reference to point to this file from procedures and tools. + * + * @return the ref + */ + public String getRef() { + return ref; + } + + /** + * Builder for {@link CreateFileRequest}. + */ + public static class Builder { + private String uploadId; + private String fileName; + private String ref; + + private Builder() { + } + + /** + * Sets the ID returned by {@code beginFileUpload}. Required. + * + * @param uploadId the upload id + * @return this builder + */ + public Builder uploadId(String uploadId) { + this.uploadId = uploadId; + return this; + } + + /** + * Sets the file's name. Required. + * + * @param fileName the file name + * @return this builder + */ + public Builder fileName(String fileName) { + this.fileName = fileName; + return this; + } + + /** + * Sets the reference to point to this file from procedures and tools. + * + * @param ref the ref + * @return this builder + */ + public Builder ref(String ref) { + this.ref = ref; + return this; + } + + /** + * Builds the request. + * + * @return the request + * @throws IllegalStateException if a required field is missing + */ + public CreateFileRequest build() { + if (uploadId == null || uploadId.isBlank()) { + throw new IllegalStateException("uploadId is required"); + } + if (fileName == null || fileName.isBlank()) { + throw new IllegalStateException("fileName is required"); + } + return new CreateFileRequest(this); + } + } +} diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/CreateKnowledgeBaseRequest.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/CreateKnowledgeBaseRequest.java new file mode 100644 index 0000000..bc70fca --- /dev/null +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/CreateKnowledgeBaseRequest.java @@ -0,0 +1,98 @@ +package ai.gradientlabs.client.request; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Parameters for creating a knowledge base. + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public class CreateKnowledgeBaseRequest { + + @JsonProperty("id") + private final String id; + + @JsonProperty("name") + private final String name; + + private CreateKnowledgeBaseRequest(Builder builder) { + this.id = builder.id; + this.name = builder.name; + } + + /** + * Returns a new builder. + * + * @return a new builder + */ + public static Builder builder() { + return new Builder(); + } + + /** + * Returns your identifier for the knowledge base. + * + * @return the id + */ + public String getId() { + return id; + } + + /** + * Returns the knowledge base's name. + * + * @return the name + */ + public String getName() { + return name; + } + + /** + * Builder for {@link CreateKnowledgeBaseRequest}. + */ + public static class Builder { + private String id; + private String name; + + private Builder() { + } + + /** + * Sets your identifier for the knowledge base. Required. + * + * @param id the id + * @return this builder + */ + public Builder id(String id) { + this.id = id; + return this; + } + + /** + * Sets the knowledge base's name. Required. + * + * @param name the name + * @return this builder + */ + public Builder name(String name) { + this.name = name; + return this; + } + + /** + * Builds the request. + * + * @return the request + * @throws IllegalStateException if a required field is missing + */ + public CreateKnowledgeBaseRequest build() { + if (id == null || id.isBlank()) { + throw new IllegalStateException("id is required"); + } + if (name == null || name.isBlank()) { + throw new IllegalStateException("name is required"); + } + return new CreateKnowledgeBaseRequest(this); + } + } +} diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/CreateNoteRequest.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/CreateNoteRequest.java index b4d996d..561dcab 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/CreateNoteRequest.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/CreateNoteRequest.java @@ -3,6 +3,8 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.Map; +import java.util.List; import java.time.Instant; /** @@ -29,7 +31,15 @@ public class CreateNoteRequest { @JsonProperty("end_time") private final Instant endTime; + @JsonProperty("attributes") + private final Map> attributes; + + @JsonProperty("knowledge_base_ids") + private final List knowledgeBaseIds; + private CreateNoteRequest(Builder builder) { + this.attributes = builder.attributes; + this.knowledgeBaseIds = builder.knowledgeBaseIds; this.id = builder.id; this.title = builder.title; this.body = builder.body; @@ -66,7 +76,27 @@ public Instant getEndTime() { return endTime; } + /** + * Returns the note's attributes, by attribute name. + * + * @return the attributes + */ + public Map> getAttributes() { + return attributes; + } + + /** + * Returns your IDs of the knowledge bases the note belongs to. + * + * @return the knowledge base ids + */ + public List getKnowledgeBaseIds() { + return knowledgeBaseIds; + } + public static class Builder { + private Map> attributes; + private List knowledgeBaseIds; private String id; private String title; private String body; @@ -149,6 +179,28 @@ public Builder endTime(Instant endTime) { return this; } + /** + * Sets the note's attributes, by attribute name. + * + * @param attributes the attributes + * @return this builder + */ + public Builder attributes(Map> attributes) { + this.attributes = attributes; + return this; + } + + /** + * Sets your IDs of the knowledge bases the note belongs to. + * + * @param knowledgeBaseIds the knowledge base ids + * @return this builder + */ + public Builder knowledgeBaseIds(List knowledgeBaseIds) { + this.knowledgeBaseIds = knowledgeBaseIds; + return this; + } + /** * Builds the request. * diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/CreateResourceSourceRequest.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/CreateResourceSourceRequest.java index 11cc2ac..facf67f 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/CreateResourceSourceRequest.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/CreateResourceSourceRequest.java @@ -34,7 +34,15 @@ public class CreateResourceSourceRequest { @JsonProperty("attribute_descriptions") private final Map attributeDescriptions; + @JsonProperty("branch_id") + private final String branchId; + + @JsonProperty("branch_name") + private final String branchName; + private CreateResourceSourceRequest(Builder builder) { + this.branchId = builder.branchId; + this.branchName = builder.branchName; this.displayName = builder.displayName; this.sourceType = builder.sourceType; this.description = builder.description; @@ -71,7 +79,27 @@ public Map getAttributeDescriptions() { return attributeDescriptions; } + /** + * Returns the ID of the branch to create the resource source on. + * + * @return the branch id + */ + public String getBranchId() { + return branchId; + } + + /** + * Returns the git name of the branch to create the resource source on. + * + * @return the branch name + */ + public String getBranchName() { + return branchName; + } + public static class Builder { + private String branchId; + private String branchName; private String displayName; private SourceType sourceType; private String description; @@ -148,6 +176,28 @@ public Builder attributeDescriptions(Map attributeDescriptions) return this; } + /** + * Sets the ID of the branch to create the resource source on. + * + * @param branchId the branch id + * @return this builder + */ + public Builder branchId(String branchId) { + this.branchId = branchId; + return this; + } + + /** + * Sets the git name of the branch to create the resource source on. + * + * @param branchName the branch name + * @return this builder + */ + public Builder branchName(String branchName) { + this.branchName = branchName; + return this; + } + /** * Builds the request. * diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/CreateResourceTypeRequest.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/CreateResourceTypeRequest.java index 2cc9732..9192205 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/CreateResourceTypeRequest.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/CreateResourceTypeRequest.java @@ -32,7 +32,15 @@ public class CreateResourceTypeRequest { @JsonProperty("is_enabled") private final Boolean isEnabled; + @JsonProperty("branch_id") + private final String branchId; + + @JsonProperty("branch_name") + private final String branchName; + private CreateResourceTypeRequest(Builder builder) { + this.branchId = builder.branchId; + this.branchName = builder.branchName; this.displayName = builder.displayName; this.description = builder.description; this.scope = builder.scope; @@ -69,7 +77,27 @@ public Boolean getIsEnabled() { return isEnabled; } + /** + * Returns the ID of the branch to create the resource type on. + * + * @return the branch id + */ + public String getBranchId() { + return branchId; + } + + /** + * Returns the git name of the branch to create the resource type on. + * + * @return the branch name + */ + public String getBranchName() { + return branchName; + } + public static class Builder { + private String branchId; + private String branchName; private String displayName; private String description; private Scope scope; @@ -146,6 +174,28 @@ public Builder isEnabled(Boolean isEnabled) { return this; } + /** + * Sets the ID of the branch to create the resource type on. + * + * @param branchId the branch id + * @return this builder + */ + public Builder branchId(String branchId) { + this.branchId = branchId; + return this; + } + + /** + * Sets the git name of the branch to create the resource type on. + * + * @param branchName the branch name + * @return this builder + */ + public Builder branchName(String branchName) { + this.branchName = branchName; + return this; + } + /** * Builds the request. * diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/CreateToolRequest.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/CreateToolRequest.java index baa0240..f276cab 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/CreateToolRequest.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/CreateToolRequest.java @@ -1,12 +1,20 @@ package ai.gradientlabs.client.request; +import ai.gradientlabs.client.model.HTTPDefinition; +import ai.gradientlabs.client.model.ToolAsyncDefinition; +import ai.gradientlabs.client.model.ToolParameter; +import ai.gradientlabs.client.model.ToolParameterSet; +import ai.gradientlabs.client.model.ToolWebhookDefinition; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; -import java.util.Map; +import java.util.List; /** * Parameters for creating a tool. + *

+ * Set exactly one of {@code http}, {@code webhook} or {@code async}, or set {@code draft} to true and none of them. + * Set {@code branchId} or {@code branchName}: the tool goes live when that branch is merged. */ @JsonInclude(JsonInclude.Include.NON_NULL) public class CreateToolRequest { @@ -17,46 +25,283 @@ public class CreateToolRequest { @JsonProperty("description") private final String description; - @JsonProperty("schema") - private final Map schema; + @JsonProperty("parameters") + private final List parameters; + + @JsonProperty("parameter_sets") + private final List parameterSets; + + @JsonProperty("http") + private final HTTPDefinition http; + + @JsonProperty("webhook") + private final ToolWebhookDefinition webhook; + + @JsonProperty("async") + private final ToolAsyncDefinition async; + + @JsonProperty("draft") + private final Boolean draft; + + @JsonProperty("branch_id") + private final String branchId; + + @JsonProperty("branch_name") + private final String branchName; private CreateToolRequest(Builder builder) { this.name = builder.name; this.description = builder.description; - this.schema = builder.schema; + this.parameters = builder.parameters == null ? List.of() : builder.parameters; + this.parameterSets = builder.parameterSets; + this.http = builder.http; + this.webhook = builder.webhook; + this.async = builder.async; + this.draft = builder.draft; + this.branchId = builder.branchId; + this.branchName = builder.branchName; } + /** + * Returns a new builder. + * + * @return a new builder + */ public static Builder builder() { return new Builder(); } + /** + * Returns the tool's name. + * + * @return the name + */ + public String getName() { + return name; + } + + /** + * Returns what the tool does and when to use it. + * + * @return the description + */ + public String getDescription() { + return description; + } + + /** + * Returns the tool's input parameters. Defaults to none. + * + * @return the parameters + */ + public List getParameters() { + return parameters; + } + + /** + * Returns conditional groups of parameters. + * + * @return the parameter sets + */ + public List getParameterSets() { + return parameterSets; + } + + /** + * Returns the HTTP request that runs the tool. + * + * @return the http + */ + public HTTPDefinition getHttp() { + return http; + } + + /** + * Returns the webhook that runs the tool. + * + * @return the webhook + */ + public ToolWebhookDefinition getWebhook() { + return webhook; + } + + /** + * Returns the asynchronous configuration. + * + * @return the async + */ + public ToolAsyncDefinition getAsync() { + return async; + } + + /** + * Returns whether the tool is still a draft. + * + * @return the draft + */ + public Boolean getDraft() { + return draft; + } + + /** + * Returns the ID of the branch to create the tool on. + * + * @return the branch id + */ + public String getBranchId() { + return branchId; + } + + /** + * Returns the git name of the branch to create the tool on. + * + * @return the branch name + */ + public String getBranchName() { + return branchName; + } + + /** + * Builder for {@link CreateToolRequest}. + */ public static class Builder { private String name; private String description; - private Map schema; + private List parameters; + private List parameterSets; + private HTTPDefinition http; + private ToolWebhookDefinition webhook; + private ToolAsyncDefinition async; + private Boolean draft; + private String branchId; + private String branchName; private Builder() { } + /** + * Sets the tool's name. Required. + * + * @param name the name + * @return this builder + */ public Builder name(String name) { this.name = name; return this; } + /** + * Sets what the tool does and when to use it. Required. + * + * @param description the description + * @return this builder + */ public Builder description(String description) { this.description = description; return this; } - public Builder schema(Map schema) { - this.schema = schema; + /** + * Sets the tool's input parameters. Defaults to none. + * + * @param parameters the parameters + * @return this builder + */ + public Builder parameters(List parameters) { + this.parameters = parameters; + return this; + } + + /** + * Sets conditional groups of parameters. + * + * @param parameterSets the parameter sets + * @return this builder + */ + public Builder parameterSets(List parameterSets) { + this.parameterSets = parameterSets; + return this; + } + + /** + * Sets the HTTP request that runs the tool. + * + * @param http the http + * @return this builder + */ + public Builder http(HTTPDefinition http) { + this.http = http; + return this; + } + + /** + * Sets the webhook that runs the tool. + * + * @param webhook the webhook + * @return this builder + */ + public Builder webhook(ToolWebhookDefinition webhook) { + this.webhook = webhook; + return this; + } + + /** + * Sets the asynchronous configuration. + * + * @param async the async + * @return this builder + */ + public Builder async(ToolAsyncDefinition async) { + this.async = async; + return this; + } + + /** + * Sets whether the tool is still a draft. + * + * @param draft the draft + * @return this builder + */ + public Builder draft(Boolean draft) { + this.draft = draft; + return this; + } + + /** + * Sets the ID of the branch to create the tool on. + * + * @param branchId the branch id + * @return this builder + */ + public Builder branchId(String branchId) { + this.branchId = branchId; + return this; + } + + /** + * Sets the git name of the branch to create the tool on. + * + * @param branchName the branch name + * @return this builder + */ + public Builder branchName(String branchName) { + this.branchName = branchName; return this; } + /** + * Builds the request. + * + * @return the request + * @throws IllegalStateException if a required field is missing + */ public CreateToolRequest build() { if (name == null || name.isBlank()) { throw new IllegalStateException("name is required"); } + if (description == null || description.isBlank()) { + throw new IllegalStateException("description is required"); + } return new CreateToolRequest(this); } } diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/CreateTrafficGroupTargetRequest.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/CreateTrafficGroupTargetRequest.java index adee0ad..b089901 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/CreateTrafficGroupTargetRequest.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/CreateTrafficGroupTargetRequest.java @@ -106,9 +106,6 @@ public Builder targetId(String targetId) { * @throws IllegalStateException if required fields are missing */ public CreateTrafficGroupTargetRequest build() { - if (groupId == null || groupId.isBlank()) { - throw new IllegalStateException("groupId is required"); - } if (targetType == null || targetType.isBlank()) { throw new IllegalStateException("targetType is required"); } diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/EventRequest.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/EventRequest.java index a5b02ab..3548a8f 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/EventRequest.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/EventRequest.java @@ -99,6 +99,9 @@ public EventRequest build() { if (type == null) { throw new IllegalStateException("type is required"); } + if (type == ConversationEventType.INTERNAL_NOTE && (body == null || body.isEmpty())) { + throw new IllegalStateException("body is required for an internal note"); + } if (participantId == null || participantId.isBlank()) { throw new IllegalStateException("participantId is required"); } diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/FinishConversationRequest.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/FinishConversationRequest.java index a06ac92..1f3251c 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/FinishConversationRequest.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/FinishConversationRequest.java @@ -3,6 +3,8 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import java.time.Instant; + /** * Parameters for finishing a conversation. */ @@ -15,7 +17,11 @@ public class FinishConversationRequest { @JsonProperty("reason_code") private final String reasonCode; + @JsonProperty("timestamp") + private final Instant timestamp; + private FinishConversationRequest(Builder builder) { + this.timestamp = builder.timestamp; this.reason = builder.reason; this.reasonCode = builder.reasonCode; } @@ -36,7 +42,17 @@ public String getReasonCode() { return reasonCode; } + /** + * Returns when the conversation finished. Defaults to now. + * + * @return the timestamp + */ + public Instant getTimestamp() { + return timestamp; + } + public static class Builder { + private Instant timestamp; private String reason; private String reasonCode; @@ -53,6 +69,17 @@ public Builder reasonCode(String reasonCode) { return this; } + /** + * Sets when the conversation finished. Defaults to now. + * + * @param timestamp the timestamp + * @return this builder + */ + public Builder timestamp(Instant timestamp) { + this.timestamp = timestamp; + return this; + } + public FinishConversationRequest build() { return new FinishConversationRequest(this); } diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/ReadConversationRequest.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/ReadConversationRequest.java index 1d42982..900a5b7 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/ReadConversationRequest.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/ReadConversationRequest.java @@ -1,19 +1,14 @@ package ai.gradientlabs.client.request; -import com.fasterxml.jackson.annotation.JsonInclude; -import com.fasterxml.jackson.annotation.JsonProperty; - /** - * Parameters for reading a conversation. + * Optional parameters for reading a conversation. */ -@JsonInclude(JsonInclude.Include.NON_NULL) public class ReadConversationRequest { - @JsonProperty("include_messages") - private final Boolean includeMessages; + private final String supportPlatform; private ReadConversationRequest(Builder builder) { - this.includeMessages = builder.includeMessages; + this.supportPlatform = builder.supportPlatform; } public static Builder builder() { @@ -24,18 +19,30 @@ public static ReadConversationRequest empty() { return builder().build(); } - public Boolean getIncludeMessages() { - return includeMessages; + /** + * Returns the support platform the conversation ID belongs to, or null for the public API. + * + * @return the support platform + */ + public String getSupportPlatform() { + return supportPlatform; } public static class Builder { - private Boolean includeMessages; + private String supportPlatform; private Builder() { } - public Builder includeMessages(boolean includeMessages) { - this.includeMessages = includeMessages; + /** + * Reads a conversation by its ID on another support platform, such as {@code intercom}, + * instead of its public API ID. + * + * @param supportPlatform the support platform + * @return this builder + */ + public Builder supportPlatform(String supportPlatform) { + this.supportPlatform = supportPlatform; return this; } diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/ReturnAsyncToolResultRequest.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/ReturnAsyncToolResultRequest.java index c9f3970..b7b194a 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/ReturnAsyncToolResultRequest.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/ReturnAsyncToolResultRequest.java @@ -2,9 +2,9 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.databind.node.NullNode; import java.time.Instant; -import java.util.Map; /** * Parameters for returning an async tool execution result. @@ -23,7 +23,7 @@ public class ReturnAsyncToolResultRequest { private final String asyncToolExecutionId; @JsonProperty("payload") - private final Map payload; + private final Object payload; @JsonProperty("timestamp") private final Instant timestamp; @@ -42,7 +42,7 @@ public String getAsyncToolExecutionId() { return asyncToolExecutionId; } - public Map getPayload() { + public Object getPayload() { return payload; } @@ -52,7 +52,7 @@ public Instant getTimestamp() { public static class Builder { private String asyncToolExecutionId; - private Map payload; + private Object payload; private Instant timestamp; private Builder() { @@ -80,8 +80,8 @@ public Builder asyncToolExecutionId(String asyncToolExecutionId) { * @param payload the result payload * @return this builder */ - public Builder payload(Map payload) { - this.payload = payload; + public Builder payload(Object payload) { + this.payload = payload == null ? NullNode.getInstance() : payload; return this; } diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/StartConversationRequest.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/StartConversationRequest.java index 60f6351..03117f2 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/StartConversationRequest.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/StartConversationRequest.java @@ -33,9 +33,6 @@ public class StartConversationRequest { @JsonProperty("channel") private final Channel channel; - @JsonProperty("metadata") - private final Map metadata; - @JsonProperty("created") private final Instant created; @@ -57,7 +54,6 @@ private StartConversationRequest(Builder builder) { this.assigneeId = builder.assigneeId; this.assigneeType = builder.assigneeType; this.channel = builder.channel; - this.metadata = builder.metadata; this.created = builder.created; this.resources = builder.resources; this.conversationToken = builder.conversationToken; @@ -89,10 +85,6 @@ public Channel getChannel() { return channel; } - public Map getMetadata() { - return metadata; - } - public Instant getCreated() { return created; } @@ -129,7 +121,6 @@ public static class Builder { private String assigneeId; private ParticipantType assigneeType; private Channel channel; - private Map metadata; private Instant created; private Map resources; private String conversationToken; @@ -204,34 +195,6 @@ public Builder channel(Channel channel) { return this; } - /** - * Sets arbitrary metadata (optional). - *

- * This will be passed along with webhooks and can be used as action parameters. - * - * @param metadata the metadata - * @return this builder - */ - public Builder metadata(Map metadata) { - this.metadata = metadata; - return this; - } - - /** - * Adds a single metadata entry. - * - * @param key the metadata key - * @param value the metadata value - * @return this builder - */ - public Builder addMetadata(String key, Object value) { - if (this.metadata == null) { - this.metadata = new HashMap<>(); - } - this.metadata.put(key, value); - return this; - } - /** * Sets when the conversation started (optional). *

diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/ToolExecuteRequest.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/ToolExecuteRequest.java index ec21438..5c95aa7 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/ToolExecuteRequest.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/ToolExecuteRequest.java @@ -1,6 +1,7 @@ package ai.gradientlabs.client.request; import ai.gradientlabs.client.model.Argument; +import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.ArrayList; @@ -9,11 +10,15 @@ /** * Request to execute a tool. */ +@JsonInclude(JsonInclude.Include.NON_NULL) public class ToolExecuteRequest { @JsonProperty("arguments") private List arguments; + @JsonProperty("token") + private String token; + /** * Creates a new tool execute request. */ @@ -59,4 +64,17 @@ public ToolExecuteRequest addArgument(String name, String value) { this.arguments.add(new Argument(name, value)); return this; } + + /** + * Returns the conversation token to run the tool with, if it needs one. + * + * @return the token + */ + public String getToken() { + return token; + } + + public void setToken(String token) { + this.token = token; + } } diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/UpdateKnowledgeBaseRequest.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/UpdateKnowledgeBaseRequest.java new file mode 100644 index 0000000..f4fae0c --- /dev/null +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/UpdateKnowledgeBaseRequest.java @@ -0,0 +1,70 @@ +package ai.gradientlabs.client.request; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Parameters for renaming a knowledge base. + */ +@JsonInclude(JsonInclude.Include.NON_NULL) +public class UpdateKnowledgeBaseRequest { + + @JsonProperty("name") + private final String name; + + private UpdateKnowledgeBaseRequest(Builder builder) { + this.name = builder.name; + } + + /** + * Returns a new builder. + * + * @return a new builder + */ + public static Builder builder() { + return new Builder(); + } + + /** + * Returns the knowledge base's new name. + * + * @return the name + */ + public String getName() { + return name; + } + + /** + * Builder for {@link UpdateKnowledgeBaseRequest}. + */ + public static class Builder { + private String name; + + private Builder() { + } + + /** + * Sets the knowledge base's new name. Required. + * + * @param name the name + * @return this builder + */ + public Builder name(String name) { + this.name = name; + return this; + } + + /** + * Builds the request. + * + * @return the request + * @throws IllegalStateException if a required field is missing + */ + public UpdateKnowledgeBaseRequest build() { + if (name == null || name.isBlank()) { + throw new IllegalStateException("name is required"); + } + return new UpdateKnowledgeBaseRequest(this); + } + } +} diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/UpdateNoteRequest.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/UpdateNoteRequest.java index 88e5923..bbbccf9 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/UpdateNoteRequest.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/UpdateNoteRequest.java @@ -3,6 +3,8 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.Map; +import java.util.List; import java.time.Instant; /** @@ -26,7 +28,15 @@ public class UpdateNoteRequest { @JsonProperty("end_time") private final Instant endTime; + @JsonProperty("attributes") + private final Map> attributes; + + @JsonProperty("knowledge_base_ids") + private final List knowledgeBaseIds; + private UpdateNoteRequest(Builder builder) { + this.attributes = builder.attributes; + this.knowledgeBaseIds = builder.knowledgeBaseIds; this.title = builder.title; this.body = builder.body; this.webpageUrl = builder.webpageUrl; @@ -58,7 +68,27 @@ public Instant getEndTime() { return endTime; } + /** + * Returns the note's attributes, by attribute name. + * + * @return the attributes + */ + public Map> getAttributes() { + return attributes; + } + + /** + * Returns your IDs of the knowledge bases the note belongs to. + * + * @return the knowledge base ids + */ + public List getKnowledgeBaseIds() { + return knowledgeBaseIds; + } + public static class Builder { + private Map> attributes; + private List knowledgeBaseIds; private String title; private String body; private String webpageUrl; @@ -127,6 +157,28 @@ public Builder endTime(Instant endTime) { return this; } + /** + * Sets the note's attributes, by attribute name. + * + * @param attributes the attributes + * @return this builder + */ + public Builder attributes(Map> attributes) { + this.attributes = attributes; + return this; + } + + /** + * Sets your IDs of the knowledge bases the note belongs to. + * + * @param knowledgeBaseIds the knowledge base ids + * @return this builder + */ + public Builder knowledgeBaseIds(List knowledgeBaseIds) { + this.knowledgeBaseIds = knowledgeBaseIds; + return this; + } + /** * Builds the request. * diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/UpdateResourceSourceRequest.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/UpdateResourceSourceRequest.java index 54afe9c..41f5c79 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/UpdateResourceSourceRequest.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/UpdateResourceSourceRequest.java @@ -3,6 +3,8 @@ import ai.gradientlabs.client.model.ResourceHTTPDefinition; import ai.gradientlabs.client.model.ResourceWebhookDefinition; import ai.gradientlabs.client.model.SourceType; +import ai.gradientlabs.client.model.ResourceSourceSchemaUpdate; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; @@ -20,6 +22,7 @@ @JsonInclude(JsonInclude.Include.NON_NULL) public class UpdateResourceSourceRequest { + @JsonIgnore private final String id; @JsonProperty("display_name") @@ -41,7 +44,7 @@ public class UpdateResourceSourceRequest { private final Map attributeDescriptions; @JsonProperty("schema") - private final Object schema; + private final ResourceSourceSchemaUpdate schema; private UpdateResourceSourceRequest(Builder builder) { this.id = builder.id; @@ -93,7 +96,7 @@ public Map getAttributeDescriptions() { return attributeDescriptions; } - public Object getSchema() { + public ResourceSourceSchemaUpdate getSchema() { return schema; } @@ -105,7 +108,7 @@ public static class Builder { private ResourceHTTPDefinition httpConfig; private ResourceWebhookDefinition webhookConfig; private Map attributeDescriptions; - private Object schema; + private ResourceSourceSchemaUpdate schema; private Builder() { } @@ -196,7 +199,7 @@ public Builder attributeDescriptions(Map attributeDescriptions) * @param schema the schema * @return this builder */ - public Builder schema(Object schema) { + public Builder schema(ResourceSourceSchemaUpdate schema) { this.schema = schema; return this; } diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/UpdateResourceSourceSchemaByExamplesRequest.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/UpdateResourceSourceSchemaByExamplesRequest.java index 3ffb5f7..5d6574a 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/UpdateResourceSourceSchemaByExamplesRequest.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/UpdateResourceSourceSchemaByExamplesRequest.java @@ -2,6 +2,7 @@ import ai.gradientlabs.client.model.SchemaUpdateStrategy; import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; @@ -19,6 +20,7 @@ @JsonInclude(JsonInclude.Include.NON_NULL) public class UpdateResourceSourceSchemaByExamplesRequest { + @JsonIgnore private final String id; @JsonProperty("examples") @@ -65,7 +67,7 @@ private Builder() { } /** - * Sets the unique identifier for the resource source to update (required). + * Sets the unique identifier for the resource source to update when calling the single-argument method. * * @param id the resource source ID * @return this builder @@ -106,9 +108,6 @@ public Builder schemaUpdateStrategy(SchemaUpdateStrategy schemaUpdateStrategy) { * @throws IllegalStateException if required fields are missing */ public UpdateResourceSourceSchemaByExamplesRequest build() { - if (id == null || id.isBlank()) { - throw new IllegalStateException("id is required"); - } if (examples == null || examples.isEmpty()) { throw new IllegalStateException("examples is required and cannot be empty"); } diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/UpdateResourceTypeRequest.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/UpdateResourceTypeRequest.java index 575e523..87c3ec6 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/UpdateResourceTypeRequest.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/UpdateResourceTypeRequest.java @@ -3,6 +3,7 @@ import ai.gradientlabs.client.model.RefreshStrategy; import ai.gradientlabs.client.model.Scope; import ai.gradientlabs.client.model.SourceConfig; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; @@ -14,6 +15,7 @@ @JsonInclude(JsonInclude.Include.NON_NULL) public class UpdateResourceTypeRequest { + @JsonIgnore private final String id; @JsonProperty("display_name") diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/UpdateToolRequest.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/UpdateToolRequest.java index 7624d82..dc88f54 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/UpdateToolRequest.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/UpdateToolRequest.java @@ -1,9 +1,14 @@ package ai.gradientlabs.client.request; +import ai.gradientlabs.client.model.HTTPDefinition; +import ai.gradientlabs.client.model.ToolAsyncDefinition; +import ai.gradientlabs.client.model.ToolParameter; +import ai.gradientlabs.client.model.ToolParameterSet; +import ai.gradientlabs.client.model.ToolWebhookDefinition; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; -import java.util.Map; +import java.util.List; /** * Parameters for updating a tool. @@ -11,48 +16,181 @@ @JsonInclude(JsonInclude.Include.NON_NULL) public class UpdateToolRequest { - @JsonProperty("name") - private final String name; - @JsonProperty("description") private final String description; - @JsonProperty("schema") - private final Map schema; + @JsonProperty("parameters") + private final List parameters; + + @JsonProperty("parameter_sets") + private final List parameterSets; + + @JsonProperty("http") + private final HTTPDefinition http; + + @JsonProperty("webhook") + private final ToolWebhookDefinition webhook; + + @JsonProperty("async") + private final ToolAsyncDefinition async; private UpdateToolRequest(Builder builder) { - this.name = builder.name; this.description = builder.description; - this.schema = builder.schema; + this.parameters = builder.parameters; + this.parameterSets = builder.parameterSets; + this.http = builder.http; + this.webhook = builder.webhook; + this.async = builder.async; } + /** + * Returns a new builder. + * + * @return a new builder + */ public static Builder builder() { return new Builder(); } + /** + * Returns what the tool does and when to use it. + * + * @return the description + */ + public String getDescription() { + return description; + } + + /** + * Returns the tool's input parameters. An empty or omitted list keeps the current parameters. + * + * @return the parameters + */ + public List getParameters() { + return parameters; + } + + /** + * Returns conditional groups of parameters. + * + * @return the parameter sets + */ + public List getParameterSets() { + return parameterSets; + } + + /** + * Returns the HTTP request that runs the tool. + * + * @return the http + */ + public HTTPDefinition getHttp() { + return http; + } + + /** + * Returns the webhook that runs the tool. + * + * @return the webhook + */ + public ToolWebhookDefinition getWebhook() { + return webhook; + } + + /** + * Returns the asynchronous configuration. + * + * @return the async + */ + public ToolAsyncDefinition getAsync() { + return async; + } + + /** + * Builder for {@link UpdateToolRequest}. + */ public static class Builder { - private String name; private String description; - private Map schema; + private List parameters; + private List parameterSets; + private HTTPDefinition http; + private ToolWebhookDefinition webhook; + private ToolAsyncDefinition async; private Builder() { } - public Builder name(String name) { - this.name = name; + /** + * Sets a new description. Leaving it empty keeps the current description. + * + * @param description the description + * @return this builder + */ + public Builder description(String description) { + this.description = description; return this; } - public Builder description(String description) { - this.description = description; + /** + * Sets the tool's input parameters. An empty or omitted list keeps the current parameters. + * + * @param parameters the parameters + * @return this builder + */ + public Builder parameters(List parameters) { + this.parameters = parameters; + return this; + } + + /** + * Sets conditional groups of parameters. + * + * @param parameterSets the parameter sets + * @return this builder + */ + public Builder parameterSets(List parameterSets) { + this.parameterSets = parameterSets; + return this; + } + + /** + * Sets the HTTP request that runs the tool. + * + * @param http the http + * @return this builder + */ + public Builder http(HTTPDefinition http) { + this.http = http; + return this; + } + + /** + * Sets the webhook that runs the tool. + * + * @param webhook the webhook + * @return this builder + */ + public Builder webhook(ToolWebhookDefinition webhook) { + this.webhook = webhook; return this; } - public Builder schema(Map schema) { - this.schema = schema; + /** + * Sets the asynchronous configuration. + * + * @param async the async + * @return this builder + */ + public Builder async(ToolAsyncDefinition async) { + this.async = async; return this; } + /** + * Builds the request. + * + * @return the request + */ public UpdateToolRequest build() { return new UpdateToolRequest(this); } diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/UpsertArticleRequest.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/UpsertArticleRequest.java index 9157717..5f1f993 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/UpsertArticleRequest.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/UpsertArticleRequest.java @@ -5,6 +5,7 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import java.util.List; import java.time.Instant; import java.util.HashMap; import java.util.Map; @@ -44,7 +45,7 @@ public class UpsertArticleRequest { private final PublicationStatus status; @JsonProperty("data") - private final Map data; + private final Object data; @JsonProperty("created") private final Instant created; @@ -52,7 +53,15 @@ public class UpsertArticleRequest { @JsonProperty("last_edited") private final Instant lastEdited; + @JsonProperty("knowledge_base_ids") + private final List knowledgeBaseIds; + + @JsonProperty("public_url") + private final String publicUrl; + private UpsertArticleRequest(Builder builder) { + this.knowledgeBaseIds = builder.knowledgeBaseIds; + this.publicUrl = builder.publicUrl; this.authorId = builder.authorId; this.id = builder.id; this.title = builder.title; @@ -102,7 +111,7 @@ public PublicationStatus getStatus() { return status; } - public Map getData() { + public Object getData() { return data; } @@ -114,7 +123,27 @@ public Instant getLastEdited() { return lastEdited; } + /** + * Returns your IDs of the knowledge bases the article belongs to. + * + * @return the knowledge base ids + */ + public List getKnowledgeBaseIds() { + return knowledgeBaseIds; + } + + /** + * Returns the article's public web address. + * + * @return the public url + */ + public String getPublicUrl() { + return publicUrl; + } + public static class Builder { + private List knowledgeBaseIds; + private String publicUrl; private String authorId; private String id; private String title; @@ -123,7 +152,7 @@ public static class Builder { private Visibility visibility; private String topicId; private PublicationStatus status; - private Map data; + private Object data; private Instant created; private Instant lastEdited; @@ -234,10 +263,10 @@ public Builder status(PublicationStatus status) { /** * Sets additional metadata about the article (optional). * - * @param data the metadata map + * @param data the JSON value * @return this builder */ - public Builder data(Map data) { + public Builder data(Object data) { this.data = data; return this; } @@ -250,10 +279,13 @@ public Builder data(Map data) { * @return this builder */ public Builder addData(String key, Object value) { - if (this.data == null) { - this.data = new HashMap<>(); + if (data != null && !(data instanceof Map)) { + throw new IllegalStateException("Adding a field requires object data"); } - this.data.put(key, value); + Map fields = data instanceof Map existing + ? new HashMap<>(existing) : new HashMap<>(); + fields.put(key, value); + data = fields; return this; } @@ -279,6 +311,28 @@ public Builder lastEdited(Instant lastEdited) { return this; } + /** + * Sets your IDs of the knowledge bases the article belongs to. + * + * @param knowledgeBaseIds the knowledge base ids + * @return this builder + */ + public Builder knowledgeBaseIds(List knowledgeBaseIds) { + this.knowledgeBaseIds = knowledgeBaseIds; + return this; + } + + /** + * Sets the article's public web address. + * + * @param publicUrl the public url + * @return this builder + */ + public Builder publicUrl(String publicUrl) { + this.publicUrl = publicUrl; + return this; + } + /** * Builds the request. * diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/UpsertArticleTopicRequest.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/UpsertArticleTopicRequest.java index 583dcb8..2d919b6 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/UpsertArticleTopicRequest.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/UpsertArticleTopicRequest.java @@ -38,7 +38,7 @@ public class UpsertArticleTopicRequest { private final PublicationStatus status; @JsonProperty("data") - private final Map data; + private final Object data; @JsonProperty("created") private final Instant created; @@ -46,7 +46,11 @@ public class UpsertArticleTopicRequest { @JsonProperty("last_edited") private final Instant lastEdited; + @JsonProperty("public_url") + private final String publicUrl; + private UpsertArticleTopicRequest(Builder builder) { + this.publicUrl = builder.publicUrl; this.id = builder.id; this.parentId = builder.parentId; this.name = builder.name; @@ -86,7 +90,7 @@ public PublicationStatus getStatus() { return status; } - public Map getData() { + public Object getData() { return data; } @@ -98,14 +102,24 @@ public Instant getLastEdited() { return lastEdited; } + /** + * Returns the topic's public web address. + * + * @return the public url + */ + public String getPublicUrl() { + return publicUrl; + } + public static class Builder { + private String publicUrl; private String id; private String parentId; private String name; private String description; private Visibility visibility; private PublicationStatus status; - private Map data; + private Object data; private Instant created; private Instant lastEdited; @@ -174,7 +188,7 @@ public Builder visibility(Visibility visibility) { } /** - * Sets whether this topic is published or a draft (required). + * Sets the publication status. This has no effect on topics. * * @param status the publication status * @return this builder @@ -187,10 +201,10 @@ public Builder status(PublicationStatus status) { /** * Sets additional metadata about the topic (optional). * - * @param data the metadata map + * @param data the JSON value * @return this builder */ - public Builder data(Map data) { + public Builder data(Object data) { this.data = data; return this; } @@ -203,10 +217,13 @@ public Builder data(Map data) { * @return this builder */ public Builder addData(String key, Object value) { - if (this.data == null) { - this.data = new HashMap<>(); + if (data != null && !(data instanceof Map)) { + throw new IllegalStateException("Adding a field requires object data"); } - this.data.put(key, value); + Map fields = data instanceof Map existing + ? new HashMap<>(existing) : new HashMap<>(); + fields.put(key, value); + data = fields; return this; } @@ -232,6 +249,17 @@ public Builder lastEdited(Instant lastEdited) { return this; } + /** + * Sets the topic's public web address. + * + * @param publicUrl the public url + * @return this builder + */ + public Builder publicUrl(String publicUrl) { + this.publicUrl = publicUrl; + return this; + } + /** * Builds the request. * @@ -248,9 +276,6 @@ public UpsertArticleTopicRequest build() { if (visibility == null) { throw new IllegalStateException("visibility is required"); } - if (status == null) { - throw new IllegalStateException("status is required"); - } if (created == null) { throw new IllegalStateException("created is required"); } diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/UpsertHandOffTargetRequest.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/UpsertHandOffTargetRequest.java index 0512362..b29da0a 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/UpsertHandOffTargetRequest.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/UpsertHandOffTargetRequest.java @@ -17,7 +17,11 @@ public class UpsertHandOffTargetRequest { @JsonProperty("name") private final String name; + @JsonProperty("ref") + private final String ref; + private UpsertHandOffTargetRequest(Builder builder) { + this.ref = builder.ref; this.id = builder.id; this.name = builder.name; } @@ -34,7 +38,17 @@ public String getName() { return name; } + /** + * Returns the reference used to point to this target from procedures. + * + * @return the ref + */ + public String getRef() { + return ref; + } + public static class Builder { + private String ref; private String id; private String name; @@ -66,6 +80,17 @@ public Builder name(String name) { return this; } + /** + * Sets the reference used to point to this target from procedures. + * + * @param ref the ref + * @return this builder + */ + public Builder ref(String ref) { + this.ref = ref; + return this; + } + /** * Builds the request. * diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/WriteSecretRequest.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/WriteSecretRequest.java index 4e88a23..cbbed3a 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/WriteSecretRequest.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/request/WriteSecretRequest.java @@ -1,6 +1,7 @@ package ai.gradientlabs.client.request; import ai.gradientlabs.client.model.RefreshMechanismHTTP; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; @@ -14,6 +15,7 @@ @JsonInclude(JsonInclude.Include.NON_NULL) public class WriteSecretRequest { + @JsonIgnore private final String name; @JsonProperty("value") diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/webhook/Webhook.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/webhook/Webhook.java index 442d5e5..aab36ca 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/webhook/Webhook.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/webhook/Webhook.java @@ -139,12 +139,50 @@ public ActionExecuteEvent asActionExecute() { /** * Returns the data for a {@code resource.pull} event. * - * @return the event data, or null if this is not a resource pull event + * @deprecated Resource fetches use {@link #asActionExecute()}. + * @return the legacy event data */ + @Deprecated public ResourcePullEvent asResourcePull() { return data instanceof ResourcePullEvent ? (ResourcePullEvent) data : null; } + /** + * Returns the data for a {@code conversation.start} event. + * + * @return the event data, or null if this is not a conversation start event + */ + public ConversationStartEvent asConversationStart() { + return data instanceof ConversationStartEvent ? (ConversationStartEvent) data : null; + } + + /** + * Returns the data for a {@code back-office-task.complete} event. + * + * @return the event data, or null if this is not a back-office task complete event + */ + public BackOfficeTaskCompleteEvent asBackOfficeTaskComplete() { + return data instanceof BackOfficeTaskCompleteEvent ? (BackOfficeTaskCompleteEvent) data : null; + } + + /** + * Returns the data for a {@code back-office-task.hand-off} event. + * + * @return the event data, or null if this is not a back-office task hand-off event + */ + public BackOfficeTaskHandOffEvent asBackOfficeTaskHandOff() { + return data instanceof BackOfficeTaskHandOffEvent ? (BackOfficeTaskHandOffEvent) data : null; + } + + /** + * Returns the data for a {@code back-office-task.fail} event. + * + * @return the event data, or null if this is not a back-office task fail event + */ + public BackOfficeTaskFailEvent asBackOfficeTaskFail() { + return data instanceof BackOfficeTaskFailEvent ? (BackOfficeTaskFailEvent) data : null; + } + @Override public String toString() { return "Webhook{" + diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/webhook/WebhookType.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/webhook/WebhookType.java index b177a17..477990a 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/webhook/WebhookType.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/webhook/WebhookType.java @@ -21,15 +21,41 @@ public enum WebhookType { */ CONVERSATION_FINISHED("conversation.finished"), + /** + * The agent is starting an outbound conversation and wants to send the first message. + */ + CONVERSATION_START("conversation.start"), + /** * The agent needs an action to be executed (e.g., while following a procedure). */ ACTION_EXECUTE("action.execute"), /** - * The agent wants to pull a resource. + * @deprecated Resource fetches use {@link #ACTION_EXECUTE}. + */ + @Deprecated + RESOURCE_PULL("resource.pull"), + + /** + * A back-office task has completed. */ - RESOURCE_PULL("resource.pull"); + BACK_OFFICE_TASK_COMPLETE("back-office-task.complete"), + + /** + * A back-office task has been handed off to a human. + */ + BACK_OFFICE_TASK_HAND_OFF("back-office-task.hand-off"), + + /** + * A back-office task has failed. + */ + BACK_OFFICE_TASK_FAIL("back-office-task.fail"), + + /** + * An event type this version of the client does not know. Its data is the raw JSON. + */ + UNKNOWN("unknown"); private final String value; @@ -37,6 +63,21 @@ public enum WebhookType { this.value = value; } + /** + * Returns the type with the given wire value, or {@link #UNKNOWN} if there is none. + * + * @param value the event type as sent in the webhook + * @return the matching type + */ + public static WebhookType fromValue(String value) { + for (WebhookType type : values()) { + if (type != UNKNOWN && type.value.equals(value)) { + return type; + } + } + return UNKNOWN; + } + @JsonValue public String getValue() { return value; diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/webhook/WebhookVerifier.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/webhook/WebhookVerifier.java index 3270da2..d60647f 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/webhook/WebhookVerifier.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/webhook/WebhookVerifier.java @@ -2,14 +2,14 @@ import ai.gradientlabs.client.exception.GradientLabsException; import ai.gradientlabs.client.exception.InvalidWebhookSignatureException; +import ai.gradientlabs.client.internal.Json; import ai.gradientlabs.client.webhook.event.*; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import jakarta.servlet.http.HttpServletRequest; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; -import jakarta.servlet.http.HttpServletRequest; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.security.InvalidKeyException; @@ -42,8 +42,7 @@ public class WebhookVerifier { public WebhookVerifier(String signingKey, Duration leeway) { this.secret = signingKey.getBytes(StandardCharsets.UTF_8); this.leeway = leeway; - this.objectMapper = new ObjectMapper(); - this.objectMapper.registerModule(new JavaTimeModule()); + this.objectMapper = Json.newMapper(); } /** @@ -187,9 +186,7 @@ private Webhook parseWebhook(String body) { Webhook webhook = new Webhook(); webhook.setId(root.get("id").asText()); - webhook.setType(WebhookType.valueOf( - root.get("type").asText().replace(".", "_").toUpperCase() - )); + webhook.setType(WebhookType.fromValue(root.path("type").asText())); webhook.setSequenceNumber(root.get("sequence_number").asInt()); webhook.setTimestamp(Instant.parse(root.get("timestamp").asText())); @@ -215,8 +212,16 @@ private Object parseEventData(WebhookType type, JsonNode dataNode) throws IOExce return objectMapper.treeToValue(dataNode, ActionExecuteEvent.class); case RESOURCE_PULL: return objectMapper.treeToValue(dataNode, ResourcePullEvent.class); + case CONVERSATION_START: + return objectMapper.treeToValue(dataNode, ConversationStartEvent.class); + case BACK_OFFICE_TASK_COMPLETE: + return objectMapper.treeToValue(dataNode, BackOfficeTaskCompleteEvent.class); + case BACK_OFFICE_TASK_HAND_OFF: + return objectMapper.treeToValue(dataNode, BackOfficeTaskHandOffEvent.class); + case BACK_OFFICE_TASK_FAIL: + return objectMapper.treeToValue(dataNode, BackOfficeTaskFailEvent.class); default: - throw new GradientLabsException("Unknown webhook type: " + type); + return dataNode; } } diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/webhook/event/ActionExecuteEvent.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/webhook/event/ActionExecuteEvent.java index c7e73c3..62adb8a 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/webhook/event/ActionExecuteEvent.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/webhook/event/ActionExecuteEvent.java @@ -6,7 +6,7 @@ /** * Event data for an {@code action.execute} webhook. *

- * Indicates the agent needs an action to be executed (e.g., while following a procedure). + * Sent when the agent calls a webhook tool or reads a webhook resource source. */ public class ActionExecuteEvent { @@ -19,6 +19,9 @@ public class ActionExecuteEvent { @JsonProperty("conversation") private WebhookConversation conversation; + @JsonProperty("back_office_task") + private WebhookBackOfficeTask backOfficeTask; + /** * Default constructor for Jackson. */ @@ -54,6 +57,15 @@ public WebhookConversation getConversation() { return conversation; } + /** + * Returns the back-office task the action is for. Null when it is for a conversation. + * + * @return the back office task + */ + public WebhookBackOfficeTask getBackOfficeTask() { + return backOfficeTask; + } + @Override public String toString() { return "ActionExecuteEvent{" + diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/webhook/event/AgentMessageEvent.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/webhook/event/AgentMessageEvent.java index 8448ba9..a5b471a 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/webhook/event/AgentMessageEvent.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/webhook/event/AgentMessageEvent.java @@ -24,6 +24,12 @@ public class AgentMessageEvent { @JsonProperty("intent") private String intent; + @JsonProperty("is_holding") + private Boolean isHolding; + + @JsonProperty("last_customer_message_id") + private String lastCustomerMessageId; + /** * Default constructor for Jackson. */ @@ -75,6 +81,24 @@ public String getIntent() { return intent; } + /** + * Returns whether this is a holding message sent while the agent works on a reply. + * + * @return the is holding + */ + public Boolean getIsHolding() { + return isHolding; + } + + /** + * Returns the ID of the last customer message the agent saw. + * + * @return the last customer message id + */ + public String getLastCustomerMessageId() { + return lastCustomerMessageId; + } + @Override public String toString() { return "AgentMessageEvent{" + diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/webhook/event/BackOfficeTaskCompleteEvent.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/webhook/event/BackOfficeTaskCompleteEvent.java new file mode 100644 index 0000000..875be94 --- /dev/null +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/webhook/event/BackOfficeTaskCompleteEvent.java @@ -0,0 +1,15 @@ +package ai.gradientlabs.client.webhook.event; + +/** + * Event data for a {@code back-office-task.complete} webhook. + *

+ * Indicates the back-office task has completed. Read its result from {@link ai.gradientlabs.client.model.BackOfficeTask#getResult()}. + */ +public class BackOfficeTaskCompleteEvent extends BackOfficeTaskEvent { + + /** + * Default constructor for Jackson. + */ + public BackOfficeTaskCompleteEvent() { + } +} diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/webhook/event/BackOfficeTaskEvent.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/webhook/event/BackOfficeTaskEvent.java new file mode 100644 index 0000000..381136d --- /dev/null +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/webhook/event/BackOfficeTaskEvent.java @@ -0,0 +1,27 @@ +package ai.gradientlabs.client.webhook.event; + +import ai.gradientlabs.client.model.BackOfficeTask; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Event data shared by the back-office task webhooks. + */ +public abstract class BackOfficeTaskEvent { + + @JsonProperty("back_office_task") + private BackOfficeTask backOfficeTask; + + /** + * Returns the back-office task the event is about. + * + * @return the back-office task + */ + public BackOfficeTask getBackOfficeTask() { + return backOfficeTask; + } + + @Override + public String toString() { + return getClass().getSimpleName() + "{backOfficeTask=" + backOfficeTask + '}'; + } +} diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/webhook/event/BackOfficeTaskFailEvent.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/webhook/event/BackOfficeTaskFailEvent.java new file mode 100644 index 0000000..1653fc9 --- /dev/null +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/webhook/event/BackOfficeTaskFailEvent.java @@ -0,0 +1,15 @@ +package ai.gradientlabs.client.webhook.event; + +/** + * Event data for a {@code back-office-task.fail} webhook. + *

+ * Indicates the back-office task has failed. Read why from {@link ai.gradientlabs.client.model.BackOfficeTask#getFailureReasons()}. + */ +public class BackOfficeTaskFailEvent extends BackOfficeTaskEvent { + + /** + * Default constructor for Jackson. + */ + public BackOfficeTaskFailEvent() { + } +} diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/webhook/event/BackOfficeTaskHandOffEvent.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/webhook/event/BackOfficeTaskHandOffEvent.java new file mode 100644 index 0000000..0eb792f --- /dev/null +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/webhook/event/BackOfficeTaskHandOffEvent.java @@ -0,0 +1,15 @@ +package ai.gradientlabs.client.webhook.event; + +/** + * Event data for a {@code back-office-task.hand-off} webhook. + *

+ * Indicates the back-office task has been handed off to a human. + */ +public class BackOfficeTaskHandOffEvent extends BackOfficeTaskEvent { + + /** + * Default constructor for Jackson. + */ + public BackOfficeTaskHandOffEvent() { + } +} diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/webhook/event/ConversationStartEvent.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/webhook/event/ConversationStartEvent.java new file mode 100644 index 0000000..08a8054 --- /dev/null +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/webhook/event/ConversationStartEvent.java @@ -0,0 +1,87 @@ +package ai.gradientlabs.client.webhook.event; + +import ai.gradientlabs.client.model.Channel; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Event data for a {@code conversation.start} webhook. + *

+ * Indicates the agent is starting an outbound conversation and wants you to send the first message. + */ +public class ConversationStartEvent { + + @JsonProperty("body") + private String body; + + @JsonProperty("subject") + private String subject; + + @JsonProperty("channel") + private Channel channel; + + @JsonProperty("customer_id") + private String customerId; + + @JsonProperty("initiator_id") + private String initiatorId; + + /** + * Default constructor for Jackson. + */ + public ConversationStartEvent() { + } + + /** + * Returns the first message to send to the customer. + * + * @return the message body + */ + public String getBody() { + return body; + } + + /** + * Returns the subject of the first message, for emails. + * + * @return the subject + */ + public String getSubject() { + return subject; + } + + /** + * Returns the channel to start the conversation on. + * + * @return the channel + */ + public Channel getChannel() { + return channel; + } + + /** + * Returns your identifier for the customer. + * + * @return the customer ID + */ + public String getCustomerId() { + return customerId; + } + + /** + * Returns the identifier of whoever started the outbound conversation. + * + * @return the initiator ID + */ + public String getInitiatorId() { + return initiatorId; + } + + @Override + public String toString() { + return "ConversationStartEvent{" + + "channel=" + channel + + ", customerId='" + customerId + '\'' + + ", initiatorId='" + initiatorId + '\'' + + '}'; + } +} diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/webhook/event/ResourcePullEvent.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/webhook/event/ResourcePullEvent.java index 19066ad..2807714 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/webhook/event/ResourcePullEvent.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/webhook/event/ResourcePullEvent.java @@ -3,10 +3,11 @@ import com.fasterxml.jackson.annotation.JsonProperty; /** - * Event data for a {@code resource.pull} webhook. + * Legacy resource event. Resource fetches use {@link ActionExecuteEvent}. *

* Indicates the agent wants to pull a resource. */ +@Deprecated public class ResourcePullEvent { @JsonProperty("resource_type") @@ -15,6 +16,9 @@ public class ResourcePullEvent { @JsonProperty("conversation") private WebhookConversation conversation; + @JsonProperty("back_office_task") + private WebhookBackOfficeTask backOfficeTask; + /** * Default constructor for Jackson. */ @@ -39,6 +43,15 @@ public WebhookConversation getConversation() { return conversation; } + /** + * Returns the back-office task the resource is read for. Null when it is read for a conversation. + * + * @return the back office task + */ + public WebhookBackOfficeTask getBackOfficeTask() { + return backOfficeTask; + } + @Override public String toString() { return "ResourcePullEvent{" + diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/webhook/event/WebhookBackOfficeTask.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/webhook/event/WebhookBackOfficeTask.java new file mode 100644 index 0000000..4f6537a --- /dev/null +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/webhook/event/WebhookBackOfficeTask.java @@ -0,0 +1,27 @@ +package ai.gradientlabs.client.webhook.event; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * The back-office task a webhook relates to. + */ +public class WebhookBackOfficeTask { + + @JsonProperty("id") + private String id; + + /** + * Default constructor for Jackson. + */ + public WebhookBackOfficeTask() { + } + + /** + * Returns your identifier for the back-office task. + * + * @return the id + */ + public String getId() { + return id; + } +} diff --git a/gradient-labs-client/src/main/java/ai/gradientlabs/client/webhook/event/WebhookConversation.java b/gradient-labs-client/src/main/java/ai/gradientlabs/client/webhook/event/WebhookConversation.java index 0156908..e7ec9b4 100644 --- a/gradient-labs-client/src/main/java/ai/gradientlabs/client/webhook/event/WebhookConversation.java +++ b/gradient-labs-client/src/main/java/ai/gradientlabs/client/webhook/event/WebhookConversation.java @@ -18,6 +18,9 @@ public class WebhookConversation { @JsonProperty("metadata") private Map metadata; + @JsonProperty("customer_source") + private String customerSource; + /** * Default constructor for Jackson. */ @@ -51,6 +54,15 @@ public Map getMetadata() { return metadata; } + /** + * Returns the support platform the customer came from, such as {@code intercom}. + * + * @return the customer source + */ + public String getCustomerSource() { + return customerSource; + } + @Override public String toString() { return "WebhookConversation{" + diff --git a/gradient-labs-client/src/test/java/ai/gradientlabs/client/ClientRequestsTest.java b/gradient-labs-client/src/test/java/ai/gradientlabs/client/ClientRequestsTest.java new file mode 100644 index 0000000..9ef5276 --- /dev/null +++ b/gradient-labs-client/src/test/java/ai/gradientlabs/client/ClientRequestsTest.java @@ -0,0 +1,301 @@ +package ai.gradientlabs.client; + +import ai.gradientlabs.client.exception.ResponseException; +import ai.gradientlabs.client.model.Attachment; +import ai.gradientlabs.client.model.AttachmentType; +import ai.gradientlabs.client.model.Channel; +import ai.gradientlabs.client.model.Conversation; +import ai.gradientlabs.client.model.CustomerMemory; +import ai.gradientlabs.client.model.FileListResponse; +import ai.gradientlabs.client.model.KnowledgeBase; +import ai.gradientlabs.client.model.MemoryCustomType; +import ai.gradientlabs.client.model.NoteListResponse; +import ai.gradientlabs.client.model.ParticipantType; +import ai.gradientlabs.client.model.Procedure; +import ai.gradientlabs.client.model.ProcedureStatus; +import ai.gradientlabs.client.model.TerminologySubstitution; +import ai.gradientlabs.client.model.Tool; +import ai.gradientlabs.client.model.ToolAsyncDefinition; +import ai.gradientlabs.client.model.ToolExecutionDefinition; +import ai.gradientlabs.client.model.ToolParameter; +import ai.gradientlabs.client.model.ToolParameterType; +import ai.gradientlabs.client.model.ToolWebhookDefinition; +import ai.gradientlabs.client.model.Topic; +import ai.gradientlabs.client.request.AddMessageRequest; +import ai.gradientlabs.client.request.AssignmentRequest; +import ai.gradientlabs.client.request.BatchCreateCustomerMemoriesV2Request; +import ai.gradientlabs.client.request.CreateToolRequest; +import ai.gradientlabs.client.request.UpdateToolRequest; +import ai.gradientlabs.client.request.CreateTrafficGroupTargetRequest; +import ai.gradientlabs.client.request.UpdateResourceSourceSchemaByExamplesRequest; +import ai.gradientlabs.client.request.DeleteHandOffTargetRequest; +import ai.gradientlabs.client.request.ListProceduresRequest; +import ai.gradientlabs.client.request.ListTopicsRequest; +import ai.gradientlabs.client.request.SetProcedureLimitRequest; +import ai.gradientlabs.client.request.ReadConversationRequest; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.jupiter.api.Test; + +import java.time.Duration; +import java.time.Instant; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class ClientRequestsTest { + + private final ObjectMapper mapper = new ObjectMapper(); + private final StubHttpClient http = new StubHttpClient(); + private final GradientLabsClient client = GradientLabsClient.builder() + .apiKey("test-key") + .baseUrl("https://api.example.com/") + .httpClient(http) + .build(); + + private String lastUri() { + return http.lastRequest().uri().toString(); + } + + @Test + void sendsRequestsToTheBaseUrlWithAuthAndUserAgent() { + http.respond(200, "{\"tools\":[]}"); + + client.listTools(); + + assertEquals("https://api.example.com/tools", lastUri()); + assertEquals("Bearer test-key", http.lastRequest().headers().firstValue("Authorization").orElse(null)); + assertTrue(http.lastRequest().headers().firstValue("User-Agent").orElse("") + .matches("Gradient-Labs-Java/\\S+ \\(Java/\\S+\\)")); + } + + @Test + void readConversationUsesTheReadPathAndSupportPlatformQuery() { + http.respond(200, "{\"id\":\"conv-1\",\"channel\":\"voice\",\"latest_intent\":\"refund\",\"new_field\":1}"); + + Conversation conversation = client.readConversation("conv 1", + ReadConversationRequest.builder().supportPlatform("intercom").build()); + + assertEquals("GET", http.lastRequest().method()); + assertEquals("https://api.example.com/conversations/conv%201/read?support_platform=intercom", lastUri()); + assertEquals(Channel.VOICE, conversation.getChannel()); + assertEquals("refund", conversation.getLatestIntent()); + + client.readConversation("conv-1"); + assertEquals("https://api.example.com/conversations/conv-1/read", lastUri()); + } + + @Test + @SuppressWarnings("deprecation") + void readConversationDeprecatedUsesTheOldPath() { + http.respond(200, "{\"id\":\"conv-1\"}"); + + client.readConversationDeprecated("conv-1"); + + assertEquals("https://api.example.com/conversations/conv-1", lastUri()); + } + + @Test + void queryParametersAreSentAndEncoded() { + http.respond(200, "{\"procedures\":[],\"pagination\":{}}"); + client.listProcedures(ListProceduresRequest.builder().cursor("a b&c").status(ProcedureStatus.LIVE).build()); + assertEquals("https://api.example.com/procedures?cursor=a+b%26c&status=live", lastUri()); + + http.respond(200, "{\"Topics\":[]}"); + client.listTopics(ListTopicsRequest.builder().supportPlatform("public-api").build()); + assertEquals("https://api.example.com/topics?support_platform=public-api", lastUri()); + + http.respond(200, "{\"id\":\"t\"}"); + client.readTool("tool-1", 3L); + assertEquals("https://api.example.com/tools/tool-1?version=3", lastUri()); + } + + @Test + void deleteHandOffTargetSendsTheIdAsAQueryParameter() { + http.respond(200, ""); + + client.deleteHandOffTarget(DeleteHandOffTargetRequest.builder().id("target-1").build()); + + assertEquals("DELETE", http.lastRequest().method()); + assertEquals("https://api.example.com/hand-off-targets?id=target-1", lastUri()); + assertEquals("", http.lastBody()); + } + + @Test + void listToolsAndSubstitutionsReadTheWrappedLists() { + http.respond(200, "{\"tools\":[{\"id\":\"t1\",\"name\":\"Lookup\",\"parameters\":[{\"name\":\"order_id\"," + + "\"type\":\"string\",\"allowed_sources\":[\"llm\"]}],\"async\":{\"timeout\":30000000000," + + "\"start_execution_tool\":{\"webhook\":{\"name\":\"start\"}}}}]}"); + List tools = client.listTools(); + assertEquals(1, tools.size()); + assertEquals(ToolParameterType.STRING, tools.get(0).getParameters().get(0).getType()); + assertEquals(Duration.ofSeconds(30), tools.get(0).getAsync().getTimeout()); + assertEquals("start", tools.get(0).getAsync().getStartExecutionTool().getWebhook().getName()); + + http.respond(200, "{\"substitutions\":[{\"id\":\"s1\",\"blocked\":\"foo\"}]}"); + List substitutions = client.listTerminologySubstitutions(); + assertEquals("s1", substitutions.get(0).getId()); + } + + @Test + void createToolWritesTheContractShape() throws Exception { + http.respond(200, "{\"id\":\"t1\"}"); + ToolParameter parameter = new ToolParameter(); + parameter.setName("order_id"); + parameter.setDescription("The order"); + parameter.setType(ToolParameterType.STRING); + ToolAsyncDefinition async = new ToolAsyncDefinition( + new ToolExecutionDefinition(null, new ToolWebhookDefinition("start")), null, + Duration.ofSeconds(30)); + + client.createTool(CreateToolRequest.builder() + .name("Lookup order").description("Looks up an order") + .parameters(List.of(parameter)).async(async).branchName("main") + .build()); + + JsonNode body = mapper.readTree(http.lastBody()); + assertTrue(body.path("id").isMissingNode()); + assertEquals("string", body.get("parameters").get(0).get("type").asText()); + assertEquals(30_000_000_000L, body.get("async").get("timeout").asLong()); + assertEquals("start", body.get("async").get("start_execution_tool").get("webhook").get("name").asText()); + assertTrue(body.get("async").get("start_execution_tool").path("http").isMissingNode()); + } + + @Test + void createToolSendsEmptyParametersWhenNoneAreSet() throws Exception { + http.respond(200, "{\"id\":\"t1\"}"); + client.createTool(CreateToolRequest.builder().name("n").description("d").draft(true).build()); + assertTrue(mapper.readTree(http.lastBody()).get("parameters").isArray()); + } + + @Test + void updateToolSendsOnlyTheSuppliedFields() throws Exception { + http.respond(200, "{}"); + client.updateTool("lookup", UpdateToolRequest.builder().description("Look up an order").build()); + assertEquals(mapper.readTree("{\"description\":\"Look up an order\"}"), mapper.readTree(http.lastBody())); + client.updateTool("lookup", UpdateToolRequest.builder().parameters(List.of()).build()); + assertEquals(mapper.readTree("{\"parameters\":[]}"), mapper.readTree(http.lastBody())); + } + + @Test + void replayAttachmentOnlyAiMessage() throws Exception { + http.respond(200, "{}"); + client.addMessage("chat", AddMessageRequest.builder().id("message").participantType(ParticipantType.AI_AGENT) + .addAttachment(new Attachment(AttachmentType.FILE, "receipt.pdf")).build()); + JsonNode body = mapper.readTree(http.lastBody()); + assertEquals("receipt.pdf", body.path("attachments").get(0).path("file_name").asText()); + assertTrue(body.path("body").isMissingNode()); + assertTrue(body.path("participant_id").isMissingNode()); + } + + @Test + void setProcedureLimitReadsTheReturnedProcedure() { + http.respond(200, "{\"procedure\":{\"id\":\"billing\",\"has_daily_limit\":true,\"max_daily_conversations\":25}}"); + Procedure procedure = client.setProcedureLimit("billing", SetProcedureLimitRequest.builder() + .hasDailyLimit(true).maxDailyConversations(25).build()); + assertEquals("billing", procedure.getId()); + assertEquals(25, procedure.getMaxDailyConversations()); + } + + @Test + void usesPathIdsWithoutSendingThemInTheRequestBody() throws Exception { + http.respond(200, "{}"); + client.createTrafficGroupTarget("group 1", CreateTrafficGroupTargetRequest.builder() + .targetType("procedure").targetId("billing").build()); + assertEquals("https://api.example.com/traffic-groups/group%201/targets", lastUri()); + assertEquals(mapper.readTree("{\"target_type\":\"procedure\",\"target_id\":\"billing\"}"), + mapper.readTree(http.lastBody())); + + client.updateResourceSourceSchemaByExamples("orders", UpdateResourceSourceSchemaByExamplesRequest.builder() + .examples(List.of(Map.of("id", "example"))).build()); + assertEquals("https://api.example.com/resource-sources/orders/schema-by-examples", lastUri()); + assertEquals(mapper.readTree("{\"examples\":[{\"id\":\"example\"}]}"), mapper.readTree(http.lastBody())); + } + + @Test + void timestampsAndParticipantTypesUseTheWireFormat() throws Exception { + http.respond(200, ""); + + client.assignConversation("conv-1", AssignmentRequest.builder() + .assigneeType(ParticipantType.AGENT) + .timestamp(Instant.parse("2026-01-02T03:04:05Z")) + .reason("needs a human") + .build()); + + JsonNode body = mapper.readTree(http.lastBody()); + assertEquals("Agent", body.get("assignee_type").asText()); + assertEquals("2026-01-02T03:04:05Z", body.get("timestamp").asText()); + assertEquals("AI Agent", ParticipantType.AI_AGENT.getValue()); + } + + @Test + void customerMemoriesUseTheCustomerPaths() throws Exception { + http.respond(200, ""); + client.batchCreateCustomerMemoriesV2("cust-1", BatchCreateCustomerMemoriesV2Request.builder() + .memories(List.of(new CustomerMemory("order_1", new MemoryCustomType("order", "Orders"), + Instant.parse("2026-07-01T10:00:00Z"), List.of(42, true)))) + .build()); + assertEquals("https://api.example.com/customers/cust-1/memories/v2", lastUri()); + JsonNode memory = mapper.readTree(http.lastBody()).get("memories").get(0); + assertEquals(mapper.readTree("[42,true]"), memory.get("data")); + assertEquals("order", memory.get("custom_type").get("name").asText()); + assertEquals("2026-07-01T10:00:00Z", memory.get("created_at").asText()); + + http.respond(200, "{\"memories\":[{\"external_id\":\"order_1\",\"custom_type\":{\"name\":\"order\"}," + + "\"created_at\":\"2026-07-01T10:00:00Z\",\"data\":{}}]}"); + List memories = client.listCustomerMemories("cust-1"); + assertEquals("GET", http.lastRequest().method()); + assertEquals("order", memories.get(0).getCustomType().getName()); + } + + @Test + void notesFilesAndKnowledgeBasesUseTheirPaths() { + http.respond(200, "{\"notes\":[{\"id\":\"n1\",\"attributes\":{\"region\":[\"uk\"]}}]," + + "\"pagination\":{\"next\":\"c2\"}}"); + NoteListResponse notes = client.listNotes("c1"); + assertEquals("https://api.example.com/notes?cursor=c1", lastUri()); + assertEquals(List.of("uk"), notes.getNotes().get(0).getAttributes().get("region")); + assertEquals("c2", notes.getPagination().getNext()); + + http.respond(200, "{\"id\":\"n1\"}"); + client.readNote("n1"); + assertEquals("https://api.example.com/notes/n1", lastUri()); + + http.respond(200, "{\"files\":[{\"id\":\"f1\",\"size_bytes\":10}],\"pagination\":{}}"); + FileListResponse files = client.listFiles(); + assertEquals("https://api.example.com/files", lastUri()); + assertEquals(10L, files.getFiles().get(0).getSizeBytes()); + + http.respond(200, "{\"id\":\"kb1\",\"gradient_labs_id\":\"g1\",\"name\":\"Help\"}"); + KnowledgeBase kb = client.readKnowledgeBase("kb1"); + assertEquals("https://api.example.com/knowledge-bases/kb1", lastUri()); + assertEquals("g1", kb.getGradientLabsId()); + } + + @Test + void topicsAndProcedureVersionsReadTheirFieldNames() { + http.respond(200, "{\"ExternalID\":\"billing\",\"Name\":\"Billing\",\"Visibility\":\"unknown\"," + + "\"Data\":\"aGk=\"}"); + Topic topic = client.readTopic("billing", null); + assertEquals("billing", topic.getExternalId()); + assertArrayEquals("hi".getBytes(), topic.getData()); + + http.respond(200, "{\"Versions\":[{\"Version\":3,\"Live\":true,\"GatedConfig\":{\"MaxDailyConversations\":5}}]}"); + ListProcedureVersionsResponse versions = client.listProcedureVersions("proc-1"); + assertEquals(3, versions.getVersions().get(0).getVersion()); + assertEquals(5, versions.getVersions().get(0).getGatedConfig().getMaxDailyConversations()); + } + + @Test + void errorResponsesOnGetBecomeResponseExceptions() { + http.respond(404, "{\"code\":\"not_found\",\"message\":\"no such note\",\"details\":{\"trace_id\":\"abc\"}}"); + + ResponseException e = assertThrows(ResponseException.class, () -> client.readNote("missing")); + + assertEquals(404, e.getStatusCode()); + } +} diff --git a/gradient-labs-client/src/test/java/ai/gradientlabs/client/OperationListTest.java b/gradient-labs-client/src/test/java/ai/gradientlabs/client/OperationListTest.java new file mode 100644 index 0000000..a8c76d5 --- /dev/null +++ b/gradient-labs-client/src/test/java/ai/gradientlabs/client/OperationListTest.java @@ -0,0 +1,125 @@ +package ai.gradientlabs.client; + +import org.junit.jupiter.api.Test; + +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Maps each public API operation ID this library implements to its client method. + * Update this map whenever PUBLIC_API_VERSION changes. + */ +class OperationListTest { + + static final Map OPERATIONS = new TreeMap<>(Map.ofEntries( + Map.entry("ArticleDelete", "deleteArticle"), + Map.entry("ArticleSetUsageStatus", "setArticleUsageStatus"), + Map.entry("ArticleTopicUpsert", "upsertArticleTopic"), + Map.entry("ArticleUpsert", "upsertArticle"), + Map.entry("BackOfficeTaskCreate", "createBackOfficeTask"), + Map.entry("BackOfficeTaskDelete", "deleteBackOfficeTask"), + Map.entry("BackOfficeTaskRead", "readBackOfficeTask"), + Map.entry("ConversationAddMessage", "addMessage"), + Map.entry("ConversationAssign", "assignConversation"), + Map.entry("ConversationCancel", "cancelConversation"), + Map.entry("ConversationDelete", "deleteConversation"), + Map.entry("ConversationEvent", "addConversationEvent"), + Map.entry("ConversationFinish", "finishConversation"), + Map.entry("ConversationRate", "rateConversation"), + Map.entry("ConversationRead", "readConversation"), + Map.entry("ConversationReadDeprecated", "readConversationDeprecated"), + Map.entry("ConversationResume", "resumeConversation"), + Map.entry("ConversationReturnAsyncToolResult", "returnAsyncToolResult"), + Map.entry("ConversationStart", "startConversation"), + Map.entry("CustomerMemoriesBatchCreate", "batchCreateCustomerMemories"), + Map.entry("CustomerMemoriesBatchCreateV2", "batchCreateCustomerMemoriesV2"), + Map.entry("CustomerMemoriesList", "listCustomerMemories"), + Map.entry("FileCreate", "createFile"), + Map.entry("FileList", "listFiles"), + Map.entry("FileUploadBegin", "beginFileUpload"), + Map.entry("GetDefaultHandOffTarget", "getDefaultHandOffTarget"), + Map.entry("HandOffTargetDelete", "deleteHandOffTarget"), + Map.entry("HandOffTargetUpsert", "upsertHandOffTarget"), + Map.entry("IPAddressList", "listIpAddresses"), + Map.entry("KnowledgeBaseCreate", "createKnowledgeBase"), + Map.entry("KnowledgeBaseList", "listKnowledgeBases"), + Map.entry("KnowledgeBaseRead", "readKnowledgeBase"), + Map.entry("KnowledgeBaseUpdate", "updateKnowledgeBase"), + Map.entry("ListHandOffTargets", "listHandOffTargets"), + Map.entry("ListProcedures", "listProcedures"), + Map.entry("ListTopics", "listTopics"), + Map.entry("ListTrafficGroups", "listTrafficGroups"), + Map.entry("NoteCreate", "createNote"), + Map.entry("NoteDelete", "deleteNote"), + Map.entry("NoteList", "listNotes"), + Map.entry("NoteRead", "readNote"), + Map.entry("NoteSetStatus", "setNoteStatus"), + Map.entry("NoteUpdate", "updateNote"), + Map.entry("OutboundChatConversationStart", "startOutboundChatConversation"), + Map.entry("OutboundEmailConversationStart", "startOutboundEmailConversation"), + Map.entry("OutboundPhoneConversationStart", "startOutboundPhoneConversation"), + Map.entry("ProcedureListVersions", "listProcedureVersions"), + Map.entry("ProcedureSetGatedVersion", "setProcedureGatedVersion"), + Map.entry("ProcedureSetLiveVersion", "setProcedureLiveVersion"), + Map.entry("ProcedureUnsetGatedVersion", "unsetProcedureGatedVersion"), + Map.entry("ProcedureUnsetLiveVersion", "unsetProcedureLiveVersion"), + Map.entry("ReadProcedure", "readProcedure"), + Map.entry("ReadTopic", "readTopic"), + Map.entry("ResourceSourceCreate", "createResourceSource"), + Map.entry("ResourceSourceDelete", "deleteResourceSource"), + Map.entry("ResourceSourceList", "listResourceSources"), + Map.entry("ResourceSourceRead", "readResourceSource"), + Map.entry("ResourceSourceUpdate", "updateResourceSource"), + Map.entry("ResourceTypeCreate", "createResourceType"), + Map.entry("ResourceTypeDelete", "deleteResourceType"), + Map.entry("ResourceTypeList", "listResourceTypes"), + Map.entry("ResourceTypeRead", "readResourceType"), + Map.entry("ResourceTypeUpdate", "updateResourceType"), + Map.entry("SecretList", "listSecrets"), + Map.entry("SecretRevoke", "revokeSecret"), + Map.entry("SecretWrite", "writeSecret"), + Map.entry("SetDefaultHandOffTarget", "setDefaultHandOffTarget"), + Map.entry("SetProcedureLimit", "setProcedureLimit"), + Map.entry("TerminologySubstitutionCreate", "createTerminologySubstitution"), + Map.entry("TerminologySubstitutionDelete", "deleteTerminologySubstitution"), + Map.entry("TerminologySubstitutionList", "listTerminologySubstitutions"), + Map.entry("TerminologySubstitutionRead", "readTerminologySubstitution"), + Map.entry("TerminologySubstitutionUpdate", "updateTerminologySubstitution"), + Map.entry("ToolCreate", "createTool"), + Map.entry("ToolDelete", "deleteTool"), + Map.entry("ToolExecute", "executeTool"), + Map.entry("ToolList", "listTools"), + Map.entry("ToolRead", "readTool"), + Map.entry("ToolUpdate", "updateTool"), + Map.entry("TrafficGroupCreate", "createTrafficGroup"), + Map.entry("TrafficGroupDelete", "deleteTrafficGroup"), + Map.entry("TrafficGroupExclusionCreate", "createTrafficGroupExclusion"), + Map.entry("TrafficGroupExclusionDelete", "deleteTrafficGroupExclusion"), + Map.entry("TrafficGroupTargetCreate", "createTrafficGroupTarget"), + Map.entry("TrafficGroupTargetDelete", "deleteTrafficGroupTarget"), + Map.entry("TrafficGroupUpdate", "updateTrafficGroup"), + Map.entry("UpdateSchemaByExamples", "updateResourceSourceSchemaByExamples"), + Map.entry("VoiceCallContextRead", "readVoiceCallContext") + )); + + @Test + void everyListedOperationHasAPublicClientMethod() { + List missing = new ArrayList<>(); + Method[] methods = GradientLabsClient.class.getDeclaredMethods(); + OPERATIONS.forEach((operationId, methodName) -> { + boolean found = Arrays.stream(methods) + .anyMatch(m -> m.getName().equals(methodName) && Modifier.isPublic(m.getModifiers())); + if (!found) { + missing.add(operationId + " -> " + methodName); + } + }); + assertTrue(missing.isEmpty(), "Client methods missing for: " + missing); + } +} diff --git a/gradient-labs-client/src/test/java/ai/gradientlabs/client/StubHttpClient.java b/gradient-labs-client/src/test/java/ai/gradientlabs/client/StubHttpClient.java new file mode 100644 index 0000000..0a3037e --- /dev/null +++ b/gradient-labs-client/src/test/java/ai/gradientlabs/client/StubHttpClient.java @@ -0,0 +1,202 @@ +package ai.gradientlabs.client; + +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLParameters; +import javax.net.ssl.SSLSession; +import java.net.Authenticator; +import java.net.CookieHandler; +import java.net.ProxySelector; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpHeaders; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.net.http.WebSocket; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.Executor; +import java.util.concurrent.Flow; + +/** + * An {@link HttpClient} that records each request and answers with a fixed status and body. + */ +final class StubHttpClient extends HttpClient { + + final List requests = new ArrayList<>(); + private int status = 200; + private String body = ""; + + StubHttpClient respond(int status, String body) { + this.status = status; + this.body = body; + return this; + } + + HttpRequest lastRequest() { + return requests.get(requests.size() - 1); + } + + String lastBody() { + HttpRequest request = lastRequest(); + if (request.bodyPublisher().isEmpty()) { + return ""; + } + StringBuilder out = new StringBuilder(); + CompletableFuture done = new CompletableFuture<>(); + request.bodyPublisher().get().subscribe(new Flow.Subscriber<>() { + @Override + public void onSubscribe(Flow.Subscription subscription) { + subscription.request(Long.MAX_VALUE); + } + + @Override + public void onNext(ByteBuffer item) { + byte[] bytes = new byte[item.remaining()]; + item.get(bytes); + out.append(new String(bytes, StandardCharsets.UTF_8)); + } + + @Override + public void onError(Throwable throwable) { + done.completeExceptionally(throwable); + } + + @Override + public void onComplete() { + done.complete(null); + } + }); + done.join(); + return out.toString(); + } + + @Override + @SuppressWarnings("unchecked") + public HttpResponse send(HttpRequest request, HttpResponse.BodyHandler responseBodyHandler) { + requests.add(request); + return (HttpResponse) new StubResponse(request, status, body); + } + + @Override + public CompletableFuture> sendAsync(HttpRequest request, HttpResponse.BodyHandler handler) { + return CompletableFuture.completedFuture(send(request, handler)); + } + + @Override + public CompletableFuture> sendAsync(HttpRequest request, HttpResponse.BodyHandler handler, + HttpResponse.PushPromiseHandler pushPromiseHandler) { + return CompletableFuture.completedFuture(send(request, handler)); + } + + @Override + public Optional cookieHandler() { + return Optional.empty(); + } + + @Override + public Optional connectTimeout() { + return Optional.empty(); + } + + @Override + public Redirect followRedirects() { + return Redirect.NEVER; + } + + @Override + public Optional proxy() { + return Optional.empty(); + } + + @Override + public SSLContext sslContext() { + try { + return SSLContext.getDefault(); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + @Override + public SSLParameters sslParameters() { + return new SSLParameters(); + } + + @Override + public Optional authenticator() { + return Optional.empty(); + } + + @Override + public Version version() { + return Version.HTTP_1_1; + } + + @Override + public Optional executor() { + return Optional.empty(); + } + + @Override + public WebSocket.Builder newWebSocketBuilder() { + throw new UnsupportedOperationException(); + } + + private static final class StubResponse implements HttpResponse { + private final HttpRequest request; + private final int status; + private final String body; + + private StubResponse(HttpRequest request, int status, String body) { + this.request = request; + this.status = status; + this.body = body; + } + + @Override + public int statusCode() { + return status; + } + + @Override + public HttpRequest request() { + return request; + } + + @Override + public Optional> previousResponse() { + return Optional.empty(); + } + + @Override + public HttpHeaders headers() { + return HttpHeaders.of(Map.of(), (a, b) -> true); + } + + @Override + public String body() { + return body; + } + + @Override + public Optional sslSession() { + return Optional.empty(); + } + + @Override + public URI uri() { + return request.uri(); + } + + @Override + public HttpClient.Version version() { + return HttpClient.Version.HTTP_1_1; + } + } +} diff --git a/gradient-labs-client/src/test/java/ai/gradientlabs/client/request/BatchCreateCustomerMemoriesRequestTest.java b/gradient-labs-client/src/test/java/ai/gradientlabs/client/request/BatchCreateCustomerMemoriesRequestTest.java new file mode 100644 index 0000000..d35df69 --- /dev/null +++ b/gradient-labs-client/src/test/java/ai/gradientlabs/client/request/BatchCreateCustomerMemoriesRequestTest.java @@ -0,0 +1,95 @@ +package ai.gradientlabs.client.request; + +import ai.gradientlabs.client.model.Memory; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; +import org.junit.jupiter.api.Test; + +import java.time.Instant; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@SuppressWarnings("deprecation") +class BatchCreateCustomerMemoriesRequestTest { + + private final ObjectMapper objectMapper = new ObjectMapper().registerModule(new JavaTimeModule()); + + @Test + void serializesAllFields() throws Exception { + BatchCreateCustomerMemoriesRequest request = BatchCreateCustomerMemoriesRequest.builder() + .memories(List.of( + Memory.builder() + .externalId("order_123") + .customType("order") + .createdAt(Instant.parse("2026-07-01T10:00:00Z")) + .data(Map.of("title", "Order #1", "amount", 42)) + .build(), + Memory.builder() + .externalId("order_456") + .customType("order") + .createdAt(Instant.parse("2026-07-02T10:00:00Z")) + .data(Map.of("title", "Order #2")) + .build())) + .build(); + + JsonNode json = objectMapper.valueToTree(request); + + assertTrue(json.get("memories").isArray()); + assertEquals(2, json.get("memories").size()); + + JsonNode first = json.get("memories").get(0); + assertEquals("order_123", first.get("external_id").asText()); + assertEquals("order", first.get("custom_type").asText()); + assertEquals("Order #1", first.get("data").get("title").asText()); + assertEquals(42, first.get("data").get("amount").asInt()); + assertTrue(first.has("created_at")); + } + + @Test + void requiresCustomType() { + assertThrows(IllegalStateException.class, () -> Memory.builder() + .externalId("order_123") + .createdAt(Instant.parse("2026-07-01T10:00:00Z")) + .data(Map.of("title", "Order #1")) + .build()); + } + + @Test + void requiresNonEmptyMemories() { + assertThrows(IllegalStateException.class, () -> BatchCreateCustomerMemoriesRequest.builder() + .memories(List.of()) + .build()); + } + + @Test + void requiresExternalId() { + assertThrows(IllegalStateException.class, () -> Memory.builder() + .customType("order") + .createdAt(Instant.parse("2026-07-01T10:00:00Z")) + .data(Map.of("title", "Order #1")) + .build()); + } + + @Test + void requiresCreatedAt() { + assertThrows(IllegalStateException.class, () -> Memory.builder() + .externalId("order_123") + .customType("order") + .data(Map.of("title", "Order #1")) + .build()); + } + + @Test + void requiresData() { + assertThrows(IllegalStateException.class, () -> Memory.builder() + .externalId("order_123") + .customType("order") + .createdAt(Instant.parse("2026-07-01T10:00:00Z")) + .build()); + } +} diff --git a/gradient-labs-client/src/test/java/ai/gradientlabs/client/webhook/WebhookVerifierTest.java b/gradient-labs-client/src/test/java/ai/gradientlabs/client/webhook/WebhookVerifierTest.java new file mode 100644 index 0000000..b0eb33e --- /dev/null +++ b/gradient-labs-client/src/test/java/ai/gradientlabs/client/webhook/WebhookVerifierTest.java @@ -0,0 +1,140 @@ +package ai.gradientlabs.client.webhook; + +import ai.gradientlabs.client.exception.InvalidWebhookSignatureException; +import ai.gradientlabs.client.model.BackOfficeTaskStatus; +import ai.gradientlabs.client.model.Channel; +import com.fasterxml.jackson.databind.JsonNode; +import jakarta.servlet.http.HttpServletRequest; +import org.junit.jupiter.api.Test; + +import javax.crypto.Mac; +import javax.crypto.spec.SecretKeySpec; +import java.io.BufferedReader; +import java.io.StringReader; +import java.lang.reflect.Proxy; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.time.Instant; +import java.util.HexFormat; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class WebhookVerifierTest { + + private static final String KEY = "signing-key"; + private final WebhookVerifier verifier = new WebhookVerifier(KEY, Duration.ofMinutes(5)); + + private static String envelope(String type, String data) { + return "{\"id\":\"evt-1\",\"type\":\"" + type + "\",\"sequence_number\":7," + + "\"timestamp\":\"2026-01-02T03:04:05Z\",\"data\":" + data + "}"; + } + + private static String sign(String key, long timestamp, String body) throws Exception { + Mac mac = Mac.getInstance("HmacSHA256"); + mac.init(new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256")); + byte[] sig = mac.doFinal((timestamp + "." + body).getBytes(StandardCharsets.UTF_8)); + return "t=" + timestamp + ",v1=" + HexFormat.of().formatHex(sig); + } + + private static HttpServletRequest request(String body, String signature) throws Exception { + BufferedReader reader = new BufferedReader(new StringReader(body)); + return (HttpServletRequest) Proxy.newProxyInstance( + HttpServletRequest.class.getClassLoader(), + new Class[]{HttpServletRequest.class}, + (proxy, method, args) -> { + switch (method.getName()) { + case "getHeader": + return "X-GradientLabs-Signature".equals(args[0]) ? signature : null; + case "getReader": + return reader; + default: + return null; + } + }); + } + + private Webhook parse(String body) throws Exception { + return verifier.parseAndVerify(request(body, sign(KEY, Instant.now().getEpochSecond(), body))); + } + + @Test + void rejectsWrongKeyAndStaleTimestamps() throws Exception { + String body = envelope("agent.message", "{\"body\":\"hi\",\"conversation\":{\"id\":\"c\"}}"); + long now = Instant.now().getEpochSecond(); + + assertThrows(InvalidWebhookSignatureException.class, + () -> verifier.parseAndVerify(request(body, sign("other-key", now, body)))); + assertThrows(InvalidWebhookSignatureException.class, + () -> verifier.parseAndVerify(request(body, sign(KEY, now - 3600, body)))); + assertThrows(InvalidWebhookSignatureException.class, + () -> verifier.parseAndVerify(request(body, sign(KEY, now + 3600, body)))); + assertThrows(InvalidWebhookSignatureException.class, + () -> verifier.parseAndVerify(request(body, "garbage"))); + } + + @Test + void parsesAgentMessage() throws Exception { + Webhook webhook = parse(envelope("agent.message", "{\"body\":\"hi\",\"is_holding\":true," + + "\"last_customer_message_id\":\"m1\",\"conversation\":{\"id\":\"c\",\"customer_id\":\"u\"}}")); + + assertEquals(WebhookType.AGENT_MESSAGE, webhook.getType()); + assertEquals("hi", webhook.asAgentMessage().getBody()); + assertEquals(Boolean.TRUE, webhook.asAgentMessage().getIsHolding()); + assertEquals("m1", webhook.asAgentMessage().getLastCustomerMessageId()); + } + + @Test + void parsesConversationHandOff() throws Exception { + Webhook webhook = parse(envelope("conversation.hand_off", + "{\"conversation\":{\"id\":\"c\"},\"reason_code\":\"customer-request\",\"reason\":\"asked\"}")); + + assertEquals(WebhookType.CONVERSATION_HANDOFF, webhook.getType()); + assertEquals("customer-request", webhook.asConversationHandOff().getReason()); + } + + @Test + void parsesConversationStart() throws Exception { + Webhook webhook = parse(envelope("conversation.start", "{\"body\":\"Hello\",\"subject\":\"Hi\"," + + "\"channel\":\"email\",\"customer_id\":\"u\",\"initiator_id\":\"i\"}")); + + assertEquals(WebhookType.CONVERSATION_START, webhook.getType()); + assertEquals(Channel.EMAIL, webhook.asConversationStart().getChannel()); + assertEquals("i", webhook.asConversationStart().getInitiatorId()); + } + + @Test + void parsesActionExecuteForABackOfficeTask() throws Exception { + Webhook webhook = parse(envelope("action.execute", + "{\"action\":\"lookup\",\"params\":{},\"back_office_task\":{\"id\":\"task-1\"}}")); + + assertEquals("task-1", webhook.asActionExecute().getBackOfficeTask().getId()); + } + + @Test + void parsesBackOfficeTaskEvents() throws Exception { + String task = "{\"back_office_task\":{\"id\":\"task-1\",\"agent_id\":\"a\",\"status\":\"completed\"," + + "\"input\":{},\"created\":\"2026-01-02T03:04:05Z\",\"attachments\":[{\"file_name\":\"f\"," + + "\"idempotency_key\":\"k\",\"external_url\":\"https://example.com/file\"}]}}"; + + Webhook complete = parse(envelope("back-office-task.complete", task)); + assertEquals(WebhookType.BACK_OFFICE_TASK_COMPLETE, complete.getType()); + assertEquals(BackOfficeTaskStatus.COMPLETED, complete.asBackOfficeTaskComplete().getBackOfficeTask().getStatus()); + assertEquals("https://example.com/file", complete.asBackOfficeTaskComplete().getBackOfficeTask() + .getAttachments().get(0).getExternalUrl()); + + assertEquals(WebhookType.BACK_OFFICE_TASK_HAND_OFF, + parse(envelope("back-office-task.hand-off", task)).getType()); + assertEquals("task-1", parse(envelope("back-office-task.fail", task)) + .asBackOfficeTaskFail().getBackOfficeTask().getId()); + } + + @Test + void unknownTypesReturnTheRawDataInsteadOfThrowing() throws Exception { + Webhook webhook = parse(envelope("something.new", "{\"x\":1}")); + + assertEquals(WebhookType.UNKNOWN, webhook.getType()); + assertTrue(webhook.getData() instanceof JsonNode); + } +} From 87ebf15df998e79abd729912e62606b09744bac3 Mon Sep 17 00:00:00 2001 From: Theo Windebank Date: Wed, 25 Nov 2026 14:41:22 +0000 Subject: [PATCH 2/2] [release] bump to 2.0.0 --- CHANGELOG.md | 64 +++++++++++++++++++ README.md | 8 +-- .../examples/spring-boot-example/pom.xml | 2 +- gradient-labs-client/pom.xml | 2 +- gradient-labs-spring-boot-starter/README.md | 4 +- gradient-labs-spring-boot-starter/pom.xml | 2 +- pom.xml | 2 +- 7 files changed, 74 insertions(+), 10 deletions(-) create mode 100644 CHANGELOG.md diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..533b7cd --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,64 @@ +# Changelog + +## 2.0.0 + +Brings the client in line with the public API (contract +`3e9c6fa0a27454d8d5300c42e4215c475c3954b085dae9901f429d0c531e50f3`, recorded in `PUBLIC_API_VERSION`). + +### Added + +- Customer memories: `listCustomerMemories`, `batchCreateCustomerMemoriesV2`, and the deprecated + `batchCreateCustomerMemories`. +- Files: `beginFileUpload`, `createFile`, `listFiles`. +- Knowledge bases: `listKnowledgeBases`, `createKnowledgeBase`, `readKnowledgeBase`, `updateKnowledgeBase`. +- Notes: `listNotes`, `readNote`. +- `readConversation(String)`, and `readConversationDeprecated` for the older `GET /conversations/{id}`. +- `readTool(String, Long)` to read a given tool version. +- Webhook events `conversation.start`, `back-office-task.complete`, `back-office-task.hand-off` and + `back-office-task.fail`. Unknown event types now return `WebhookType.UNKNOWN` with the raw JSON as data. +- Tools now carry their full definition: parameters, parameter sets, HTTP, webhook, async and MCP settings, + draft state and branch. +- New fields across conversations, messages, notes, articles, topics, hand-off targets, resource sources, + traffic groups, voice call context, back-office task attachments and webhook events. +- Enum values: `Channel.VOICE`, `ParticipantType.BOT`, `ProcedureStatus.UNSAVED` and `ARCHIVED`, + `Visibility.UNKNOWN`, `PublicationStatus.DELETED` and `EXCLUDED`, two Salesforce email identifier + types, and every support platform the API accepts. + +### Fixed + +- Requests now go to the configured base URL. +- Query parameters are sent and URL-encoded; path parameters are URL-encoded. +- `readConversation` calls `GET /conversations/{id}/read`. +- `listTools` and `listTerminologySubstitutions` read the API's wrapped list responses. +- `deleteHandOffTarget` sends the ID as a query parameter. +- Setting the daily limit returns the updated procedure. +- Resource fetches arrive as `action.execute` events. +- Topic reads accept an omitted support platform. +- Timestamps are sent as RFC 3339 strings, not numbers. +- `ParticipantType` sends the values the API accepts (`Customer`, `Agent`, `AI Agent`, `Bot`). +- Response fields and enum values the client does not know no longer fail parsing. +- Topics and procedure versions read the field names the API returns. +- `conversation.hand_off` webhooks parse again. +- Error responses to GET requests throw `ResponseException`, like other methods. +- Back-office task attachments send `base_64_contents`. + +### Breaking changes + +- Tool creation uses the returned ID. Omit the ID when building a create request. +- Read the public response fields on procedures, messages and back-office task attachments. + Procedure responses omit author details. Message responses omit the subject and conversation token. + Task attachments expose their download URL. +- Memory data, article and topic data, back-office task input and asynchronous tool results accept any JSON value. +- Use `SecretRefreshRequest` when configuring secret refreshes. The retry option sets the timeout per attempt. +- Use `ResourceSourceSchemaUpdate` to send a new raw schema for a resource source. +- File and note pagination expose the next cursor. Procedure pagination also exposes the previous cursor. + +- `ParticipantType.HUMAN` is renamed `AGENT`. +- `AttachmentType.DOCUMENT`, `VIDEO` and `AUDIO` are removed; use `FILE`. +- Removed fields the API does not have: `Conversation.metadata`, `Message.metadata`, + `Message.conversationId`, `StartConversationRequest` and `AddMessageRequest` metadata, and + `ReadConversationRequest.includeMessages` (replaced by `supportPlatform`). +- `Tool`, `CreateToolRequest` and `UpdateToolRequest` follow the API's tool shape; `schema`, `created` and + `updated` are gone, and `UpdateToolRequest` no longer takes a name. +- `Topic.getData()` returns `byte[]`. +- `Memory` (v1 batch create) now requires `customType`, as the API does. diff --git a/README.md b/README.md index 9d46957..16b1764 100644 --- a/README.md +++ b/README.md @@ -23,14 +23,14 @@ For Spring Boot applications, use the starter dependency for zero-configuration ai.gradient-labs gradient-labs-spring-boot-starter - 1.0.2 + 2.0.0 ``` ### Gradle ```gradle -implementation 'ai.gradient-labs:gradient-labs-spring-boot-starter:1.0.2' +implementation 'ai.gradient-labs:gradient-labs-spring-boot-starter:2.0.0' ``` ### Configuration @@ -95,14 +95,14 @@ For non-Spring applications, use the core client library: ai.gradient-labs gradient-labs-client - 1.0.2 + 2.0.0 ``` ### Gradle ```gradle -implementation 'ai.gradient-labs:gradient-labs-client:1.0.2' +implementation 'ai.gradient-labs:gradient-labs-client:2.0.0' ``` ## Error Handling diff --git a/gradient-labs-client/examples/spring-boot-example/pom.xml b/gradient-labs-client/examples/spring-boot-example/pom.xml index 88d167d..880dc68 100644 --- a/gradient-labs-client/examples/spring-boot-example/pom.xml +++ b/gradient-labs-client/examples/spring-boot-example/pom.xml @@ -28,7 +28,7 @@ ai.gradient-labs gradient-labs-spring-boot-starter - 1.0.2 + 2.0.0 diff --git a/gradient-labs-client/pom.xml b/gradient-labs-client/pom.xml index 1e225c4..eab644e 100644 --- a/gradient-labs-client/pom.xml +++ b/gradient-labs-client/pom.xml @@ -7,7 +7,7 @@ ai.gradient-labs gradient-labs-parent - 1.0.2 + 2.0.0 gradient-labs-client diff --git a/gradient-labs-spring-boot-starter/README.md b/gradient-labs-spring-boot-starter/README.md index fbba524..b32d755 100644 --- a/gradient-labs-spring-boot-starter/README.md +++ b/gradient-labs-spring-boot-starter/README.md @@ -20,14 +20,14 @@ This starter provides zero-configuration setup for Spring Boot applications usin ai.gradient-labs gradient-labs-spring-boot-starter - 1.0.2 + 2.0.0 ``` ### Gradle ```gradle -implementation 'ai.gradient-labs:gradient-labs-spring-boot-starter:1.0.2' +implementation 'ai.gradient-labs:gradient-labs-spring-boot-starter:2.0.0' ``` ## Configuration diff --git a/gradient-labs-spring-boot-starter/pom.xml b/gradient-labs-spring-boot-starter/pom.xml index 6d13e82..c378bf1 100644 --- a/gradient-labs-spring-boot-starter/pom.xml +++ b/gradient-labs-spring-boot-starter/pom.xml @@ -7,7 +7,7 @@ ai.gradient-labs gradient-labs-parent - 1.0.2 + 2.0.0 gradient-labs-spring-boot-starter diff --git a/pom.xml b/pom.xml index c3577d1..91ab8f9 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ ai.gradient-labs gradient-labs-parent - 1.0.2 + 2.0.0 pom Gradient Labs Java SDK