From b041d216c8ab457d47fd669bd85429c581655ab3 Mon Sep 17 00:00:00 2001 From: Theo Windebank Date: Wed, 25 Nov 2026 14:34:37 +0000 Subject: [PATCH 1/2] Sync with the public API contract Add file, knowledge base, note list/read and customer memory operations, the remaining webhook events and their fields, and the missing request and response fields. Fix query parameters, topic and procedure-version response names, timestamp decoding, and attachment types. Record the contract version and add an operation-list test. --- PUBLIC_API_VERSION | 1 + src/gradient_labs/__init__.py | 4 + src/gradient_labs/_article_topic_upsert.py | 14 +- src/gradient_labs/_article_topics_list.py | 7 +- src/gradient_labs/_article_upsert.py | 21 +- src/gradient_labs/_back_office_task_create.py | 13 +- .../_conversation_add_message.py | 78 +--- src/gradient_labs/_conversation_assign.py | 6 +- src/gradient_labs/_conversation_event.py | 3 +- src/gradient_labs/_conversation_read.py | 8 +- .../_conversation_read_deprecated.py | 11 + .../_conversation_return_async_tool_result.py | 11 +- src/gradient_labs/_conversation_start.py | 16 + .../_customer_memories_batch_create.py | 54 +++ .../_customer_memories_batch_create_v2.py | 56 +++ src/gradient_labs/_customer_memories_list.py | 12 + src/gradient_labs/_datetime.py | 50 ++ src/gradient_labs/_file_create.py | 39 ++ src/gradient_labs/_file_list.py | 43 ++ src/gradient_labs/_file_upload_begin.py | 31 ++ src/gradient_labs/_handoff_target_delete.py | 2 +- src/gradient_labs/_handoff_target_upsert.py | 8 +- src/gradient_labs/_http_client.py | 27 +- src/gradient_labs/_knowledge_base_create.py | 27 ++ src/gradient_labs/_knowledge_base_list.py | 22 + src/gradient_labs/_knowledge_base_read.py | 10 + src/gradient_labs/_knowledge_base_update.py | 26 ++ src/gradient_labs/_note_create.py | 17 +- src/gradient_labs/_note_list.py | 43 ++ src/gradient_labs/_note_read.py | 10 + src/gradient_labs/_note_update.py | 17 +- src/gradient_labs/_pagination.py | 7 +- src/gradient_labs/_procedure_list.py | 8 +- src/gradient_labs/_procedure_set_limit.py | 2 +- src/gradient_labs/_procedure_version_list.py | 12 +- src/gradient_labs/_resource_source_create.py | 10 + src/gradient_labs/_resource_source_update.py | 8 +- src/gradient_labs/_resource_type_create.py | 10 + src/gradient_labs/_secret_write.py | 7 +- src/gradient_labs/_tool_create.py | 6 +- src/gradient_labs/_tool_execute.py | 9 +- src/gradient_labs/_tool_read.py | 14 +- src/gradient_labs/_tool_update.py | 8 +- src/gradient_labs/_voice_call_context_read.py | 18 +- src/gradient_labs/_without_none.py | 11 + src/gradient_labs/article.py | 10 + src/gradient_labs/back_office_task.py | 6 +- src/gradient_labs/client.py | 190 +++++++- src/gradient_labs/conversation.py | 175 ++++++- src/gradient_labs/customer_memory.py | 44 ++ src/gradient_labs/file.py | 56 +++ src/gradient_labs/handoff_target.py | 5 + src/gradient_labs/knowledge_base.py | 27 ++ src/gradient_labs/note.py | 22 +- src/gradient_labs/procedure.py | 50 +- src/gradient_labs/resource_source.py | 33 +- src/gradient_labs/resource_type.py | 8 +- src/gradient_labs/secret.py | 23 +- src/gradient_labs/terminology_substitution.py | 6 +- src/gradient_labs/tool.py | 183 +++++++- src/gradient_labs/topic.py | 59 ++- src/gradient_labs/traffic_group.py | 5 +- src/gradient_labs/voice_call_context.py | 5 +- src/gradient_labs/webhook.py | 8 + tests/test_new_operations.py | 438 ++++++++++++++++++ tests/test_operations.py | 119 +++++ 66 files changed, 2069 insertions(+), 220 deletions(-) create mode 100644 PUBLIC_API_VERSION create mode 100644 src/gradient_labs/_conversation_read_deprecated.py create mode 100644 src/gradient_labs/_customer_memories_batch_create.py create mode 100644 src/gradient_labs/_customer_memories_batch_create_v2.py create mode 100644 src/gradient_labs/_customer_memories_list.py create mode 100644 src/gradient_labs/_datetime.py create mode 100644 src/gradient_labs/_file_create.py create mode 100644 src/gradient_labs/_file_list.py create mode 100644 src/gradient_labs/_file_upload_begin.py create mode 100644 src/gradient_labs/_knowledge_base_create.py create mode 100644 src/gradient_labs/_knowledge_base_list.py create mode 100644 src/gradient_labs/_knowledge_base_read.py create mode 100644 src/gradient_labs/_knowledge_base_update.py create mode 100644 src/gradient_labs/_note_list.py create mode 100644 src/gradient_labs/_note_read.py create mode 100644 src/gradient_labs/_without_none.py create mode 100644 src/gradient_labs/customer_memory.py create mode 100644 src/gradient_labs/file.py create mode 100644 src/gradient_labs/knowledge_base.py create mode 100644 tests/test_new_operations.py create mode 100644 tests/test_operations.py 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/src/gradient_labs/__init__.py b/src/gradient_labs/__init__.py index 66e0326..2087a38 100644 --- a/src/gradient_labs/__init__.py +++ b/src/gradient_labs/__init__.py @@ -1,4 +1,5 @@ from .client import * +from ._tool_execute import Argument as Argument from .article import * from .conversation import * from .handoff_target import * @@ -16,3 +17,6 @@ from .topic import * from .terminology_substitution import * from .ip_addresses import * +from .customer_memory import * +from .file import * +from .knowledge_base import * diff --git a/src/gradient_labs/_article_topic_upsert.py b/src/gradient_labs/_article_topic_upsert.py index 8be4e66..f0a2e16 100644 --- a/src/gradient_labs/_article_topic_upsert.py +++ b/src/gradient_labs/_article_topic_upsert.py @@ -1,7 +1,9 @@ -from typing import Optional +from typing import Any, Optional from collections import defaultdict from datetime import datetime +from ._datetime import parse_datetime + from dataclasses import dataclass, field from dataclasses_json import dataclass_json, config from marshmallow import fields @@ -30,7 +32,7 @@ class ArticleTopicUpsertParams: created: datetime = field( metadata=config( encoder=datetime.isoformat, - decoder=datetime.fromisoformat, + decoder=parse_datetime, mm_field=fields.DateTime(format="iso"), ) ) @@ -39,7 +41,7 @@ class ArticleTopicUpsertParams: last_edited: datetime = field( metadata=config( encoder=datetime.isoformat, - decoder=datetime.fromisoformat, + decoder=parse_datetime, mm_field=fields.DateTime(format="iso"), ) ) @@ -51,13 +53,17 @@ class ArticleTopicUpsertParams: parent_id: Optional[str] = None # data optionally gives additional meta-data about the topic. - data: Optional[dict] = field(default_factory=lambda: defaultdict(dict)) + data: Any = field(default_factory=lambda: defaultdict(dict)) + + public_url: Optional[str] = None def upsert_article_topic( *, client: HttpClient, params: ArticleTopicUpsertParams ) -> None: body = params.to_dict() + if params.public_url is None: + body.pop("public_url") if params.parent_id is None: body.pop("parent_id") if params.description is None: diff --git a/src/gradient_labs/_article_topics_list.py b/src/gradient_labs/_article_topics_list.py index 9dd154d..0249a47 100644 --- a/src/gradient_labs/_article_topics_list.py +++ b/src/gradient_labs/_article_topics_list.py @@ -1,7 +1,7 @@ from typing import List, Optional -from dataclasses import dataclass +from dataclasses import dataclass, field -from dataclasses_json import dataclass_json +from dataclasses_json import dataclass_json, config from .topic import Topic from ._http_client import HttpClient @@ -24,7 +24,8 @@ class ListTopicsParams: class ListTopicsResponse: """Response containing a list of topics.""" - topics: List[Topic] + # The API names this field `Topics`. + topics: List[Topic] = field(metadata=config(field_name="Topics")) def list_topics( diff --git a/src/gradient_labs/_article_upsert.py b/src/gradient_labs/_article_upsert.py index 3b3bba5..380ef70 100644 --- a/src/gradient_labs/_article_upsert.py +++ b/src/gradient_labs/_article_upsert.py @@ -1,7 +1,9 @@ -from typing import Optional, Any +from typing import Optional, Any, List from collections import defaultdict from datetime import datetime +from ._datetime import parse_datetime + from dataclasses import dataclass, field from dataclasses_json import dataclass_json, config from marshmallow import fields @@ -27,7 +29,7 @@ class UpsertArticleParams: created: datetime = field( metadata=config( encoder=datetime.isoformat, - decoder=datetime.fromisoformat, + decoder=parse_datetime, mm_field=fields.DateTime(format="iso"), ) ) @@ -36,7 +38,7 @@ class UpsertArticleParams: last_edited: datetime = field( metadata=config( encoder=datetime.isoformat, - decoder=datetime.fromisoformat, + decoder=parse_datetime, mm_field=fields.DateTime(format="iso"), ) ) @@ -61,6 +63,15 @@ class UpsertArticleParams: # data optionally gives additional meta-data about the article. data: Optional[Any] = field(default_factory=lambda: defaultdict(dict)) + # public_url optionally links to where the article can be read online. + public_url: Optional[str] = None + + # knowledge_base_ids optionally names the knowledge bases this article belongs to. + # Use the IDs of knowledge bases you created with create_knowledge_base, or + # "public-api". The list cannot be empty. If you leave it out, the article goes + # into the default "public-api" knowledge base, replacing any others it was in. + knowledge_base_ids: Optional[List[str]] = None + def upsert_article(*, client: HttpClient, params: UpsertArticleParams) -> None: body = params.to_dict() @@ -74,6 +85,10 @@ def upsert_article(*, client: HttpClient, params: UpsertArticleParams) -> None: body.pop("author_id") if params.body is None: body.pop("body") + if params.public_url is None: + body.pop("public_url") + if params.knowledge_base_ids is None: + body.pop("knowledge_base_ids") body["created"] = HttpClient.localize(params.created) body["last_edited"] = HttpClient.localize(params.last_edited) diff --git a/src/gradient_labs/_back_office_task_create.py b/src/gradient_labs/_back_office_task_create.py index d6acc6d..2dfe265 100644 --- a/src/gradient_labs/_back_office_task_create.py +++ b/src/gradient_labs/_back_office_task_create.py @@ -1,9 +1,10 @@ from typing import Optional, Dict, Any, List from datetime import datetime -from dataclasses import dataclass -from dataclasses_json import dataclass_json +from dataclasses import dataclass, field +from dataclasses_json import dataclass_json, config from ._http_client import HttpClient +from ._without_none import without_none from .back_office_task import BackOfficeTask @@ -13,7 +14,9 @@ class BackOfficeTaskCreateAttachment: file_name: str # Provide either url (remote file) or base64_contents (inline upload), not both. url: Optional[str] = None - base64_contents: Optional[str] = None + base64_contents: Optional[str] = field( + default=None, metadata=config(field_name="base_64_contents") + ) @dataclass_json @@ -25,7 +28,7 @@ class BackOfficeTaskCreateParams: # procedure_id is the procedure (prefix `proc_`) within the agent to start the # task from. procedure_id: str - input: Dict[str, Any] + input: Any created: Optional[datetime] = None metadata: Optional[Dict[str, str]] = None attachments: Optional[List[BackOfficeTaskCreateAttachment]] = None @@ -45,6 +48,6 @@ def create_back_office_task( if params.metadata is not None: body["metadata"] = params.metadata if params.attachments is not None: - body["attachments"] = [a.to_dict() for a in params.attachments] + body["attachments"] = [without_none(a.to_dict()) for a in params.attachments] rsp = client.post(path="back-office-tasks", body=body) return BackOfficeTask.from_dict(rsp) diff --git a/src/gradient_labs/_conversation_add_message.py b/src/gradient_labs/_conversation_add_message.py index 78a45af..489f0b2 100644 --- a/src/gradient_labs/_conversation_add_message.py +++ b/src/gradient_labs/_conversation_add_message.py @@ -2,41 +2,12 @@ from datetime import datetime from dataclasses import dataclass, field -from dataclasses_json import dataclass_json, config -from marshmallow import fields +from dataclasses_json import dataclass_json from ._http_client import HttpClient -from .conversation import AttachmentType, ParticipantType - - -@dataclass_json -@dataclass(frozen=True) -class Attachment: - # type of file that was uploaded. - type: AttachmentType - - # file_name is the name of the file that was uploaded, or an - # adequate placeholder for that name, which can be shown to reviewers. - file_name: str - - # url is the publicly accessible URL where the attachment can be downloaded - # from. This should be a fully qualified URL. If not given, the AI agent will - # only know that an attachment exists, but will be unable to process it. - url: Optional[str] = "" - - # summary is an optional short summary of the attachment. This is only intended - # to be used if you cannot give us access to the raw attachment, but can - # run your own LLM completions on the attachment and send us a description instead. - # - # If a summary or description is provided, then there must be no URL. - summary: Optional[str] = "" - - # description is an optional description of the attachment. This is only intended - # to be used if you cannot give us access to the raw attachment, but can - # run your own LLM completions on the attachment and send us a description instead. - # - # Chat to us first before using it! - description: Optional[str] = "" +from .conversation import Attachment, ParticipantType +from ._datetime import optional_datetime_config +from ._without_none import without_none @dataclass_json @@ -51,14 +22,14 @@ class AddMessageParams: id: str # body contains the message text. - body: str + body: Optional[str] = None # participant_id identifies the message sender. - participant_id: str + participant_id: Optional[str] = None # participant_type identifies the type of participant who sent this message. - # This cannot be set to ParticipantTypeAI. - participant_type: ParticipantType + # Use AI_AGENT only to replay a message already sent by the AI agent. + participant_type: Optional[ParticipantType] = None # created is the time at which the message was sent. created: Optional[datetime] = None @@ -71,6 +42,14 @@ class AddMessageParams: # as well as in HTTP Tools using templates. conversation_token: Optional[str] = None + # subject is the email subject line. It is only valid for email conversations, + # and rejected for every other channel. + subject: Optional[str] = None + + def __post_init__(self): + if self.participant_type is None: + raise TypeError("participant_type is required") + @dataclass_json @dataclass(frozen=True) @@ -86,22 +65,11 @@ class Message: # body contains the message text. body: str - # participant_id identifies the message sender. - participant_id: str - # participant_type identifies the type of participant who sent this message. participant_type: ParticipantType - # Created is the time at which the message was sent. - created: datetime = field( - metadata=config( - encoder=datetime.isoformat, - decoder=datetime.fromisoformat, - mm_field=fields.DateTime(format="iso"), - ) - ) - - # attachments contains any files that were uploaded with this message. + participant_id: str + created: Optional[datetime] = field(default=None, metadata=optional_datetime_config) attachments: Optional[List[Attachment]] = None @@ -110,16 +78,20 @@ def add_message( ) -> Message: body = { "id": params.id, - "body": params.body, - "participant_id": params.participant_id, "participant_type": params.participant_type.value, } + if params.body is not None: + body["body"] = params.body + if params.participant_id is not None: + body["participant_id"] = params.participant_id if params.created is not None: body["created"] = HttpClient.localize(params.created) if params.attachments is not None: - body["attachments"] = [a.to_dict() for a in params.attachments] + body["attachments"] = [without_none(a.to_dict()) for a in params.attachments] if params.conversation_token is not None: body["conversation_token"] = params.conversation_token + if params.subject is not None: + body["subject"] = params.subject rsp = client.post(path=f"conversations/{conversation_id}/messages", body=body) return Message.from_dict(rsp) diff --git a/src/gradient_labs/_conversation_assign.py b/src/gradient_labs/_conversation_assign.py index f957d13..19069ca 100644 --- a/src/gradient_labs/_conversation_assign.py +++ b/src/gradient_labs/_conversation_assign.py @@ -32,13 +32,15 @@ def assign_conversation( *, client: HttpClient, conversation_id: str, params: AssignmentParams ) -> None: """assigns a conversation to a participant.""" - body = {"assignee_type": params.participant_type.value} + body = {"assignee_type": params.assignee_type.value} if params.assignee_id: body["assignee_id"] = params.assignee_id if params.timestamp: body["timestamp"] = HttpClient.localize(params.timestamp) + if params.reason: + body["reason"] = params.reason _ = client.put( path=f"conversations/{conversation_id}/assignee", - body=params.to_dict(), + body=body, ) diff --git a/src/gradient_labs/_conversation_event.py b/src/gradient_labs/_conversation_event.py index e064227..ae72ddb 100644 --- a/src/gradient_labs/_conversation_event.py +++ b/src/gradient_labs/_conversation_event.py @@ -30,8 +30,7 @@ class EventParams: # IdempotencyKey optionally enables you to safely retry requests idempotency_key: Optional[str] = None - # Body optionally allows adding content (text) to the event. This is - # required for the + # Internal notes require a message body. body: Optional[str] = None diff --git a/src/gradient_labs/_conversation_read.py b/src/gradient_labs/_conversation_read.py index bcdf1fe..9bda900 100644 --- a/src/gradient_labs/_conversation_read.py +++ b/src/gradient_labs/_conversation_read.py @@ -21,12 +21,12 @@ class ReadParams: def read_conversation( *, client: HttpClient, conversation_id: str, params: Optional[ReadParams] = None ) -> Conversation: - path = f"conversations/{conversation_id}/read" + query_params = {} if params and params.support_platform: - path += "?support_platform={params.support_platform}" + query_params["support_platform"] = params.support_platform rsp = client.get( - path=path, - body=None, + path=f"conversations/{conversation_id}/read", + query_params=query_params, ) return Conversation.from_dict(rsp) diff --git a/src/gradient_labs/_conversation_read_deprecated.py b/src/gradient_labs/_conversation_read_deprecated.py new file mode 100644 index 0000000..edf9499 --- /dev/null +++ b/src/gradient_labs/_conversation_read_deprecated.py @@ -0,0 +1,11 @@ +from ._http_client import HttpClient +from .conversation import Conversation + + +def read_conversation_deprecated( + *, client: HttpClient, conversation_id: str +) -> Conversation: + """read_conversation_deprecated retrieves the conversation from the deprecated + `GET /conversations/{id}` endpoint. Use read_conversation instead.""" + rsp = client.get(path=f"conversations/{conversation_id}") + return Conversation.from_dict(rsp) diff --git a/src/gradient_labs/_conversation_return_async_tool_result.py b/src/gradient_labs/_conversation_return_async_tool_result.py index 3d7e9d1..5d8a082 100644 --- a/src/gradient_labs/_conversation_return_async_tool_result.py +++ b/src/gradient_labs/_conversation_return_async_tool_result.py @@ -1,4 +1,4 @@ -from typing import Optional, Any, Dict +from typing import Optional, Any from datetime import datetime from dataclasses import dataclass @@ -22,11 +22,8 @@ class ReturnAsyncToolResultParams: # requests the tool execution. async_tool_execution_id: str - # payload is the result data from the tool execution as a JSON object. - # The structure of this object depends on your tool's implementation. - # The agent will use AI to extract relevant information from any well-formed - # JSON object. - payload: Dict[str, Any] + # Any JSON value returned by the tool. + payload: Any # timestamp optionally defines the time when the result was generated. # If not given, this will default to the current time. @@ -50,7 +47,7 @@ def return_async_tool_result( results to conversations that are finished, failed, or cancelled. - Make sure to use the correct async_tool_execution_id from the action.execute webhook event. - - The result payload should be a valid JSON object containing the data the + - The result payload should be a valid JSON value containing the data the agent needs to continue the conversation. """ body = { diff --git a/src/gradient_labs/_conversation_start.py b/src/gradient_labs/_conversation_start.py index aeddd10..dfeda91 100644 --- a/src/gradient_labs/_conversation_start.py +++ b/src/gradient_labs/_conversation_start.py @@ -18,6 +18,16 @@ class SupportPlatform(str, Enum): SALESFORCE: str = "salesforce" FRESHCHAT: str = "freshchat" FRESHDESK: str = "freshdesk" + DIXA: str = "dixa" + GMAIL: str = "gmail" + KUSTOMER: str = "kustomer" + LIVECHAT: str = "livechat" + PUBLIC_API: str = "public-api" + CHAT_SDK: str = "chat-sdk" + LIVEKIT: str = "livekit" + TWILIO: str = "twilio" + TALKDESK: str = "talkdesk" + INTERCOM_VOICE: str = "intercom-voice" class CustomerSupportPlatformIdentifierType(str, Enum): @@ -30,6 +40,8 @@ class CustomerSupportPlatformIdentifierType(str, Enum): ZENDESK_SUPPORT_USER: str = "zendesk_support_user" SALESFORCE_CONTACT_ID: str = "salesforce_contact_id" SALESFORCE_ACCOUNT_ID: str = "salesforce_account_id" + SALESFORCE_CONTACT_EMAIL: str = "salesforce_contact_email" + SALESFORCE_SUPPLIED_EMAIL: str = "salesforce_supplied_email" @dataclass_json @@ -108,6 +120,10 @@ def start_conversation( "customer_id": params.customer_id, "channel": params.channel.value, } + if params.assignee_type is not None: + body["assignee_type"] = params.assignee_type.value + if params.assignee_id is not None: + body["assignee_id"] = params.assignee_id if params.created is not None: body["created"] = HttpClient.localize(params.created) if params.resources is not None: diff --git a/src/gradient_labs/_customer_memories_batch_create.py b/src/gradient_labs/_customer_memories_batch_create.py new file mode 100644 index 0000000..b6ad5df --- /dev/null +++ b/src/gradient_labs/_customer_memories_batch_create.py @@ -0,0 +1,54 @@ +from typing import Any, List +from datetime import datetime +from dataclasses import dataclass + +from ._http_client import HttpClient + + +@dataclass(frozen=True) +class BatchCreateCustomerMemoryDeprecated: + """BatchCreateCustomerMemoryDeprecated is one memory to store about a customer.""" + + # external_id is your own identifier for the memory. + external_id: str + + # custom_type is the name of the memory's category. + custom_type: str + + # created_at is when the memory's underlying event occurred. + created_at: datetime + + # data is any JSON value as the memory's payload. + data: Any + + +@dataclass(frozen=True) +class BatchCreateCustomerMemoriesDeprecatedParams: + """BatchCreateCustomerMemoriesDeprecatedParams contains the memories to store.""" + + memories: List[BatchCreateCustomerMemoryDeprecated] + + +def batch_create_customer_memories( + *, + client: HttpClient, + customer_id: str, + params: BatchCreateCustomerMemoriesDeprecatedParams, +) -> None: + """batch_create_customer_memories stores memories about a customer through the + deprecated `POST /customers/{customer_id}/memories` endpoint. Use + batch_create_customer_memories_v2 instead. + + Note: requires an `Integration` API key.""" + body = { + "memories": [ + { + "external_id": m.external_id, + "custom_type": m.custom_type, + "created_at": HttpClient.localize(m.created_at), + "data": m.data, + } + for m in params.memories + ] + } + _ = client.post(path=f"customers/{customer_id}/memories", body=body) diff --git a/src/gradient_labs/_customer_memories_batch_create_v2.py b/src/gradient_labs/_customer_memories_batch_create_v2.py new file mode 100644 index 0000000..70c8dcb --- /dev/null +++ b/src/gradient_labs/_customer_memories_batch_create_v2.py @@ -0,0 +1,56 @@ +from typing import Any, List +from datetime import datetime +from dataclasses import dataclass + +from ._http_client import HttpClient +from .customer_memory import CustomerMemoryType + + +@dataclass(frozen=True) +class BatchCreateCustomerMemory: + """BatchCreateCustomerMemory is one memory to store about a customer.""" + + # external_id is your own identifier for the memory. It must be unique within + # your company. Retrying the same memory is safe and creates no duplicate. + external_id: str + + # custom_type is the category of the memory. + custom_type: CustomerMemoryType + + # created_at is when the memory's underlying event occurred. + created_at: datetime + + # data is any JSON value as the memory's payload. + data: Any + + +@dataclass(frozen=True) +class BatchCreateCustomerMemoriesParams: + """BatchCreateCustomerMemoriesParams contains the memories to store.""" + + memories: List[BatchCreateCustomerMemory] + + +def batch_create_customer_memories_v2( + *, + client: HttpClient, + customer_id: str, + params: BatchCreateCustomerMemoriesParams, +) -> None: + """batch_create_customer_memories_v2 stores memories about a customer. + + Note: requires an `Integration` API key.""" + body = { + "memories": [ + { + "external_id": m.external_id, + "custom_type": { + k: v for k, v in m.custom_type.to_dict().items() if v is not None + }, + "created_at": HttpClient.localize(m.created_at), + "data": m.data, + } + for m in params.memories + ] + } + _ = client.post(path=f"customers/{customer_id}/memories/v2", body=body) diff --git a/src/gradient_labs/_customer_memories_list.py b/src/gradient_labs/_customer_memories_list.py new file mode 100644 index 0000000..f495f7b --- /dev/null +++ b/src/gradient_labs/_customer_memories_list.py @@ -0,0 +1,12 @@ +from ._http_client import HttpClient +from .customer_memory import CustomerMemoriesList + + +def list_customer_memories( + *, client: HttpClient, customer_id: str +) -> CustomerMemoriesList: + """list_customer_memories lists all memories retained for a customer. + + Note: requires an `Integration` API key.""" + rsp = client.get(path=f"customers/{customer_id}/memories") + return CustomerMemoriesList.from_dict(rsp) diff --git a/src/gradient_labs/_datetime.py b/src/gradient_labs/_datetime.py new file mode 100644 index 0000000..8e659fa --- /dev/null +++ b/src/gradient_labs/_datetime.py @@ -0,0 +1,50 @@ +import re +from datetime import datetime +from typing import Optional + +from dataclasses_json import config +from marshmallow import fields + + +def parse_datetime(value: str) -> datetime: + """parse_datetime reads an RFC 3339 timestamp, including a trailing `Z`.""" + if value.endswith("Z"): + value = value[:-1] + "+00:00" + # Python 3.9 and 3.10 accept only three or six fractional digits. + value = re.sub( + r"(?<=:\d{2})\.(\d+)", lambda m: "." + m[1][:6].ljust(6, "0"), value, count=1 + ) + return datetime.fromisoformat(value) + + +def _parse_optional(value: Optional[str]) -> Optional[datetime]: + return parse_datetime(value) if value is not None else None + + +def _format_optional(value: Optional[datetime]) -> Optional[str]: + return value.isoformat() if value is not None else None + + +# datetime_config decodes a required RFC 3339 timestamp field. +datetime_config = config( + encoder=datetime.isoformat, + decoder=parse_datetime, + mm_field=fields.DateTime(format="iso"), +) + +# optional_datetime_config decodes an RFC 3339 timestamp field that may be absent or null. +optional_datetime_config = config( + encoder=_format_optional, + decoder=_parse_optional, + mm_field=fields.DateTime(format="iso", allow_none=True, load_default=None), +) + + +def datetime_config_named(field_name: str) -> dict: + """datetime_config_named is datetime_config for a field the API names differently.""" + return config( + field_name=field_name, + encoder=datetime.isoformat, + decoder=parse_datetime, + mm_field=fields.DateTime(format="iso"), + ) diff --git a/src/gradient_labs/_file_create.py b/src/gradient_labs/_file_create.py new file mode 100644 index 0000000..23101d7 --- /dev/null +++ b/src/gradient_labs/_file_create.py @@ -0,0 +1,39 @@ +from typing import Optional +from dataclasses import dataclass +from dataclasses_json import dataclass_json + +from ._http_client import HttpClient +from .file import File + + +@dataclass_json +@dataclass(frozen=True) +class CreateFileParams: + """CreateFileParams contains the parameters for creating a file.""" + + # upload_id is the `upload_id` that begin_file_upload returned. + upload_id: str + + # file_name is the file's name, which the AI agent sees: 1 to 200 characters, with + # no slashes and no space at either end. + file_name: str + + # ref is the name a back-office test case uses to list this file as an attachment. + # Leave it out to have one made from file_name. + ref: Optional[str] = None + + +def create_file(*, client: HttpClient, params: CreateFileParams) -> File: + """create_file turns an uploaded file into a workspace file. Calling it again with + the same upload_id returns the same file. + + Note: requires a `Management` API key.""" + body = { + "upload_id": params.upload_id, + "file_name": params.file_name, + } + if params.ref is not None: + body["ref"] = params.ref + + rsp = client.post(path="files", body=body) + return File.from_dict(rsp) diff --git a/src/gradient_labs/_file_list.py b/src/gradient_labs/_file_list.py new file mode 100644 index 0000000..9a3c24b --- /dev/null +++ b/src/gradient_labs/_file_list.py @@ -0,0 +1,43 @@ +from typing import List, Optional +from dataclasses import dataclass +from dataclasses_json import dataclass_json + +from ._http_client import HttpClient +from ._pagination import ForwardPaginationInfo +from .file import File + + +@dataclass_json +@dataclass(frozen=True) +class FileListParams: + """FileListParams contains the parameters for listing files.""" + + # cursor is the page to fetch, from `pagination.next` in a previous response. + # Leave it out to get the first page. + cursor: Optional[str] = None + + +@dataclass_json +@dataclass(frozen=True) +class FileListResponse: + """FileListResponse is a page of files.""" + + # files are your company's files on this page, newest first. + files: List[File] + + # pagination contains the cursor for the next page, if there is one. + pagination: ForwardPaginationInfo + + +def list_files( + *, client: HttpClient, params: Optional[FileListParams] = None +) -> FileListResponse: + """list_files returns a page of the files uploaded to your workspace. + + Note: requires a `Management` API key.""" + query_params = {} + if params is not None and params.cursor is not None: + query_params["cursor"] = params.cursor + + rsp = client.get(path="files", query_params=query_params) + return FileListResponse.from_dict(rsp) diff --git a/src/gradient_labs/_file_upload_begin.py b/src/gradient_labs/_file_upload_begin.py new file mode 100644 index 0000000..9fb6247 --- /dev/null +++ b/src/gradient_labs/_file_upload_begin.py @@ -0,0 +1,31 @@ +from typing import Optional +from dataclasses import dataclass +from dataclasses_json import dataclass_json + +from ._http_client import HttpClient +from .file import FileUpload + + +@dataclass_json +@dataclass(frozen=True) +class BeginFileUploadParams: + """BeginFileUploadParams contains the parameters for starting a file upload.""" + + # content_type is the `Content-Type` header the upload sends. Leave it out to send + # `application/octet-stream`: the file's type is read from its contents either way. + content_type: Optional[str] = None + + +def begin_file_upload( + *, client: HttpClient, params: Optional[BeginFileUploadParams] = None +) -> FileUpload: + """begin_file_upload starts uploading a file to your workspace. PUT the file to the + returned upload_url, then call create_file with the upload_id. + + Note: requires a `Management` API key.""" + body = {} + if params is not None and params.content_type is not None: + body["content_type"] = params.content_type + + rsp = client.post(path="file-uploads", body=body) + return FileUpload.from_dict(rsp) diff --git a/src/gradient_labs/_handoff_target_delete.py b/src/gradient_labs/_handoff_target_delete.py index b28f5db..5bb7af6 100644 --- a/src/gradient_labs/_handoff_target_delete.py +++ b/src/gradient_labs/_handoff_target_delete.py @@ -17,5 +17,5 @@ def delete_hand_off_target( ) -> None: _ = client.delete( path="hand-off-targets", - body=params.to_dict(), + query_params={"id": params.id}, ) diff --git a/src/gradient_labs/_handoff_target_upsert.py b/src/gradient_labs/_handoff_target_upsert.py index 60bdb2e..8a91b76 100644 --- a/src/gradient_labs/_handoff_target_upsert.py +++ b/src/gradient_labs/_handoff_target_upsert.py @@ -1,3 +1,4 @@ +from typing import Optional from dataclasses import dataclass from dataclasses_json import dataclass_json @@ -14,11 +15,16 @@ class UpsertHandOffTargetParams: # name is the hand-off target’s name. This cannot be nil. name: str + # ref is an optional short reference for this target that never changes, made of + # letters, digits, `_` and `-`. It starts with a letter or digit, is at most 100 + # characters and is stored in lowercase. Leave it out to have one made from name. + ref: Optional[str] = None + def upsert_hand_off_target( *, client: HttpClient, params: UpsertHandOffTargetParams ) -> None: _ = client.post( path="hand-off-targets", - body=params.to_dict(), + body={k: v for k, v in params.to_dict().items() if v is not None}, ) diff --git a/src/gradient_labs/_http_client.py b/src/gradient_labs/_http_client.py index cddbe46..f3216ba 100644 --- a/src/gradient_labs/_http_client.py +++ b/src/gradient_labs/_http_client.py @@ -1,4 +1,4 @@ -from typing import Any, Callable +from typing import Any, Callable, Optional from datetime import datetime from importlib import metadata @@ -30,17 +30,17 @@ def __init__( self.base_url = base_url self.timeout = timeout - def post(self, path: str, body: Any): - return self._api_call(requests.post, path, body) + def post(self, path: str, body: Any = None, query_params: Optional[dict] = None): + return self._api_call(requests.post, path, body, query_params) - def put(self, path: str, body: Any): - return self._api_call(requests.put, path, body) + def put(self, path: str, body: Any = None, query_params: Optional[dict] = None): + return self._api_call(requests.put, path, body, query_params) - def get(self, path: str, body: Any): - return self._api_call(requests.get, path, body) + def get(self, path: str, body: Any = None, query_params: Optional[dict] = None): + return self._api_call(requests.get, path, body, query_params) - def delete(self, path: str, body: Any): - return self._api_call(requests.delete, path, body) + def delete(self, path: str, body: Any = None, query_params: Optional[dict] = None): + return self._api_call(requests.delete, path, body, query_params) @classmethod def localize(cls, timestamp: datetime) -> str: @@ -49,11 +49,18 @@ def localize(cls, timestamp: datetime) -> str: return timestamp.strftime("%Y-%m-%dT%H:%M:%S.%fZ") return timestamp.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S.%fZ") - def _api_call(self, request_func: Callable, path: str, body: Any): + def _api_call( + self, + request_func: Callable, + path: str, + body: Any, + query_params: Optional[dict] = None, + ): url = f"{self.base_url}/{path}" rsp = request_func( url, json=body, + params=query_params, headers={ "Content-Type": "application/json", "Authorization": f"Bearer {self.api_key}", diff --git a/src/gradient_labs/_knowledge_base_create.py b/src/gradient_labs/_knowledge_base_create.py new file mode 100644 index 0000000..94a71bd --- /dev/null +++ b/src/gradient_labs/_knowledge_base_create.py @@ -0,0 +1,27 @@ +from dataclasses import dataclass +from dataclasses_json import dataclass_json + +from ._http_client import HttpClient +from .knowledge_base import KnowledgeBase + + +@dataclass_json +@dataclass(frozen=True) +class CreateKnowledgeBaseParams: + """CreateKnowledgeBaseParams contains the parameters for creating a knowledge base.""" + + # id is your own identifier for this knowledge base. + id: str + + # name is the name of the knowledge base. + name: str + + +def create_knowledge_base( + *, client: HttpClient, params: CreateKnowledgeBaseParams +) -> KnowledgeBase: + """create_knowledge_base creates a new knowledge base. + + Note: requires an `Integration` or `Management` API key.""" + rsp = client.post(path="knowledge-bases", body=params.to_dict()) + return KnowledgeBase.from_dict(rsp) diff --git a/src/gradient_labs/_knowledge_base_list.py b/src/gradient_labs/_knowledge_base_list.py new file mode 100644 index 0000000..51c927a --- /dev/null +++ b/src/gradient_labs/_knowledge_base_list.py @@ -0,0 +1,22 @@ +from typing import List +from dataclasses import dataclass +from dataclasses_json import dataclass_json + +from ._http_client import HttpClient +from .knowledge_base import KnowledgeBase + + +@dataclass_json +@dataclass(frozen=True) +class KnowledgeBasesList: + """KnowledgeBasesList contains the list of your knowledge bases.""" + + knowledge_bases: List[KnowledgeBase] + + +def list_knowledge_bases(*, client: HttpClient) -> KnowledgeBasesList: + """list_knowledge_bases returns all of your knowledge bases. + + Note: requires an `Integration` or `Management` API key.""" + rsp = client.get(path="knowledge-bases") + return KnowledgeBasesList.from_dict(rsp) diff --git a/src/gradient_labs/_knowledge_base_read.py b/src/gradient_labs/_knowledge_base_read.py new file mode 100644 index 0000000..b54c93f --- /dev/null +++ b/src/gradient_labs/_knowledge_base_read.py @@ -0,0 +1,10 @@ +from ._http_client import HttpClient +from .knowledge_base import KnowledgeBase + + +def read_knowledge_base(*, client: HttpClient, knowledge_base_id: str) -> KnowledgeBase: + """read_knowledge_base retrieves a knowledge base by your own ID for it. + + Note: requires an `Integration` or `Management` API key.""" + rsp = client.get(path=f"knowledge-bases/{knowledge_base_id}") + return KnowledgeBase.from_dict(rsp) diff --git a/src/gradient_labs/_knowledge_base_update.py b/src/gradient_labs/_knowledge_base_update.py new file mode 100644 index 0000000..34a3303 --- /dev/null +++ b/src/gradient_labs/_knowledge_base_update.py @@ -0,0 +1,26 @@ +from dataclasses import dataclass +from dataclasses_json import dataclass_json + +from ._http_client import HttpClient +from .knowledge_base import KnowledgeBase + + +@dataclass_json +@dataclass(frozen=True) +class UpdateKnowledgeBaseParams: + """UpdateKnowledgeBaseParams contains the parameters for updating a knowledge base.""" + + # name is the new name of the knowledge base. + name: str + + +def update_knowledge_base( + *, client: HttpClient, knowledge_base_id: str, params: UpdateKnowledgeBaseParams +) -> KnowledgeBase: + """update_knowledge_base renames a knowledge base. + + Note: requires an `Integration` or `Management` API key.""" + rsp = client.post( + path=f"knowledge-bases/{knowledge_base_id}", body=params.to_dict() + ) + return KnowledgeBase.from_dict(rsp) diff --git a/src/gradient_labs/_note_create.py b/src/gradient_labs/_note_create.py index b92a185..4c1690f 100644 --- a/src/gradient_labs/_note_create.py +++ b/src/gradient_labs/_note_create.py @@ -1,4 +1,4 @@ -from typing import Optional +from typing import Dict, List, Optional from datetime import datetime from dataclasses import dataclass from dataclasses_json import dataclass_json @@ -31,6 +31,17 @@ class CreateNoteParams: # EndTime is when the note is no longer relevant. end_time: Optional[datetime] = None + # Attributes says which customers the note applies to, as a map from attribute key + # to the attribute values it applies to. The keys and values must match the + # attributes defined for your company. Leave it out for a note that applies to + # every conversation. + attributes: Optional[Dict[str, List[str]]] = None + + # knowledge_base_ids optionally names the knowledge bases this note belongs to. The + # list cannot be empty. If you leave it out, the note goes into the default + # "public-api" knowledge base. + knowledge_base_ids: Optional[List[str]] = None + def create_note(*, client: HttpClient, params: CreateNoteParams) -> Note: """create_note creates a new note.""" @@ -46,6 +57,10 @@ def create_note(*, client: HttpClient, params: CreateNoteParams) -> Note: body["start_time"] = HttpClient.localize(params.start_time) if params.end_time is not None: body["end_time"] = HttpClient.localize(params.end_time) + if params.attributes is not None: + body["attributes"] = params.attributes + if params.knowledge_base_ids is not None: + body["knowledge_base_ids"] = params.knowledge_base_ids rsp = client.post(path="notes", body=body) return Note.from_dict(rsp) diff --git a/src/gradient_labs/_note_list.py b/src/gradient_labs/_note_list.py new file mode 100644 index 0000000..04a4a5c --- /dev/null +++ b/src/gradient_labs/_note_list.py @@ -0,0 +1,43 @@ +from typing import List, Optional +from dataclasses import dataclass +from dataclasses_json import dataclass_json + +from ._http_client import HttpClient +from ._pagination import ForwardPaginationInfo +from .note import Note + + +@dataclass_json +@dataclass(frozen=True) +class NoteListParams: + """NoteListParams contains the parameters for listing notes.""" + + # cursor is the page to fetch, from `pagination.next` in a previous response. + # Leave it out to get the first page. + cursor: Optional[str] = None + + +@dataclass_json +@dataclass(frozen=True) +class NoteListResponse: + """NoteListResponse is a page of notes.""" + + # notes are the notes on this page. + notes: List[Note] + + # pagination contains the cursor for the next page, if there is one. + pagination: ForwardPaginationInfo + + +def list_notes( + *, client: HttpClient, params: Optional[NoteListParams] = None +) -> NoteListResponse: + """list_notes returns a page of the notes created by your company. + + Note: requires a `Management` API key.""" + query_params = {} + if params is not None and params.cursor is not None: + query_params["cursor"] = params.cursor + + rsp = client.get(path="notes", query_params=query_params) + return NoteListResponse.from_dict(rsp) diff --git a/src/gradient_labs/_note_read.py b/src/gradient_labs/_note_read.py new file mode 100644 index 0000000..0ba0bfc --- /dev/null +++ b/src/gradient_labs/_note_read.py @@ -0,0 +1,10 @@ +from ._http_client import HttpClient +from .note import Note + + +def read_note(*, client: HttpClient, note_id: str) -> Note: + """read_note retrieves a note by your own ID for it. + + Note: requires a `Management` API key.""" + rsp = client.get(path=f"notes/{note_id}") + return Note.from_dict(rsp) diff --git a/src/gradient_labs/_note_update.py b/src/gradient_labs/_note_update.py index 59a4b48..633f7e5 100644 --- a/src/gradient_labs/_note_update.py +++ b/src/gradient_labs/_note_update.py @@ -1,4 +1,4 @@ -from typing import Optional +from typing import Dict, List, Optional from datetime import datetime from dataclasses import dataclass from dataclasses_json import dataclass_json @@ -28,6 +28,17 @@ class UpdateNoteParams: # EndTime is when the note is no longer relevant. end_time: Optional[datetime] = None + # Attributes says which customers the note applies to, as a map from attribute key + # to the attribute values it applies to. The keys and values must match the + # attributes defined for your company. Leave it out for a note that applies to + # every conversation. + attributes: Optional[Dict[str, List[str]]] = None + + # knowledge_base_ids optionally names the knowledge bases this note belongs to. The + # list cannot be empty. If you leave it out, the note goes into the default + # "public-api" knowledge base. + knowledge_base_ids: Optional[List[str]] = None + def update_note(*, client: HttpClient, note_id: str, params: UpdateNoteParams) -> Note: """update_note updates an existing note's contents.""" @@ -42,6 +53,10 @@ def update_note(*, client: HttpClient, note_id: str, params: UpdateNoteParams) - body["start_time"] = HttpClient.localize(params.start_time) if params.end_time is not None: body["end_time"] = HttpClient.localize(params.end_time) + if params.attributes is not None: + body["attributes"] = params.attributes + if params.knowledge_base_ids is not None: + body["knowledge_base_ids"] = params.knowledge_base_ids rsp = client.post(path=f"notes/{note_id}", body=body) return Note.from_dict(rsp) diff --git a/src/gradient_labs/_pagination.py b/src/gradient_labs/_pagination.py index 6352776..97b2fa5 100644 --- a/src/gradient_labs/_pagination.py +++ b/src/gradient_labs/_pagination.py @@ -5,9 +5,12 @@ @dataclass_json @dataclass(frozen=True) -class PaginationInfo: +class ForwardPaginationInfo: # next is a cursor to retrieve the next page of results. next: Optional[str] = None - # prev is a cursor to retrieve the previous page of results. + +@dataclass_json +@dataclass(frozen=True) +class PaginationInfo(ForwardPaginationInfo): prev: Optional[str] = None diff --git a/src/gradient_labs/_procedure_list.py b/src/gradient_labs/_procedure_list.py index 33e7cce..4fb890f 100644 --- a/src/gradient_labs/_procedure_list.py +++ b/src/gradient_labs/_procedure_list.py @@ -31,11 +31,11 @@ class ProcedureListResponse: def list_procedures( *, client: HttpClient, params: ProcedureListParams ) -> ProcedureListResponse: - path = "procedures" + query_params = {} if params.cursor is not None: - path = f"{path}?cursor={params.cursor}" + query_params["cursor"] = params.cursor if params.status is not None: - path = f"{path}?status={params.status}" + query_params["status"] = ProcedureStatus(params.status).value - rsp = client.get(path=path, body={}) + rsp = client.get(path="procedures", query_params=query_params) return ProcedureListResponse.from_dict(rsp) diff --git a/src/gradient_labs/_procedure_set_limit.py b/src/gradient_labs/_procedure_set_limit.py index 82aa687..ed97184 100644 --- a/src/gradient_labs/_procedure_set_limit.py +++ b/src/gradient_labs/_procedure_set_limit.py @@ -26,4 +26,4 @@ def set_procedure_limit( path=f"procedure/{procedure_id}/limit", body=params.to_dict(), ) - return Procedure.from_dict(body) + return Procedure.from_dict(body["procedure"]) diff --git a/src/gradient_labs/_procedure_version_list.py b/src/gradient_labs/_procedure_version_list.py index 08da342..06f8f06 100644 --- a/src/gradient_labs/_procedure_version_list.py +++ b/src/gradient_labs/_procedure_version_list.py @@ -1,6 +1,6 @@ -from dataclasses import dataclass +from dataclasses import dataclass, field from typing import List -from dataclasses_json import dataclass_json +from dataclasses_json import dataclass_json, config from ._http_client import HttpClient from .procedure import ProcedureVersion @@ -11,7 +11,8 @@ class ListProcedureVersionsResponse: """Response containing list of procedure versions.""" - versions: List[ProcedureVersion] + # The API names this field `Versions`. + versions: List[ProcedureVersion] = field(metadata=config(field_name="Versions")) def list_procedure_versions( @@ -20,8 +21,5 @@ def list_procedure_versions( """list_procedure_versions lists existing non-ephemeral versions of a procedure. Note: requires a `Management` API key.""" - body = client.get( - path=f"procedures/{procedure_id}/versions", - body={}, - ) + body = client.get(path=f"procedures/{procedure_id}/versions") return ListProcedureVersionsResponse.from_dict(body) diff --git a/src/gradient_labs/_resource_source_create.py b/src/gradient_labs/_resource_source_create.py index 56d451e..8228339 100644 --- a/src/gradient_labs/_resource_source_create.py +++ b/src/gradient_labs/_resource_source_create.py @@ -34,6 +34,12 @@ class CreateResourceSourceParams: # AttributeDescriptions optional raw attribute-level descriptions. attribute_descriptions: Optional[Dict[str, str]] = None + # branch_id optionally makes the change on a git-backed branch, by its ID. + branch_id: Optional[str] = None + + # branch_name optionally makes the change on a git-backed branch, by its name. + branch_name: Optional[str] = None + def create_resource_source( *, client: HttpClient, params: CreateResourceSourceParams @@ -55,5 +61,9 @@ def create_resource_source( if params.attribute_descriptions is not None: body["attribute_descriptions"] = params.attribute_descriptions + if params.branch_id is not None: + body["branch_id"] = params.branch_id + if params.branch_name is not None: + body["branch_name"] = params.branch_name rsp = client.post(path="resource-sources", body=body) return ResourceSource.from_dict(rsp) diff --git a/src/gradient_labs/_resource_source_update.py b/src/gradient_labs/_resource_source_update.py index d7e8591..26eabf8 100644 --- a/src/gradient_labs/_resource_source_update.py +++ b/src/gradient_labs/_resource_source_update.py @@ -1,4 +1,4 @@ -from typing import Optional, Dict, Any +from typing import Optional, Dict, Any, TypedDict from dataclasses import dataclass from dataclasses_json import dataclass_json @@ -11,6 +11,10 @@ ) +class ResourceSourceSchemaUpdate(TypedDict, total=False): + raw: Dict[str, Any] + + @dataclass_json @dataclass(frozen=True) class UpdateResourceSourceParams: @@ -41,7 +45,7 @@ class UpdateResourceSourceParams: attribute_descriptions: Optional[Dict[str, str]] = None # Schema is the schema of the resource source. - schema: Optional[Any] = None + schema: Optional[ResourceSourceSchemaUpdate] = None def update_resource_source( diff --git a/src/gradient_labs/_resource_type_create.py b/src/gradient_labs/_resource_type_create.py index 1f2e93f..1dec20a 100644 --- a/src/gradient_labs/_resource_type_create.py +++ b/src/gradient_labs/_resource_type_create.py @@ -29,6 +29,12 @@ class CreateResourceTypeParams: # IsEnabled indicates whether the resource type should be enabled. is_enabled: Optional[bool] = None + # branch_id optionally makes the change on a git-backed branch, by its ID. + branch_id: Optional[str] = None + + # branch_name optionally makes the change on a git-backed branch, by its name. + branch_name: Optional[str] = None + def create_resource_type( *, client: HttpClient, params: CreateResourceTypeParams @@ -49,5 +55,9 @@ def create_resource_type( if params.is_enabled is not None: body["is_enabled"] = params.is_enabled + if params.branch_id is not None: + body["branch_id"] = params.branch_id + if params.branch_name is not None: + body["branch_name"] = params.branch_name rsp = client.post(path="resource-types", body=body) return ResourceType.from_dict(rsp) diff --git a/src/gradient_labs/_secret_write.py b/src/gradient_labs/_secret_write.py index 220235d..05d2c90 100644 --- a/src/gradient_labs/_secret_write.py +++ b/src/gradient_labs/_secret_write.py @@ -4,6 +4,7 @@ from dataclasses_json import dataclass_json from ._http_client import HttpClient +from ._without_none import without_none from .secret import Secret, RefreshMechanismHTTP @@ -38,7 +39,11 @@ def write_secret(*, client: HttpClient, params: WriteSecretParams) -> Secret: if params.expiry is not None: body["expiry"] = HttpClient.localize(params.expiry) if params.refresh_mechanism_http is not None: - body["refresh_mechanism_http"] = params.refresh_mechanism_http.to_dict() + refresh = without_none(params.refresh_mechanism_http.to_dict()) + retry = refresh["request_definition"].get("retry") + if retry is not None: + retry.pop("max_attempts", None) + body["refresh_mechanism_http"] = refresh rsp = client.put(path=f"secrets/{params.name}", body=body) return Secret.from_dict(rsp) diff --git a/src/gradient_labs/_tool_create.py b/src/gradient_labs/_tool_create.py index 3cd9eb0..342a4c2 100644 --- a/src/gradient_labs/_tool_create.py +++ b/src/gradient_labs/_tool_create.py @@ -1,4 +1,5 @@ from ._http_client import HttpClient +from ._without_none import without_none from .tool import Tool @@ -6,5 +7,8 @@ def create_tool(*, client: HttpClient, params: Tool) -> Tool: """create_tool creates a new tool. Note: requires a `Management` API key.""" - rsp = client.post(path="tools", body=params.to_dict()) + body = without_none(params.to_dict()) + body.pop("id", None) + body.pop("mcp", None) + rsp = client.post(path="tools", body=body) return Tool.from_dict(rsp) diff --git a/src/gradient_labs/_tool_execute.py b/src/gradient_labs/_tool_execute.py index c10cb26..1b43272 100644 --- a/src/gradient_labs/_tool_execute.py +++ b/src/gradient_labs/_tool_execute.py @@ -4,6 +4,7 @@ from dataclasses_json import dataclass_json from ._http_client import HttpClient +from ._without_none import without_none @dataclass_json @@ -27,6 +28,10 @@ class ToolExecuteParams: # arguments to execute the tool with. arguments: Optional[List[Argument]] = field(default_factory=lambda: []) + # token is an optional conversation-scoped token. When the tool sends one in its + # authorization header, the tool call only succeeds if you provide it here. + token: Optional[str] = None + @dataclass_json @dataclass(frozen=True) @@ -47,5 +52,7 @@ def execute_tool(*, client: HttpClient, params: ToolExecuteParams) -> ToolExecut """execute_tool executes a tool. Note: requires a `Management` API key.""" - rsp = client.post(path=f"tools/{params.id}/execute", body=params.to_dict()) + body = without_none(params.to_dict()) + body.pop("id") + rsp = client.post(path=f"tools/{params.id}/execute", body=body) return ToolExecuteResult.from_dict(rsp) diff --git a/src/gradient_labs/_tool_read.py b/src/gradient_labs/_tool_read.py index 17ac69e..930d7bc 100644 --- a/src/gradient_labs/_tool_read.py +++ b/src/gradient_labs/_tool_read.py @@ -1,12 +1,20 @@ +from typing import Optional + from ._http_client import HttpClient from .tool import Tool -def read_tool(*, client: HttpClient, tool_id: str) -> Tool: - """read_tool retrieves a new tool. +def read_tool( + *, client: HttpClient, tool_id: str, version: Optional[int] = None +) -> Tool: + """read_tool retrieves a tool. Leave version out to read its current version. Note: requires a `Management` API key.""" + query_params = {} + if version is not None: + query_params["version"] = version + rsp = client.get( path=f"tools/{tool_id}", - body={}, + query_params=query_params, ) return Tool.from_dict(rsp) diff --git a/src/gradient_labs/_tool_update.py b/src/gradient_labs/_tool_update.py index 20f84a7..d9c8e1e 100644 --- a/src/gradient_labs/_tool_update.py +++ b/src/gradient_labs/_tool_update.py @@ -1,14 +1,16 @@ from ._http_client import HttpClient +from ._without_none import without_none from .tool import Tool, ToolUpdateParams def update_tool(*, client: HttpClient, params: ToolUpdateParams) -> Tool: - """update_tool updates an existing tool. It allows callers to convert mock tools - into real tools, but not the other way around. + """Update the supplied fields of a tool. Note: requires a `Management` API key.""" + body = without_none(params.to_dict()) + body.pop("id") rsp = client.put( path=f"tools/{params.id}", - body=params.to_dict(), + body=body, ) return Tool.from_dict(rsp) diff --git a/src/gradient_labs/_voice_call_context_read.py b/src/gradient_labs/_voice_call_context_read.py index 3e0cbc3..7b9ef58 100644 --- a/src/gradient_labs/_voice_call_context_read.py +++ b/src/gradient_labs/_voice_call_context_read.py @@ -19,16 +19,16 @@ def read_voice_call_context( phone_number: str, params: Optional[VoiceCallContextReadParams] = None, ) -> VoiceCallContext: - path = f"voice/latest-call-context/{phone_number}" - query_parts = [] + query_params = {} if params is not None: if params.lookback_seconds is not None: - query_parts.append(f"lookback_seconds={params.lookback_seconds}") + query_params["lookback_seconds"] = params.lookback_seconds if params.include_large_fields is not None: - query_parts.append( - f"include_large_fields={str(params.include_large_fields).lower()}" - ) - if query_parts: - path = f"{path}?{'&'.join(query_parts)}" - rsp = client.get(path=path, body={}) + query_params["include_large_fields"] = str( + params.include_large_fields + ).lower() + rsp = client.get( + path=f"voice/latest-call-context/{phone_number}", + query_params=query_params, + ) return VoiceCallContext.from_dict(rsp) diff --git a/src/gradient_labs/_without_none.py b/src/gradient_labs/_without_none.py new file mode 100644 index 0000000..59d72f2 --- /dev/null +++ b/src/gradient_labs/_without_none.py @@ -0,0 +1,11 @@ +from typing import Any + + +def without_none(value: Any) -> Any: + """without_none drops None values from nested dicts and lists, so that unset + optional fields are left out of a request instead of sent as null.""" + if isinstance(value, dict): + return {k: without_none(v) for k, v in value.items() if v is not None} + if isinstance(value, list): + return [without_none(v) for v in value] + return value diff --git a/src/gradient_labs/article.py b/src/gradient_labs/article.py index ca64384..2df6f99 100644 --- a/src/gradient_labs/article.py +++ b/src/gradient_labs/article.py @@ -25,6 +25,10 @@ class Visibility(str, Enum): # that customers do not have access to. INTERNAL: str = "internal" + # UNKNOWN is only ever returned by the API, when it cannot tell who can view the + # item. Do not send it. + UNKNOWN: str = "unknown" + class PublicationStatus(str, Enum): """PublicationStatus describes the status of a help article.""" @@ -35,3 +39,9 @@ class PublicationStatus(str, Enum): # PUBLISHED means that the article is published. PUBLISHED: str = "published" + + # DELETED means that the article has been deleted. + DELETED: str = "deleted" + + # EXCLUDED means that the article is kept out of the AI agent's knowledge. + EXCLUDED: str = "excluded" diff --git a/src/gradient_labs/back_office_task.py b/src/gradient_labs/back_office_task.py index 6d5d640..0cfad5a 100644 --- a/src/gradient_labs/back_office_task.py +++ b/src/gradient_labs/back_office_task.py @@ -5,6 +5,8 @@ from dataclasses_json import dataclass_json, config from marshmallow import fields +from ._datetime import parse_datetime + class BackOfficeTaskStatus(str, Enum): PENDING = "pending" @@ -32,7 +34,7 @@ class BackOfficeTaskAttachment: # Reusable marshmallow config for optional datetime fields; avoids repeating allow_none/load_default. _optional_datetime_config = config( encoder=lambda x: x.isoformat() if x is not None else None, - decoder=lambda x: datetime.fromisoformat(x) if x is not None else None, + decoder=lambda x: parse_datetime(x) if x is not None else None, mm_field=fields.DateTime(format="iso", allow_none=True, load_default=None), ) @@ -47,7 +49,7 @@ class BackOfficeTask: created: datetime = field( metadata=config( encoder=datetime.isoformat, - decoder=datetime.fromisoformat, + decoder=parse_datetime, mm_field=fields.DateTime(format="iso"), ) ) diff --git a/src/gradient_labs/client.py b/src/gradient_labs/client.py index a9c7e6b..dcf6913 100644 --- a/src/gradient_labs/client.py +++ b/src/gradient_labs/client.py @@ -1,3 +1,4 @@ +import warnings from typing import Optional, List from ._article_delete import delete_article @@ -18,6 +19,7 @@ from ._conversation_rate import rate_conversation, RatingParams from ._conversation_resume import resume_conversation, ResumeParams from ._conversation_read import read_conversation, ReadParams +from ._conversation_read_deprecated import read_conversation_deprecated from ._conversation_delete import delete_conversation from ._conversation_start import ( start_conversation, @@ -78,7 +80,33 @@ from ._tool_read import read_tool from ._tool_update import update_tool +from ._customer_memories_list import list_customer_memories +from ._customer_memories_batch_create import ( + batch_create_customer_memories, + BatchCreateCustomerMemoriesDeprecatedParams, + BatchCreateCustomerMemoryDeprecated as BatchCreateCustomerMemoryDeprecated, +) +from ._customer_memories_batch_create_v2 import ( + batch_create_customer_memories_v2, + BatchCreateCustomerMemoriesParams, + BatchCreateCustomerMemory as BatchCreateCustomerMemory, +) +from .customer_memory import CustomerMemoriesList + +from ._file_upload_begin import begin_file_upload, BeginFileUploadParams +from ._file_list import list_files, FileListParams, FileListResponse +from ._file_create import create_file, CreateFileParams +from .file import File, FileUpload + +from ._knowledge_base_list import list_knowledge_bases, KnowledgeBasesList +from ._knowledge_base_create import create_knowledge_base, CreateKnowledgeBaseParams +from ._knowledge_base_read import read_knowledge_base +from ._knowledge_base_update import update_knowledge_base, UpdateKnowledgeBaseParams +from .knowledge_base import KnowledgeBase + from ._note_create import create_note, CreateNoteParams +from ._note_list import list_notes, NoteListParams, NoteListResponse +from ._note_read import read_note from ._note_delete import delete_note from ._note_update import update_note, UpdateNoteParams from ._note_set_status import set_note_status, SetNoteStatusParams @@ -324,6 +352,21 @@ def read_conversation( params=params, ) + def read_conversation_deprecated(self, *, conversation_id: str) -> Conversation: + """Retrieves the conversation from the deprecated `GET /conversations/{id}` + endpoint. + + Deprecated: use read_conversation.""" + warnings.warn( + "read_conversation_deprecated is deprecated: use read_conversation", + DeprecationWarning, + stacklevel=2, + ) + return read_conversation_deprecated( + client=self.http_client, + conversation_id=conversation_id, + ) + def delete_conversation(self, *, conversation_id: str) -> None: """delete_conversation deletes a conversation and its associated messages, events and other data. @@ -623,13 +666,14 @@ def execute_tool(self, *, params: ToolExecuteParams) -> ToolExecuteResult: params=params, ) - def read_tool(self, *, tool_id: str) -> Tool: - """read_tool retrieves a new tool. + def read_tool(self, *, tool_id: str, version: Optional[int] = None) -> Tool: + """read_tool retrieves a tool. Leave version out to read its current version. Note: requires a `Management` API key.""" return read_tool( client=self.http_client, tool_id=tool_id, + version=version, ) def list_tools(self) -> List[Tool]: @@ -641,8 +685,7 @@ def list_tools(self) -> List[Tool]: ) def update_tool(self, *, params: ToolUpdateParams) -> Tool: - """update_tool updates an existing tool. It allows callers to convert mock tools - into real tools, but not the other way around. + """Update the supplied fields of a tool. Note: requires a `Management` API key.""" return update_tool( @@ -650,6 +693,125 @@ def update_tool(self, *, params: ToolUpdateParams) -> Tool: params=params, ) + def list_customer_memories(self, *, customer_id: str) -> CustomerMemoriesList: + """list_customer_memories lists all memories retained for a customer. + + Experimental. Requires an `Integration` API key.""" + return list_customer_memories( + client=self.http_client, + customer_id=customer_id, + ) + + def batch_create_customer_memories( + self, + *, + customer_id: str, + params: BatchCreateCustomerMemoriesDeprecatedParams, + ) -> None: + """batch_create_customer_memories stores memories about a customer through the + deprecated `POST /customers/{customer_id}/memories` endpoint. + + Deprecated: use batch_create_customer_memories_v2. + + Experimental. Requires an `Integration` API key.""" + warnings.warn( + "batch_create_customer_memories is deprecated: use batch_create_customer_memories_v2", + DeprecationWarning, + stacklevel=2, + ) + batch_create_customer_memories( + client=self.http_client, + customer_id=customer_id, + params=params, + ) + + def batch_create_customer_memories_v2( + self, + *, + customer_id: str, + params: BatchCreateCustomerMemoriesParams, + ) -> None: + """batch_create_customer_memories_v2 stores memories about a customer. + + Experimental. Requires an `Integration` API key.""" + batch_create_customer_memories_v2( + client=self.http_client, + customer_id=customer_id, + params=params, + ) + + def begin_file_upload( + self, *, params: Optional[BeginFileUploadParams] = None + ) -> FileUpload: + """begin_file_upload starts uploading a file to your workspace. PUT the file to + the returned upload_url, then call create_file with the upload_id. + + Note: requires a `Management` API key.""" + return begin_file_upload( + client=self.http_client, + params=params, + ) + + def list_files( + self, *, params: Optional[FileListParams] = None + ) -> FileListResponse: + """list_files returns a page of the files uploaded to your workspace. + + Note: requires a `Management` API key.""" + return list_files( + client=self.http_client, + params=params, + ) + + def create_file(self, *, params: CreateFileParams) -> File: + """create_file turns an uploaded file into a workspace file. + + Note: requires a `Management` API key.""" + return create_file( + client=self.http_client, + params=params, + ) + + def list_knowledge_bases(self) -> KnowledgeBasesList: + """list_knowledge_bases returns all of your knowledge bases. + + Note: requires an `Integration` or `Management` API key.""" + return list_knowledge_bases( + client=self.http_client, + ) + + def create_knowledge_base( + self, *, params: CreateKnowledgeBaseParams + ) -> KnowledgeBase: + """create_knowledge_base creates a new knowledge base. + + Note: requires an `Integration` or `Management` API key.""" + return create_knowledge_base( + client=self.http_client, + params=params, + ) + + def read_knowledge_base(self, *, knowledge_base_id: str) -> KnowledgeBase: + """read_knowledge_base retrieves a knowledge base by your own ID for it. + + Note: requires an `Integration` or `Management` API key.""" + return read_knowledge_base( + client=self.http_client, + knowledge_base_id=knowledge_base_id, + ) + + def update_knowledge_base( + self, *, knowledge_base_id: str, params: UpdateKnowledgeBaseParams + ) -> KnowledgeBase: + """update_knowledge_base renames a knowledge base. + + Note: requires an `Integration` or `Management` API key.""" + return update_knowledge_base( + client=self.http_client, + knowledge_base_id=knowledge_base_id, + params=params, + ) + def parse_webhook(self, payload: str, signature_header: str) -> WebhookEvent: """parse_webhook parses a webhook event.""" return Webhook.parse_event( @@ -665,6 +827,26 @@ def create_note(self, *, params: CreateNoteParams) -> Note: params=params, ) + def list_notes( + self, *, params: Optional[NoteListParams] = None + ) -> NoteListResponse: + """list_notes returns a page of the notes created by your company. + + Note: requires a `Management` API key.""" + return list_notes( + client=self.http_client, + params=params, + ) + + def read_note(self, *, note_id: str) -> Note: + """read_note retrieves a note by your own ID for it. + + Note: requires a `Management` API key.""" + return read_note( + client=self.http_client, + note_id=note_id, + ) + def update_note(self, *, note_id: str, params: UpdateNoteParams) -> Note: """update_note updates an existing note's contents.""" return update_note( diff --git a/src/gradient_labs/conversation.py b/src/gradient_labs/conversation.py index 57cb08b..2e30d2e 100644 --- a/src/gradient_labs/conversation.py +++ b/src/gradient_labs/conversation.py @@ -6,6 +6,10 @@ from marshmallow import fields from typing import Any, Dict +from ._datetime import parse_datetime + +from .back_office_task import BackOfficeTask + class ParticipantType(str, Enum): """A participant type identifies the type of user who has @@ -31,8 +35,7 @@ class AttachmentType(str, Enum): that a customer has uploaded into the conversation.""" IMAGE: str = "image" - DOCUMENT: str = "document" - AUDIO: str = "audio" + FILE: str = "file" class ConversationEventType(str, Enum): @@ -83,14 +86,14 @@ class Conversation: created: datetime = field( metadata=config( encoder=datetime.isoformat, - decoder=datetime.fromisoformat, + decoder=parse_datetime, mm_field=fields.DateTime(format="iso"), ) ) updated: datetime = field( metadata=config( encoder=datetime.isoformat, - decoder=datetime.fromisoformat, + decoder=parse_datetime, mm_field=fields.DateTime(format="iso"), ) ) @@ -109,10 +112,34 @@ class Conversation: @dataclass_json @dataclass(frozen=True) class Attachment: + # type of file that was uploaded. type: AttachmentType + + # file_name is the name of the file that was uploaded, or an + # adequate placeholder for that name, which can be shown to reviewers. file_name: str + # url is the publicly accessible URL where the attachment can be downloaded + # from. This should be a fully qualified URL. If not given, the AI agent will + # only know that an attachment exists, but will be unable to process it. + url: Optional[str] = None + + # summary is an optional short summary of the attachment. This is only intended + # to be used if you cannot give us access to the raw attachment, but can + # run your own LLM completions on the attachment and send us a description instead. + # + # If a summary or description is provided, then there must be no URL. + summary: Optional[str] = None + # description is an optional description of the attachment. This is only intended + # to be used if you cannot give us access to the raw attachment, but can + # run your own LLM completions on the attachment and send us a description instead. + # + # Chat to us first before using it! + description: Optional[str] = None + + +@dataclass_json @dataclass(frozen=True) class WebhookConversation: """ @@ -129,6 +156,17 @@ class WebhookConversation: The customer's assigned identifier. """ + customer_source: Optional[str] = None + """ + The support platform the customer comes from, such as `intercom`. Only + present on action.execute events. + """ + + metadata: Optional[Any] = None + """ + Extra details about the conversation. Only present on action.execute events. + """ + @dataclass_json @dataclass(frozen=True) @@ -214,15 +252,33 @@ class ConversationFinishedEvent: Details of the conversation the event relates to. """ + intent: Optional[str] = None + """ + Intent is the most recent intent that was classified from the customer's conversation, if any. + """ + + reason_code: Optional[str] = None + """ + reason_code is the code that describes why the conversation finished, if known. + """ + @dataclass_json @dataclass(frozen=True) -class ActionExecuteEvent: - conversation: WebhookConversation +class WebhookBackOfficeTask: """ - Details of the conversation the event relates to. + Details of the back-office task the event relates to. + """ + + id: str """ + The back-office task's identifier. + """ + +@dataclass_json +@dataclass(frozen=True) +class ActionExecuteEvent: action: str """ The action's given identifier. @@ -233,6 +289,107 @@ class ActionExecuteEvent: Parameters the agent has generated for this action. """ + conversation: Optional[WebhookConversation] = None + """ + Details of the conversation the event relates to. Not set when the action + runs for a back-office task. + """ + + back_office_task: Optional[WebhookBackOfficeTask] = None + """ + Details of the back-office task the event relates to. Only set when the + action runs for a back-office task. + """ + + +@dataclass_json +@dataclass(frozen=True) +class BackOfficeTaskCompleteEvent: + """ + An event that says a back-office task has completed. + """ + + back_office_task: BackOfficeTask + """ + The back-office task. + """ + + +@dataclass_json +@dataclass(frozen=True) +class BackOfficeTaskHandOffEvent: + """ + An event that says a back-office task has been handed off to a human. + """ + + back_office_task: BackOfficeTask + """ + The back-office task. + """ + + +@dataclass_json +@dataclass(frozen=True) +class BackOfficeTaskFailEvent: + """ + An event that says a back-office task has failed. + """ + + back_office_task: BackOfficeTask + """ + The back-office task. + """ + + +@dataclass_json +@dataclass(frozen=True) +class ConversationStartEvent: + """ + An event asking you to open an outbound conversation with a customer. + Answer it with a ConversationStartResponse. + """ + + customer_id: str + """ + Your identifier for the customer to contact. + """ + + channel: ConversationChannel + """ + How to contact the customer. + """ + + body: str + """ + The first message to send to the customer. + """ + + subject: str + """ + The subject line, for email conversations. Empty on other channels. + """ + + initiator_id: str + """ + Who started the outbound conversation: `public-api` when you started it + through the API. Otherwise the Gradient Labs ID of the conversation or + back-office task that started it. + """ + + +@dataclass_json +@dataclass(frozen=True) +class ConversationStartResponse: + """ + The body to answer a conversation.start event with. + """ + + conversation_id: str + """ + Your identifier for the conversation you opened. Use it in later API calls + about this conversation. + """ + @dataclass_json @dataclass(frozen=True) @@ -253,9 +410,7 @@ class WebhookEvent: """ timestamp: datetime = field( - metadata=config( - decoder=datetime.fromisoformat, mm_field=fields.DateTime(format="iso") - ) + metadata=config(decoder=parse_datetime, mm_field=fields.DateTime(format="iso")) ) """ Time at which this event was generated. diff --git a/src/gradient_labs/customer_memory.py b/src/gradient_labs/customer_memory.py new file mode 100644 index 0000000..f5a979f --- /dev/null +++ b/src/gradient_labs/customer_memory.py @@ -0,0 +1,44 @@ +from typing import Any, List, Optional +from datetime import datetime +from dataclasses import dataclass, field +from dataclasses_json import dataclass_json + +from ._datetime import datetime_config + + +@dataclass_json +@dataclass(frozen=True) +class CustomerMemoryType: + """CustomerMemoryType is the customer-defined category of a memory.""" + + # name is the name of the category. `support_conversation` is reserved for Gradient Labs. + name: str + + # description is an optional description of the category. + description: Optional[str] = None + + +@dataclass_json +@dataclass(frozen=True) +class CustomerMemory: + """CustomerMemory is something remembered about a customer.""" + + # external_id is your own identifier for the memory. + external_id: str + + # custom_type is the category of the memory. + custom_type: CustomerMemoryType + + # created_at is when the memory's underlying event occurred. + created_at: datetime = field(metadata=datetime_config) + + # data is the memory's payload, any JSON value. + data: Any + + +@dataclass_json +@dataclass(frozen=True) +class CustomerMemoriesList: + """CustomerMemoriesList contains all memories retained for a customer.""" + + memories: List[CustomerMemory] diff --git a/src/gradient_labs/file.py b/src/gradient_labs/file.py new file mode 100644 index 0000000..b093125 --- /dev/null +++ b/src/gradient_labs/file.py @@ -0,0 +1,56 @@ +from typing import Dict +from datetime import datetime +from dataclasses import dataclass, field +from dataclasses_json import dataclass_json + +from ._datetime import datetime_config + + +@dataclass_json +@dataclass(frozen=True) +class FileUpload: + """FileUpload tells you where to send a file's contents.""" + + # upload_id identifies the upload. Pass it to create_file once the file has + # been uploaded. + upload_id: str + + # upload_url is where to send the file, as an HTTP `PUT` with every header in headers. + upload_url: str + + # content_type is the `Content-Type` header the `PUT` must send. + content_type: str + + # headers are every header the `PUT` must send, `Content-Type` included. + headers: Dict[str, str] + + # expires_at is when upload_url stops accepting the file. + expires_at: datetime = field(metadata=datetime_config) + + # max_bytes is the largest file that can be uploaded, in bytes. + max_bytes: int + + +@dataclass_json +@dataclass(frozen=True) +class File: + """File is a file your company has uploaded.""" + + # id is the file's unique identifier. + id: str + + # ref is the file's name in a back-office test case, which lists it as `file_ref`. + # It never changes. + ref: str + + # file_name is the name the file was uploaded with, which the AI agent sees. + file_name: str + + # content_type is the file's type, read from its contents. + content_type: str + + # size_bytes is the file's size in bytes. + size_bytes: int + + # created is when the file was uploaded. + created: datetime = field(metadata=datetime_config) diff --git a/src/gradient_labs/handoff_target.py b/src/gradient_labs/handoff_target.py index 7f07d5c..f7a3436 100644 --- a/src/gradient_labs/handoff_target.py +++ b/src/gradient_labs/handoff_target.py @@ -1,3 +1,4 @@ +from typing import Optional from dataclasses import dataclass from dataclasses_json import dataclass_json @@ -11,3 +12,7 @@ class HandOffTarget: # name is the hand-off target’s name. name: str + + # ref is a short reference for this target that never changes. It is stored in + # lowercase and is unique within your company. + ref: Optional[str] = None diff --git a/src/gradient_labs/knowledge_base.py b/src/gradient_labs/knowledge_base.py new file mode 100644 index 0000000..7f9fef9 --- /dev/null +++ b/src/gradient_labs/knowledge_base.py @@ -0,0 +1,27 @@ +from datetime import datetime +from dataclasses import dataclass, field +from dataclasses_json import dataclass_json + +from ._datetime import datetime_config + + +@dataclass_json +@dataclass(frozen=True) +class KnowledgeBase: + """KnowledgeBase groups articles and notes, and controls which AI agents can use them.""" + + # gradient_labs_id is the internal Gradient Labs identifier for this knowledge base. + gradient_labs_id: str + + # id is your own identifier for this knowledge base. Name the knowledge base by + # this ID in `knowledge_base_ids` on articles and notes. + id: str + + # name is the name of the knowledge base. + name: str + + # created is when the knowledge base was created. + created: datetime = field(metadata=datetime_config) + + # updated is when the knowledge base was last updated. + updated: datetime = field(metadata=datetime_config) diff --git a/src/gradient_labs/note.py b/src/gradient_labs/note.py index a5fa693..f7c1c4a 100644 --- a/src/gradient_labs/note.py +++ b/src/gradient_labs/note.py @@ -1,9 +1,11 @@ -from typing import Optional +from typing import Dict, List, Optional from enum import Enum -from dataclasses import dataclass +from dataclasses import dataclass, field from dataclasses_json import dataclass_json from datetime import datetime +from ._datetime import optional_datetime_config + class NoteStatus(str, Enum): """NoteStatus describes whether a note is draft, live, or deleted.""" @@ -39,19 +41,27 @@ class Note: url: Optional[str] = None # StartTime is when the note becomes relevant. - valid_from: Optional[datetime] = None + valid_from: Optional[datetime] = field( + default=None, metadata=optional_datetime_config + ) # EndTime is when the note is no longer relevant. - valid_to: Optional[datetime] = None + valid_to: Optional[datetime] = field( + default=None, metadata=optional_datetime_config + ) # LastModifiedBy identifies who last modified the note. last_modified_by: str = "" # Created is when the note was created. - created: Optional[datetime] = None + created: Optional[datetime] = field(default=None, metadata=optional_datetime_config) # Updated is when the note was last updated. - updated: Optional[datetime] = None + updated: Optional[datetime] = field(default=None, metadata=optional_datetime_config) # Status describes whether the note is draft, live, or deleted. status: NoteStatus = NoteStatus.DRAFT + + # Attributes says which customers the note applies to, as a map from attribute key + # to the attribute values it applies to. Empty means every conversation. + attributes: Optional[Dict[str, List[str]]] = None diff --git a/src/gradient_labs/procedure.py b/src/gradient_labs/procedure.py index 4256eea..fd3b805 100644 --- a/src/gradient_labs/procedure.py +++ b/src/gradient_labs/procedure.py @@ -1,9 +1,12 @@ from enum import Enum +from typing import Optional from datetime import datetime from dataclasses import dataclass, field from dataclasses_json import dataclass_json, config from marshmallow import fields +from ._datetime import parse_datetime + class ProcedureStatus(str, Enum): """Identifies the publication status of a procedure.""" @@ -16,19 +19,17 @@ class ProcedureStatus(str, Enum): # conversations. LIVE: str = "live" + # UNSAVED indicates the procedure has changes that have not been saved yet. + UNSAVED: str = "unsaved" -@dataclass_json -@dataclass(frozen=True) -class UserDetails: - """UserDetails describes a procedure author.""" - - email: str + # ARCHIVED indicates the procedure has been archived. + ARCHIVED: str = "archived" @dataclass_json @dataclass(frozen=True) class Procedure: - """UserDetails describes a procedure author.""" + """A procedure and its publication status.""" # id uniquely identifies the procedure. id: str @@ -39,14 +40,11 @@ class Procedure: # status is the overall status of the procedure. status: ProcedureStatus - # author is the user who originally created the procedure. - author: UserDetails - # created is the time at which the procedure was originally created. created: datetime = field( metadata=config( encoder=datetime.isoformat, - decoder=datetime.fromisoformat, + decoder=parse_datetime, mm_field=fields.DateTime(format="iso"), ) ) @@ -57,7 +55,7 @@ class Procedure: updated: datetime = field( metadata=config( encoder=datetime.isoformat, - decoder=datetime.fromisoformat, + decoder=parse_datetime, mm_field=fields.DateTime(format="iso"), ) ) @@ -68,7 +66,10 @@ class Procedure: # max_daily_conversations is the maximum number of conversations that a procedure # can be used in on a given day, when it is rate limited. - max_daily_conversations: int + max_daily_conversations: Optional[int] = None + + # description says when the procedure applies. + description: Optional[str] = None @dataclass_json @@ -78,7 +79,9 @@ class GatedConfig: # max_daily_conversations is the maximum number of conversations per day # that can use the gated version. - max_daily_conversations: int + max_daily_conversations: int = field( + metadata=config(field_name="MaxDailyConversations") + ) @dataclass_json @@ -87,35 +90,38 @@ class ProcedureVersion: """A specific version of a procedure.""" # name is the user-given name of the procedure at the time of this version. - name: str + name: str = field(metadata=config(field_name="Name")) # description of the procedure at the time of this version. - description: str + description: str = field(metadata=config(field_name="Description")) # version is a numeric identifier for the version. It is incremented every # time a new version of the procedure is saved. - version: int + version: int = field(metadata=config(field_name="Version")) # author is the ID of the user who created this version of the procedure. - author: str + author: str = field(metadata=config(field_name="Author")) # created is the time at which this version of the procedure was created. created: datetime = field( metadata=config( + field_name="Created", encoder=datetime.isoformat, - decoder=datetime.fromisoformat, + decoder=parse_datetime, mm_field=fields.DateTime(format="iso"), ) ) # gated indicates whether the version is a gated version that is used before "live", # within the daily limit defined in gated_config. - gated: bool + gated: bool = field(metadata=config(field_name="Gated")) # gated_config defines how the gated version is limited. # gated_config is relevant only if gated == True. - gated_config: GatedConfig | None + gated_config: Optional[GatedConfig] = field( + metadata=config(field_name="GatedConfig") + ) # live indicates whether the version is the "production" version used by the agent by default, # if there are no gated versions or all gated versions have exceeded their limit. - live: bool + live: bool = field(metadata=config(field_name="Live")) diff --git a/src/gradient_labs/resource_source.py b/src/gradient_labs/resource_source.py index 06b3018..99bf0f5 100644 --- a/src/gradient_labs/resource_source.py +++ b/src/gradient_labs/resource_source.py @@ -1,9 +1,12 @@ -from typing import Optional, Dict, Any +from typing import Optional, Dict, Any, List from enum import Enum -from dataclasses import dataclass +from dataclasses import dataclass, field from dataclasses_json import dataclass_json from datetime import datetime +from ._datetime import datetime_config +from .resource_type import RefreshStrategy, Scope + class SourceType(str, Enum): """SourceType describes how the data is fetched from the source.""" @@ -72,6 +75,18 @@ class ResourceWebhookDefinition: name: str +@dataclass_json +@dataclass(frozen=True) +class ResourceManagedDefinition: + """ResourceManagedDefinition describes a source that Gradient Labs manages for you.""" + + # Enabled is whether the managed source is switched on. + enabled: bool + + # Key identifies the managed source. + key: str + + @dataclass_json @dataclass class ResourceSource: @@ -88,10 +103,10 @@ class ResourceSource: source_type: SourceType # Created is the timestamp when the resource source was created. - created: datetime + created: datetime = field(metadata=datetime_config) # Updated is the timestamp when the resource source was last updated. - updated: datetime + updated: datetime = field(metadata=datetime_config) # Description optional free-text field to describe the source in more detail. description: Optional[str] = None @@ -112,3 +127,13 @@ class ResourceSource: # It is updated asynchronously as data is fetched from the source. # Nil if the schema has not been inferred yet. Includes attribute descriptions if present. schema: Optional[Any] = None + + # AvailableRefreshStrategies lists the refresh strategies that resource types + # using this source can pick. + available_refresh_strategies: Optional[List[RefreshStrategy]] = None + + # AvailableScopes lists the scopes that resource types using this source can pick. + available_scopes: Optional[List[Scope]] = None + + # Managed is set when Gradient Labs manages the source for you. + managed: Optional[ResourceManagedDefinition] = None diff --git a/src/gradient_labs/resource_type.py b/src/gradient_labs/resource_type.py index 36aacb1..5a4d8e3 100644 --- a/src/gradient_labs/resource_type.py +++ b/src/gradient_labs/resource_type.py @@ -1,9 +1,11 @@ from typing import Optional, List, Any from enum import Enum -from dataclasses import dataclass +from dataclasses import dataclass, field from dataclasses_json import dataclass_json from datetime import datetime +from ._datetime import optional_datetime_config + class Scope(str, Enum): """Scope determines when in the conversation the resource is fetched and used.""" @@ -108,7 +110,7 @@ class ResourceType: is_enabled: bool = False # Created is when the resource type was created. - created: Optional[datetime] = None + created: Optional[datetime] = field(default=None, metadata=optional_datetime_config) # Updated is when the resource type was last updated. - updated: Optional[datetime] = None + updated: Optional[datetime] = field(default=None, metadata=optional_datetime_config) diff --git a/src/gradient_labs/secret.py b/src/gradient_labs/secret.py index 3e589c5..23e6fa1 100644 --- a/src/gradient_labs/secret.py +++ b/src/gradient_labs/secret.py @@ -1,11 +1,24 @@ from typing import Optional -from dataclasses import dataclass +from dataclasses import dataclass, field from dataclasses_json import dataclass_json from datetime import datetime +from ._datetime import datetime_config, optional_datetime_config from .tool import HTTPDefinition +@dataclass_json +@dataclass(frozen=True) +class SecretHTTPRetry: + request_timeout_seconds: Optional[int] = None + + +@dataclass_json +@dataclass(frozen=True) +class SecretHTTPRequest(HTTPDefinition): + retry: Optional[SecretHTTPRetry] = None + + @dataclass_json @dataclass(frozen=True) class RefreshMechanismHTTP: @@ -14,7 +27,7 @@ class RefreshMechanismHTTP: need periodic renewal.""" # request_definition specifies the HTTP request to make to refresh the secret. - request_definition: HTTPDefinition + request_definition: SecretHTTPRequest # response_param_name is the JSON field name in the response that contains # the new secret value. @@ -30,13 +43,13 @@ class Secret: name: str # created is when the secret was first created. - created: datetime + created: datetime = field(metadata=datetime_config) # updated is when the secret was last updated. - updated: datetime + updated: datetime = field(metadata=datetime_config) # expiry is the optional expiration time for the secret. - expiry: Optional[datetime] = None + expiry: Optional[datetime] = field(default=None, metadata=optional_datetime_config) # refresh_mechanism_http is the optional configuration for automatically refreshing # the secret value using an HTTP request (e.g., OAuth token refresh). diff --git a/src/gradient_labs/terminology_substitution.py b/src/gradient_labs/terminology_substitution.py index 0d20307..9c3cf35 100644 --- a/src/gradient_labs/terminology_substitution.py +++ b/src/gradient_labs/terminology_substitution.py @@ -4,6 +4,8 @@ from dataclasses_json import dataclass_json, config from marshmallow import fields +from ._datetime import parse_datetime + @dataclass_json @dataclass(frozen=True) @@ -15,14 +17,14 @@ class TerminologySubstitution: created: datetime = field( metadata=config( encoder=datetime.isoformat, - decoder=datetime.fromisoformat, + decoder=parse_datetime, mm_field=fields.DateTime(format="iso"), ) ) updated: datetime = field( metadata=config( encoder=datetime.isoformat, - decoder=datetime.fromisoformat, + decoder=parse_datetime, mm_field=fields.DateTime(format="iso"), ) ) diff --git a/src/gradient_labs/tool.py b/src/gradient_labs/tool.py index 59344fc..19f281c 100644 --- a/src/gradient_labs/tool.py +++ b/src/gradient_labs/tool.py @@ -1,7 +1,9 @@ +from datetime import timedelta from typing import Optional, List, Dict from enum import Enum from dataclasses import dataclass, field -from dataclasses_json import dataclass_json +from dataclasses_json import dataclass_json, config +from marshmallow import fields class ParameterType(str, Enum): @@ -10,6 +12,58 @@ class ParameterType(str, Enum): # STRING indicates the parameter accepts string/text values. STRING: str = "string" + # STRING_ARRAY indicates the parameter accepts a list of strings. The API only + # returns it on existing tools: creating or updating a tool with it fails. + STRING_ARRAY: str = "string_array" + + # JSON indicates the parameter accepts a JSON value. The API only returns it + # on existing tools: creating or updating a tool with it fails. + JSON: str = "json" + + # INTEGER indicates the parameter accepts whole numbers. + INTEGER: str = "integer" + + # FLOAT indicates the parameter accepts decimal numbers. + FLOAT: str = "float" + + # BOOLEAN indicates the parameter accepts true or false. + BOOLEAN: str = "boolean" + + # DATE indicates the parameter accepts a calendar date. + DATE: str = "date" + + # TIMESTAMP indicates the parameter accepts a date and time. + TIMESTAMP: str = "timestamp" + + # DURATION indicates the parameter accepts a length of time. + DURATION: str = "duration" + + # ATTACHMENT indicates the parameter accepts a file. Set transfer_mode too. + ATTACHMENT: str = "attachment" + + +class ParameterSource(str, Enum): + """ParameterSource says where a parameter's value can come from.""" + + # LLM means the AI agent provides the value. + LLM: str = "llm" + + # LITERAL means a procedure sets a fixed value. + LITERAL: str = "literal" + + # RESOURCE means the value comes from a resource. + RESOURCE: str = "resource" + + +class TransferMode(str, Enum): + """TransferMode says how an attachment parameter's file reaches the tool.""" + + # BASE64 sends the file's contents, base64-encoded. + BASE64: str = "base64" + + # TEMPORARY_URL sends a temporary URL to download the file from. + TEMPORARY_URL: str = "temporary_url" + class BodyEncoding(str, Enum): """BodyEncoding determines how the HTTP body will be encoded.""" @@ -37,6 +91,33 @@ class ToolParameter: required: Optional[bool] = False options: Optional[List[ParameterOption]] = field(default_factory=lambda: []) + # allowed_sources says where the parameter's value can come from. At least + # one is required. + allowed_sources: List[ParameterSource] = field( + default_factory=lambda: [ParameterSource.LLM] + ) + + # transfer_mode says how an attachment parameter's file reaches the tool. It is + # required when type is ATTACHMENT, and not allowed for any other type. + transfer_mode: Optional[TransferMode] = None + + +@dataclass_json +@dataclass(frozen=True) +class ToolParameterSet: + """ToolParameterSet is a group of parameters that apply when a discriminator + parameter has a given value.""" + + # discriminator_parameter_name is the name of the top-level parameter whose + # value decides whether this set applies. + discriminator_parameter_name: str + + # discriminator_value is the value of that parameter that activates this set. + discriminator_value: str + + # parameters are the extra parameters that apply when this set is active. + parameters: List[ToolParameter] + @dataclass_json @dataclass(frozen=True) @@ -44,6 +125,18 @@ class ToolWebhookConfiguration: name: str +@dataclass_json +@dataclass(frozen=True) +class HTTPRetryDefinition: + """HTTPRetryDefinition overrides how a tool's HTTP request is retried.""" + + # max_attempts is the most times the request is tried. + max_attempts: Optional[int] = None + + # request_timeout_seconds is how long each attempt may take. + request_timeout_seconds: Optional[int] = None + + @dataclass_json @dataclass(frozen=True) class HTTPBodyDefinition: @@ -59,6 +152,56 @@ class HTTPDefinition: url_template: str header_templates: Optional[Dict[str, str]] = None body: Optional[HTTPBodyDefinition] = None + retry: Optional[HTTPRetryDefinition] = None + + +@dataclass_json +@dataclass(frozen=True) +class AsyncChildTool: + """AsyncChildTool is one step of an async tool. It uses its parent tool's parameters. + Set either webhook or http.""" + + webhook: Optional[ToolWebhookConfiguration] = None + http: Optional[HTTPDefinition] = None + + +def _encode_timeout(value: timedelta) -> int: + return (value // timedelta(microseconds=1)) * 1000 + + +def _decode_timeout(value: int) -> timedelta: + return timedelta(microseconds=value // 1000) + + +@dataclass_json +@dataclass(frozen=True) +class AsyncDefinition: + """AsyncDefinition configures a tool for long-running operations.""" + + # start_execution_tool starts the operation. It runs as soon as the tool is used. + start_execution_tool: AsyncChildTool + + # timeout is the longest to wait for the operation to finish. + timeout: timedelta = field( + metadata=config( + encoder=_encode_timeout, + decoder=_decode_timeout, + mm_field=fields.TimeDelta(), + ) + ) + + # cancel_execution_tool optionally cancels the operation. + cancel_execution_tool: Optional[AsyncChildTool] = None + + +@dataclass_json +@dataclass(frozen=True) +class ToolMCPConfiguration: + """ToolMCPConfiguration runs a tool on a Model Context Protocol server. The API + only returns it when reading a tool: creating a tool with it fails.""" + + server_id: str + external_tool_name: str @dataclass_json @@ -71,13 +214,45 @@ class Tool: webhook: Optional[ToolWebhookConfiguration] = None http: Optional[HTTPDefinition] = None + # parameter_sets are groups of extra parameters that apply when a discriminator + # parameter has a given value. + parameter_sets: Optional[List[ToolParameterSet]] = None + + # async_ configures a long-running tool. It is sent as `async`. + async_: Optional[AsyncDefinition] = field( + default=None, metadata=config(field_name="async") + ) + + # mcp is set on tools that run on an MCP server. + mcp: Optional[ToolMCPConfiguration] = None + + # draft marks a tool that is still being built. A draft tool cannot run, and + # takes no webhook, http or async configuration. + draft: Optional[bool] = None + + # branch_id is the ID of the git-backed branch to create the tool on. Only used + # when creating a tool: send this or branch_name. + branch_id: Optional[str] = None + + # branch_name is the name of the git-backed branch to create the tool on, as an + # alternative to branch_id. Only used when creating a tool. + branch_name: Optional[str] = None + @dataclass_json @dataclass(frozen=True) class ToolUpdateParams: id: str - description: str - parameters: List[ToolParameter] = field(default_factory=lambda: []) + description: Optional[str] = None + parameters: Optional[List[ToolParameter]] = None webhook: Optional[ToolWebhookConfiguration] = None http: Optional[HTTPDefinition] = None - mock: Optional[bool] = False + + # parameter_sets are groups of extra parameters that apply when a discriminator + # parameter has a given value. + parameter_sets: Optional[List[ToolParameterSet]] = None + + # async_ configures a long-running tool. It is sent as `async`. + async_: Optional[AsyncDefinition] = field( + default=None, metadata=config(field_name="async") + ) diff --git a/src/gradient_labs/topic.py b/src/gradient_labs/topic.py index bd8d7f6..bf5c944 100644 --- a/src/gradient_labs/topic.py +++ b/src/gradient_labs/topic.py @@ -1,46 +1,55 @@ -from dataclasses import dataclass +from dataclasses import dataclass, field from datetime import datetime from typing import Optional, Any -from dataclasses_json import dataclass_json +from dataclasses_json import dataclass_json, config +from ._datetime import datetime_config_named from .article import Visibility @dataclass_json @dataclass(frozen=True) class Topic: - """Topic represents an article topic for categorizing help articles.""" + """Topic is an article topic. The API names its fields in CamelCase + (e.g. `ExternalID`), so each field below says which one it reads.""" - # source identifies the CRM or support platform that the topic comes from - source: str + # source is the support platform this topic comes from, such as "public-api" + # or "intercom". + source: str = field(metadata=config(field_name="Source")) - # external_id identifies this topic in the Source - external_id: str + # external_id is your identifier for this topic on the support platform. + external_id: str = field(metadata=config(field_name="ExternalID")) - # name is the human-readable name for this topic - name: str + # name is the topic's name. + name: str = field(metadata=config(field_name="Name")) - # visibility describes who can see the topic - visibility: Visibility + # visibility describes who can see this topic. + visibility: Visibility = field(metadata=config(field_name="Visibility")) - # created is when the topic was created in the source - created: datetime + # created is when the topic was first created on the support platform. + created: datetime = field(metadata=datetime_config_named("Created")) - # last_edited is when the topic was last changed in the source - last_edited: datetime + # last_edited is when the topic was last changed on the support platform. + last_edited: datetime = field(metadata=datetime_config_named("LastEdited")) - # last_seen is the last time we saw this topic when crawling - last_seen: datetime + # last_seen is when Gradient Labs last saw this topic while syncing. + last_seen: datetime = field(metadata=datetime_config_named("LastSeen")) - # data is a raw representation of the topic from the support platform - data: Any + # data is the topic as the support platform represents it, base64-encoded. + data: Any = field(metadata=config(field_name="Data")) - # description is the optional subtext for the topic - description: Optional[str] = None + # description is a short description of the topic. + description: Optional[str] = field( + default=None, metadata=config(field_name="Description") + ) - # parent_external_id identifies the topic that this topic is nested under - parent_external_id: Optional[str] = None + # parent_external_id identifies the topic this one sits under, if any. + parent_external_id: Optional[str] = field( + default=None, metadata=config(field_name="ParentExternalID") + ) - # public_url optionally points to the public resource for this topic - public_url: Optional[str] = None + # public_url is a link to the topic online, if it has one. + public_url: Optional[str] = field( + default=None, metadata=config(field_name="PublicURL") + ) diff --git a/src/gradient_labs/traffic_group.py b/src/gradient_labs/traffic_group.py index c6c528c..cf03b3f 100644 --- a/src/gradient_labs/traffic_group.py +++ b/src/gradient_labs/traffic_group.py @@ -1,6 +1,6 @@ from typing import List -from dataclasses import dataclass +from dataclasses import dataclass, field from dataclasses_json import dataclass_json @@ -25,3 +25,6 @@ class TrafficGroup: # targets is the list of targets assigned to the traffic group. targets: List[TrafficGroupTarget] + + # excluded_targets is the list of targets that are kept out of the traffic group. + excluded_targets: List[TrafficGroupTarget] = field(default_factory=list) diff --git a/src/gradient_labs/voice_call_context.py b/src/gradient_labs/voice_call_context.py index 80401db..86d410e 100644 --- a/src/gradient_labs/voice_call_context.py +++ b/src/gradient_labs/voice_call_context.py @@ -4,6 +4,8 @@ from dataclasses_json import dataclass_json, config from marshmallow import fields +from ._datetime import parse_datetime + @dataclass_json @dataclass(frozen=True) @@ -11,7 +13,7 @@ class VoiceCallContext: started_at: datetime = field( metadata=config( encoder=datetime.isoformat, - decoder=datetime.fromisoformat, + decoder=parse_datetime, mm_field=fields.DateTime(format="iso"), ) ) @@ -21,3 +23,4 @@ class VoiceCallContext: last_executed_procedure: Optional[str] = None last_executed_procedure_url: Optional[str] = None gradient_labs_url: Optional[str] = None + live_handoff_url: Optional[str] = None diff --git a/src/gradient_labs/webhook.py b/src/gradient_labs/webhook.py index d9a2606..dddaab9 100644 --- a/src/gradient_labs/webhook.py +++ b/src/gradient_labs/webhook.py @@ -63,6 +63,14 @@ def parse_event( data["data"] = ConversationFinishedEvent.from_dict(data["data"]) elif data["type"] == "action.execute": data["data"] = ActionExecuteEvent.from_dict(data["data"]) + elif data["type"] == "back-office-task.complete": + data["data"] = BackOfficeTaskCompleteEvent.from_dict(data["data"]) + elif data["type"] == "back-office-task.hand-off": + data["data"] = BackOfficeTaskHandOffEvent.from_dict(data["data"]) + elif data["type"] == "back-office-task.fail": + data["data"] = BackOfficeTaskFailEvent.from_dict(data["data"]) + elif data["type"] == "conversation.start": + data["data"] = ConversationStartEvent.from_dict(data["data"]) return WebhookEvent.from_dict(data) @classmethod diff --git a/tests/test_new_operations.py b/tests/test_new_operations.py new file mode 100644 index 0000000..0f45e13 --- /dev/null +++ b/tests/test_new_operations.py @@ -0,0 +1,438 @@ +import warnings +from datetime import datetime +from unittest.mock import MagicMock + +import pytest + +from gradient_labs import ( + BatchCreateCustomerMemoriesDeprecatedParams, + BatchCreateCustomerMemoriesParams, + BatchCreateCustomerMemory, + BatchCreateCustomerMemoryDeprecated, + BeginFileUploadParams, + Client, + CreateFileParams, + CreateKnowledgeBaseParams, + CustomerMemoryType, + FileListParams, + NoteListParams, + NoteStatus, + UpdateKnowledgeBaseParams, +) + +TIME = "2024-01-15T10:30:00Z" + + +def _client(method: str, response=None): + client = Client(api_key="test-key") + mock = MagicMock(return_value=response) + setattr(client.http_client, method, mock) + return client, mock + + +def _note(**extra): + return { + "gradient_labs_id": "note_01", + "id": "spring-sale", + "title": "Spring sale", + "last_modified_by": "public-api", + "status": "live", + "created": TIME, + "updated": TIME, + **extra, + } + + +def _knowledge_base(): + return { + "gradient_labs_id": "knowledgebase_01", + "id": "help-centre", + "name": "Help Centre", + "created": TIME, + "updated": TIME, + } + + +def _file(): + return { + "id": "companyfile_01", + "ref": "id-card-front", + "file_name": "id-card-front.png", + "content_type": "image/png", + "size_bytes": 482113, + "created": TIME, + } + + +class TestNotes: + def test_list_notes(self): + client, get = _client( + "get", + { + "notes": [_note(attributes={"Locale": ["UK"]})], + "pagination": {"next": "cursor-2"}, + }, + ) + + rsp = client.list_notes(params=NoteListParams(cursor="cursor-1")) + + _, kwargs = get.call_args + assert kwargs["path"] == "notes" + assert kwargs["query_params"] == {"cursor": "cursor-1"} + assert rsp.notes[0].id == "spring-sale" + assert rsp.notes[0].status == NoteStatus.LIVE + assert rsp.notes[0].attributes == {"Locale": ["UK"]} + assert rsp.pagination.next == "cursor-2" + + def test_list_notes_without_params(self): + client, get = _client("get", {"notes": [], "pagination": {}}) + + client.list_notes() + + assert get.call_args.kwargs["query_params"] == {} + + def test_read_note(self): + client, get = _client("get", _note(body="20% off")) + + note = client.read_note(note_id="spring-sale") + + assert get.call_args.kwargs["path"] == "notes/spring-sale" + assert note.body == "20% off" + assert note.created.year == 2024 + + +class TestKnowledgeBases: + def test_list(self): + client, get = _client("get", {"knowledge_bases": [_knowledge_base()]}) + + rsp = client.list_knowledge_bases() + + assert get.call_args.kwargs["path"] == "knowledge-bases" + assert rsp.knowledge_bases[0].id == "help-centre" + + def test_create(self): + client, post = _client("post", _knowledge_base()) + + kb = client.create_knowledge_base( + params=CreateKnowledgeBaseParams(id="help-centre", name="Help Centre") + ) + + _, kwargs = post.call_args + assert kwargs["path"] == "knowledge-bases" + assert kwargs["body"] == {"id": "help-centre", "name": "Help Centre"} + assert kb.gradient_labs_id == "knowledgebase_01" + + def test_read(self): + client, get = _client("get", _knowledge_base()) + + client.read_knowledge_base(knowledge_base_id="help-centre") + + assert get.call_args.kwargs["path"] == "knowledge-bases/help-centre" + + def test_update(self): + client, post = _client("post", _knowledge_base()) + + client.update_knowledge_base( + knowledge_base_id="help-centre", + params=UpdateKnowledgeBaseParams(name="Help"), + ) + + _, kwargs = post.call_args + assert kwargs["path"] == "knowledge-bases/help-centre" + assert kwargs["body"] == {"name": "Help"} + + +class TestFiles: + def test_begin_upload(self): + client, post = _client( + "post", + { + "upload_id": "upload_1", + "upload_url": "https://storage.example.com/upload_1", + "content_type": "image/png", + "headers": {"Content-Type": "image/png"}, + "expires_at": TIME, + "max_bytes": 5242880, + }, + ) + + upload = client.begin_file_upload( + params=BeginFileUploadParams(content_type="image/png") + ) + + _, kwargs = post.call_args + assert kwargs["path"] == "file-uploads" + assert kwargs["body"] == {"content_type": "image/png"} + assert upload.upload_id == "upload_1" + assert upload.headers == {"Content-Type": "image/png"} + assert upload.max_bytes == 5242880 + + def test_begin_upload_without_params(self): + client, post = _client( + "post", + { + "upload_id": "u", + "upload_url": "https://storage.example.com/u", + "content_type": "application/octet-stream", + "headers": {}, + "expires_at": TIME, + "max_bytes": 1, + }, + ) + + client.begin_file_upload() + + assert post.call_args.kwargs["body"] == {} + + def test_list(self): + client, get = _client( + "get", {"files": [_file()], "pagination": {"next": "cursor-2"}} + ) + + rsp = client.list_files(params=FileListParams(cursor="cursor-1")) + + _, kwargs = get.call_args + assert kwargs["path"] == "files" + assert kwargs["query_params"] == {"cursor": "cursor-1"} + assert rsp.files[0].ref == "id-card-front" + assert rsp.pagination.next == "cursor-2" + + def test_create(self): + client, post = _client("post", _file()) + + file = client.create_file( + params=CreateFileParams(upload_id="upload_1", file_name="id.png") + ) + + _, kwargs = post.call_args + assert kwargs["path"] == "files" + assert kwargs["body"] == {"upload_id": "upload_1", "file_name": "id.png"} + assert file.size_bytes == 482113 + + +class TestCustomerMemories: + def test_list(self): + client, get = _client( + "get", + { + "memories": [ + { + "external_id": "order_123", + "custom_type": { + "name": "order_event", + "description": "An order", + }, + "created_at": TIME, + "data": {"total": 10}, + } + ] + }, + ) + + rsp = client.list_customer_memories(customer_id="cust-1") + + assert get.call_args.kwargs["path"] == "customers/cust-1/memories" + memory = rsp.memories[0] + assert memory.custom_type.name == "order_event" + assert memory.data == {"total": 10} + + def test_batch_create_v2(self): + client, post = _client("post") + + client.batch_create_customer_memories_v2( + customer_id="cust-1", + params=BatchCreateCustomerMemoriesParams( + memories=[ + BatchCreateCustomerMemory( + external_id="order_123", + custom_type=CustomerMemoryType(name="order_event"), + created_at=datetime(2024, 1, 15, 10, 30), + data={"total": 10}, + ) + ] + ), + ) + + _, kwargs = post.call_args + assert kwargs["path"] == "customers/cust-1/memories/v2" + assert kwargs["body"] == { + "memories": [ + { + "external_id": "order_123", + "custom_type": {"name": "order_event"}, + "created_at": "2024-01-15T10:30:00.000000Z", + "data": {"total": 10}, + } + ] + } + + def test_batch_create_is_deprecated(self): + client, post = _client("post") + + with pytest.warns(DeprecationWarning): + client.batch_create_customer_memories( + customer_id="cust-1", + params=BatchCreateCustomerMemoriesDeprecatedParams( + memories=[ + BatchCreateCustomerMemoryDeprecated( + external_id="order_123", + custom_type="order_event", + created_at=datetime(2024, 1, 15, 10, 30), + data={}, + ) + ] + ), + ) + + _, kwargs = post.call_args + assert kwargs["path"] == "customers/cust-1/memories" + assert kwargs["body"]["memories"][0]["custom_type"] == "order_event" + + +class TestReadConversationDeprecated: + def test_reads_the_deprecated_path(self): + client, get = _client( + "get", + { + "id": "conv-1", + "customer_id": "cust-1", + "channel": "web", + "status": "active", + "created": "2024-01-15T10:30:00+00:00", + "updated": "2024-01-15T10:30:00+00:00", + }, + ) + + with pytest.warns(DeprecationWarning): + conversation = client.read_conversation_deprecated(conversation_id="conv-1") + + assert get.call_args.kwargs["path"] == "conversations/conv-1" + assert conversation.id == "conv-1" + + def test_read_conversation_does_not_warn(self): + client, get = _client( + "get", + { + "id": "conv-1", + "customer_id": "cust-1", + "channel": "web", + "status": "active", + "created": "2024-01-15T10:30:00+00:00", + "updated": "2024-01-15T10:30:00+00:00", + }, + ) + + with warnings.catch_warnings(): + warnings.simplefilter("error") + client.read_conversation(conversation_id="conv-1") + + assert get.call_args.kwargs["path"] == "conversations/conv-1/read" + + +def test_update_tool_preserves_unset_fields(): + from gradient_labs import ToolUpdateParams + + client, put = _client("put", {"id": "tool-1", "name": "search", "description": ""}) + client.update_tool( + params=ToolUpdateParams(id="tool-1", description="Find an order") + ) + put.assert_called_once_with( + path="tools/tool-1", body={"description": "Find an order"} + ) + + +def test_tool_execute_with_public_argument(): + from gradient_labs import Argument, ToolExecuteParams + + client, post = _client("post", {"id": "run-1", "result": ["found"]}) + response = client.execute_tool( + params=ToolExecuteParams(id="tool-1", arguments=[Argument("query", "books")]) + ) + post.assert_called_once_with( + path="tools/tool-1/execute", + body={"arguments": [{"name": "query", "value": "books"}]}, + ) + assert response.result == ["found"] + + +def test_article_topic_public_url_and_arbitrary_data(): + from gradient_labs import ArticleTopicUpsertParams, PublicationStatus, Visibility + + client, post = _client("post") + client.upsert_article_topic( + params=ArticleTopicUpsertParams( + id="topic", + name="Help", + visibility=Visibility.PUBLIC, + status=PublicationStatus.PUBLISHED, + created=datetime(2024, 1, 1), + last_edited=datetime(2024, 1, 2), + data=[None, False], + public_url="https://example.org/help", + ) + ) + assert post.call_args.kwargs["body"]["public_url"] == "https://example.org/help" + assert post.call_args.kwargs["body"]["data"] == [None, False] + + +def test_attachment_only_message_and_positional_replay(): + from gradient_labs import ( + AddMessageParams, + Attachment, + AttachmentType, + ParticipantType, + ) + + client, post = _client( + "post", + { + "id": "message", + "body": "", + "participant_type": "AI Agent", + "participant_id": "agent", + }, + ) + attachment = Attachment( + AttachmentType.FILE, "receipt.pdf", url="https://example.org/receipt.pdf" + ) + response = client.add_message( + conversation_id="conv", + params=AddMessageParams( + id="message", + participant_type=ParticipantType.AI_AGENT, + attachments=[attachment], + ), + ) + assert post.call_args.kwargs["body"] == { + "id": "message", + "participant_type": "AI Agent", + "attachments": [ + { + "type": "file", + "file_name": "receipt.pdf", + "url": "https://example.org/receipt.pdf", + } + ], + } + assert response.participant_id == "agent" + client.add_message( + conversation_id="conv", + params=AddMessageParams("message", "Hello", "agent", ParticipantType.AI_AGENT), + ) + assert post.call_args.kwargs["body"]["body"] == "Hello" + + +@pytest.mark.parametrize("fraction,microsecond", [("1", 100000), ("123456789", 123456)]) +def test_rfc3339_fractional_seconds(fraction, microsecond): + from gradient_labs import CustomerMemory + + memory = CustomerMemory.from_dict( + { + "external_id": "order", + "custom_type": {"name": "order"}, + "created_at": f"2025-01-02T03:04:05.{fraction}Z", + "data": {}, + } + ) + assert memory.created_at.microsecond == microsecond + assert memory.created_at.utcoffset().total_seconds() == 0 diff --git a/tests/test_operations.py b/tests/test_operations.py new file mode 100644 index 0000000..6a2ae60 --- /dev/null +++ b/tests/test_operations.py @@ -0,0 +1,119 @@ +import re +from pathlib import Path + +import pytest + +from gradient_labs import Client + +# OPERATIONS maps each public API contract operation id the library implements to +# the Client method that calls it. Update it with PUBLIC_API_VERSION when the +# library catches up with a new version of the contract. +# +# GET /spec.json (operation id `Spec`) is deliberately not exposed. +OPERATIONS = { + "ArticleUpsert": "upsert_article", + "ArticleSetUsageStatus": "set_article_usage_status", + "ArticleDelete": "delete_article", + "BackOfficeTaskCreate": "create_back_office_task", + "BackOfficeTaskDelete": "delete_back_office_task", + "BackOfficeTaskRead": "read_back_office_task", + "ConversationStart": "start_conversation", + "ConversationCancel": "cancel_conversation", + "ConversationFinish": "finish_conversation", + "ConversationAddMessage": "add_message", + "ConversationResume": "resume_conversation", + "ConversationReturnAsyncToolResult": "return_async_tool_result", + "ConversationDelete": "delete_conversation", + "ConversationReadDeprecated": "read_conversation_deprecated", + "ConversationAssign": "assign_conversation", + "ConversationEvent": "add_conversation_event", + "ConversationRate": "rate_conversation", + "ConversationRead": "read_conversation", + "CustomerMemoriesList": "list_customer_memories", + "CustomerMemoriesBatchCreate": "batch_create_customer_memories", + "CustomerMemoriesBatchCreateV2": "batch_create_customer_memories_v2", + "FileUploadBegin": "begin_file_upload", + "FileList": "list_files", + "FileCreate": "create_file", + "HandOffTargetDelete": "delete_hand_off_target", + "ListHandOffTargets": "list_handoff_targets", + "HandOffTargetUpsert": "upsert_hand_off_target", + "GetDefaultHandOffTarget": "get_default_hand_off_target", + "SetDefaultHandOffTarget": "set_default_hand_off_target", + "IPAddressList": "list_ip_addresses", + "KnowledgeBaseList": "list_knowledge_bases", + "KnowledgeBaseCreate": "create_knowledge_base", + "KnowledgeBaseRead": "read_knowledge_base", + "KnowledgeBaseUpdate": "update_knowledge_base", + "NoteList": "list_notes", + "NoteCreate": "create_note", + "NoteDelete": "delete_note", + "NoteRead": "read_note", + "NoteUpdate": "update_note", + "NoteSetStatus": "set_note_status", + "OutboundChatConversationStart": "start_outbound_chat_conversation", + "OutboundEmailConversationStart": "start_outbound_email_conversation", + "OutboundPhoneConversationStart": "start_outbound_phone_conversation", + "ReadProcedure": "read_procedure", + "SetProcedureLimit": "set_procedure_limit", + "ListProcedures": "list_procedures", + "ProcedureListVersions": "list_procedure_versions", + "ProcedureSetGatedVersion": "set_procedure_gated_version", + "ProcedureSetLiveVersion": "set_procedure_live_version", + "ProcedureUnsetGatedVersion": "unset_procedure_gated_version", + "ProcedureUnsetLiveVersion": "unset_procedure_live_version", + "ResourceSourceList": "list_resource_sources", + "ResourceSourceCreate": "create_resource_source", + "ResourceSourceDelete": "delete_resource_source", + "ResourceSourceRead": "read_resource_source", + "ResourceSourceUpdate": "update_resource_source", + "UpdateSchemaByExamples": "update_resource_source_schema_by_examples", + "ResourceTypeList": "list_resource_types", + "ResourceTypeCreate": "create_resource_type", + "ResourceTypeDelete": "delete_resource_type", + "ResourceTypeRead": "read_resource_type", + "ResourceTypeUpdate": "update_resource_type", + "SecretList": "list_secrets", + "SecretRevoke": "revoke_secret", + "SecretWrite": "write_secret", + "TerminologySubstitutionList": "list_terminology_substitutions", + "TerminologySubstitutionCreate": "create_terminology_substitution", + "TerminologySubstitutionDelete": "delete_terminology_substitution", + "TerminologySubstitutionRead": "read_terminology_substitution", + "TerminologySubstitutionUpdate": "update_terminology_substitution", + "ToolList": "list_tools", + "ToolCreate": "create_tool", + "ToolDelete": "delete_tool", + "ToolRead": "read_tool", + "ToolUpdate": "update_tool", + "ToolExecute": "execute_tool", + "ReadTopic": "read_topic", + "ListTopics": "list_topics", + "ArticleTopicUpsert": "upsert_article_topic", + "ListTrafficGroups": "list_traffic_groups", + "TrafficGroupCreate": "create_traffic_group", + "TrafficGroupDelete": "delete_traffic_group", + "TrafficGroupUpdate": "update_traffic_group", + "TrafficGroupExclusionCreate": "create_traffic_group_exclusion", + "TrafficGroupExclusionDelete": "delete_traffic_group_exclusion", + "TrafficGroupTargetCreate": "create_traffic_group_target", + "TrafficGroupTargetDelete": "delete_traffic_group_target", + "VoiceCallContextRead": "read_voice_call_context", +} + + +@pytest.mark.parametrize("operation_id,method", sorted(OPERATIONS.items())) +def test_operation_has_method(operation_id, method): + assert callable(getattr(Client, method, None)), ( + f"{operation_id} should be implemented by Client.{method}" + ) + + +def test_spec_is_not_exposed(): + assert "Spec" not in OPERATIONS + assert not hasattr(Client, "read_spec") + + +def test_public_api_version_is_a_contract_hash(): + version = Path(__file__).resolve().parent.parent / "PUBLIC_API_VERSION" + assert re.fullmatch(r"[0-9a-f]{64}\n", version.read_text()) From bf8ca0f1ececbb06abc38a39958fc29bca73541b Mon Sep 17 00:00:00 2001 From: Theo Windebank Date: Wed, 25 Nov 2026 14:35:16 +0000 Subject: [PATCH 2/2] Bump version to 0.13.0 --- pyproject.toml | 2 +- uv.lock | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 0acee60..89d4502 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "gradient-labs" -version = "0.12.2" +version = "0.13.0" description = "Python bindings for the Gradient Labs API" readme = "README.md" requires-python = ">=3.9,<4.0" diff --git a/uv.lock b/uv.lock index 11db5e9..2d5a2a7 100644 --- a/uv.lock +++ b/uv.lock @@ -181,7 +181,7 @@ wheels = [ [[package]] name = "gradient-labs" -version = "0.12.2" +version = "0.13.0" source = { editable = "." } dependencies = [ { name = "dataclasses-json" },