nbq 0.9.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
nbq-0.9.0/.gitignore ADDED
@@ -0,0 +1,34 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.egg-info/
5
+ build/
6
+ dist/
7
+ .pytest_cache/
8
+ .mypy_cache/
9
+ .ruff_cache/
10
+ .coverage
11
+ htmlcov/
12
+
13
+ # Virtual environments and tooling
14
+ .venv/
15
+ venv/
16
+ .uv/
17
+
18
+ # JavaScript / TypeScript
19
+ node_modules/
20
+ .turbo/
21
+ coverage/
22
+
23
+ # Secrets and local environment
24
+ .env
25
+ .env.*
26
+ !.env.example
27
+ *.envrc
28
+
29
+ # Editors and operating systems
30
+ .vscode/
31
+ .idea/
32
+ *.swp
33
+ *.swo
34
+ .DS_Store
nbq-0.9.0/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
nbq-0.9.0/PKG-INFO ADDED
@@ -0,0 +1,109 @@
1
+ Metadata-Version: 2.5
2
+ Name: nbq
3
+ Version: 0.9.0
4
+ Summary: Official Python SDK for the Zelinqa Next Best Question API
5
+ Project-URL: Documentation, https://docs.zelinqa.ai
6
+ Project-URL: Homepage, https://zelinqa.ai
7
+ Project-URL: Repository, https://github.com/Zelinqa/nbq-sdk
8
+ Project-URL: Issues, https://github.com/Zelinqa/nbq-sdk/issues
9
+ Author-email: Zelinqa <support@zelinqa.ai>
10
+ License-Expression: Apache-2.0
11
+ License-File: LICENSE
12
+ Keywords: conversational-ai,nbq,next-best-question,zelinqa
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Typing :: Typed
19
+ Requires-Python: >=3.11
20
+ Requires-Dist: httpx<1,>=0.27
21
+ Description-Content-Type: text/markdown
22
+
23
+ # NBQ Python SDK
24
+
25
+ The official Python client for the [Zelinqa NBQ API](https://docs.zelinqa.ai).
26
+
27
+ NBQ selects the next best question for a conversation from a customer-configured question
28
+ bank. This package is a typed HTTP client; the scoring algorithm remains in the hosted NBQ
29
+ Engine.
30
+
31
+ > The SDK is currently beta. Its public surface follows the deployed `/v1` runtime API.
32
+
33
+ ## Installation
34
+
35
+ ```bash
36
+ pip install nbq
37
+ ```
38
+
39
+ ## Synchronous client
40
+
41
+ ```python
42
+ from nbq import Message, NBQClient
43
+
44
+ with NBQClient(api_key="nbq_live_...") as client:
45
+ result = client.next_question(
46
+ session_id="conversation-123",
47
+ conversation_history=[
48
+ Message(role="user", content="We receive about 200 leads per month."),
49
+ ],
50
+ )
51
+
52
+ if result.next_question is not None:
53
+ print(result.next_question.text)
54
+ ```
55
+
56
+ Keep the same `session_id` for the entire conversation and use a new one for each new
57
+ conversation. Send every question actually asked in `answered_question_ids` on subsequent
58
+ calls.
59
+
60
+ ## Asynchronous client
61
+
62
+ ```python
63
+ from nbq import AsyncNBQClient, Message
64
+
65
+ async with AsyncNBQClient(api_key="nbq_live_...") as client:
66
+ result = await client.next_question(
67
+ session_id="conversation-123",
68
+ conversation_history=[
69
+ Message(role="user", content="We receive about 200 leads per month."),
70
+ ],
71
+ answered_question_ids=["q_company_size"],
72
+ )
73
+ ```
74
+
75
+ ## Report an outcome
76
+
77
+ ```python
78
+ conversion = client.report_conversion(
79
+ session_id="conversation-123",
80
+ outcome="lead",
81
+ metadata={"source": "website"},
82
+ )
83
+ print(conversion.conversion_id)
84
+ ```
85
+
86
+ The SDK automatically adds an idempotency key to writes. You can provide your own key when
87
+ the same business operation may be retried outside the SDK process.
88
+
89
+ ## Configuration
90
+
91
+ ```python
92
+ client = NBQClient(
93
+ api_key="nbq_live_...",
94
+ base_url="https://api.zelinqa.ai",
95
+ timeout=10.0,
96
+ max_retries=2,
97
+ )
98
+ ```
99
+
100
+ Do not expose the runtime API key in browser or mobile code. Call NBQ from a trusted backend.
101
+
102
+ ## Support
103
+
104
+ Log the `request_id` returned by NBQ when contacting support. Do not include API keys or
105
+ conversation content in bug reports.
106
+
107
+ ## License
108
+
109
+ Apache License 2.0.
@@ -0,0 +1,61 @@
1
+ [project]
2
+ name = "nbq"
3
+ version = "0.9.0"
4
+ description = "Official Python SDK for the Zelinqa Next Best Question API"
5
+ readme = "python/README.md"
6
+ requires-python = ">=3.11"
7
+ authors = [{ name = "Zelinqa", email = "support@zelinqa.ai" }]
8
+ license = "Apache-2.0"
9
+ license-files = ["LICENSE"]
10
+ keywords = ["nbq", "next-best-question", "conversational-ai", "zelinqa"]
11
+ classifiers = [
12
+ "Development Status :: 4 - Beta",
13
+ "Intended Audience :: Developers",
14
+ "Programming Language :: Python :: 3",
15
+ "Programming Language :: Python :: 3 :: Only",
16
+ "Programming Language :: Python :: 3.11",
17
+ "Typing :: Typed",
18
+ ]
19
+ dependencies = ["httpx>=0.27,<1"]
20
+
21
+ [project.urls]
22
+ Documentation = "https://docs.zelinqa.ai"
23
+ Homepage = "https://zelinqa.ai"
24
+ Repository = "https://github.com/Zelinqa/nbq-sdk"
25
+ Issues = "https://github.com/Zelinqa/nbq-sdk/issues"
26
+
27
+ [build-system]
28
+ requires = ["hatchling"]
29
+ build-backend = "hatchling.build"
30
+
31
+ [tool.hatch.build.targets.sdist]
32
+ include = ["python/src/nbq", "python/README.md", "LICENSE"]
33
+
34
+ [tool.hatch.build.targets.wheel]
35
+ packages = ["python/src/nbq"]
36
+
37
+ [dependency-groups]
38
+ dev = [
39
+ "mypy>=1.10",
40
+ "pytest>=8.0",
41
+ "pytest-asyncio>=0.24",
42
+ "ruff>=0.6.0",
43
+ "twine>=6.0",
44
+ ]
45
+
46
+ [tool.pytest.ini_options]
47
+ asyncio_mode = "auto"
48
+ testpaths = ["python/tests"]
49
+ addopts = "-ra -q --strict-markers"
50
+
51
+ [tool.ruff]
52
+ line-length = 100
53
+ target-version = "py311"
54
+
55
+ [tool.ruff.lint]
56
+ select = ["E", "F", "W", "I", "N", "B", "UP", "RUF"]
57
+ ignore = ["E501"]
58
+
59
+ [tool.mypy]
60
+ python_version = "3.11"
61
+ strict = true
@@ -0,0 +1,87 @@
1
+ # NBQ Python SDK
2
+
3
+ The official Python client for the [Zelinqa NBQ API](https://docs.zelinqa.ai).
4
+
5
+ NBQ selects the next best question for a conversation from a customer-configured question
6
+ bank. This package is a typed HTTP client; the scoring algorithm remains in the hosted NBQ
7
+ Engine.
8
+
9
+ > The SDK is currently beta. Its public surface follows the deployed `/v1` runtime API.
10
+
11
+ ## Installation
12
+
13
+ ```bash
14
+ pip install nbq
15
+ ```
16
+
17
+ ## Synchronous client
18
+
19
+ ```python
20
+ from nbq import Message, NBQClient
21
+
22
+ with NBQClient(api_key="nbq_live_...") as client:
23
+ result = client.next_question(
24
+ session_id="conversation-123",
25
+ conversation_history=[
26
+ Message(role="user", content="We receive about 200 leads per month."),
27
+ ],
28
+ )
29
+
30
+ if result.next_question is not None:
31
+ print(result.next_question.text)
32
+ ```
33
+
34
+ Keep the same `session_id` for the entire conversation and use a new one for each new
35
+ conversation. Send every question actually asked in `answered_question_ids` on subsequent
36
+ calls.
37
+
38
+ ## Asynchronous client
39
+
40
+ ```python
41
+ from nbq import AsyncNBQClient, Message
42
+
43
+ async with AsyncNBQClient(api_key="nbq_live_...") as client:
44
+ result = await client.next_question(
45
+ session_id="conversation-123",
46
+ conversation_history=[
47
+ Message(role="user", content="We receive about 200 leads per month."),
48
+ ],
49
+ answered_question_ids=["q_company_size"],
50
+ )
51
+ ```
52
+
53
+ ## Report an outcome
54
+
55
+ ```python
56
+ conversion = client.report_conversion(
57
+ session_id="conversation-123",
58
+ outcome="lead",
59
+ metadata={"source": "website"},
60
+ )
61
+ print(conversion.conversion_id)
62
+ ```
63
+
64
+ The SDK automatically adds an idempotency key to writes. You can provide your own key when
65
+ the same business operation may be retried outside the SDK process.
66
+
67
+ ## Configuration
68
+
69
+ ```python
70
+ client = NBQClient(
71
+ api_key="nbq_live_...",
72
+ base_url="https://api.zelinqa.ai",
73
+ timeout=10.0,
74
+ max_retries=2,
75
+ )
76
+ ```
77
+
78
+ Do not expose the runtime API key in browser or mobile code. Call NBQ from a trusted backend.
79
+
80
+ ## Support
81
+
82
+ Log the `request_id` returned by NBQ when contacting support. Do not include API keys or
83
+ conversation content in bug reports.
84
+
85
+ ## License
86
+
87
+ Apache License 2.0.
@@ -0,0 +1,40 @@
1
+ """Official Python SDK for the Zelinqa NBQ API."""
2
+
3
+ from ._version import __version__
4
+ from .client import AsyncNBQClient, NBQClient
5
+ from .errors import (
6
+ NBQAPIError,
7
+ NBQAuthenticationError,
8
+ NBQConflictError,
9
+ NBQConnectionError,
10
+ NBQError,
11
+ NBQRateLimitError,
12
+ NBQServerError,
13
+ NBQValidationError,
14
+ )
15
+ from .models import (
16
+ ConversionResponse,
17
+ Message,
18
+ NextQuestion,
19
+ NextQuestionsResponse,
20
+ Outcome,
21
+ )
22
+
23
+ __all__ = [
24
+ "AsyncNBQClient",
25
+ "ConversionResponse",
26
+ "Message",
27
+ "NBQAPIError",
28
+ "NBQAuthenticationError",
29
+ "NBQClient",
30
+ "NBQConflictError",
31
+ "NBQConnectionError",
32
+ "NBQError",
33
+ "NBQRateLimitError",
34
+ "NBQServerError",
35
+ "NBQValidationError",
36
+ "NextQuestion",
37
+ "NextQuestionsResponse",
38
+ "Outcome",
39
+ "__version__",
40
+ ]
@@ -0,0 +1 @@
1
+ __version__ = "0.9.0"
@@ -0,0 +1,359 @@
1
+ """Synchronous and asynchronous clients for the NBQ runtime API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import json
7
+ import time
8
+ import uuid
9
+ from collections.abc import Mapping, Sequence
10
+ from typing import Any, cast
11
+ from urllib.parse import quote, urlsplit
12
+
13
+ import httpx
14
+
15
+ from ._version import __version__
16
+ from .errors import NBQConnectionError, api_error_from_payload
17
+ from .models import (
18
+ ConversionResponse,
19
+ MessageInput,
20
+ NextQuestionsResponse,
21
+ Outcome,
22
+ serialize_messages,
23
+ )
24
+
25
+ DEFAULT_BASE_URL = "https://api.zelinqa.ai"
26
+ DEFAULT_TIMEOUT_SECONDS = 10.0
27
+ DEFAULT_MAX_RETRIES = 2
28
+ MAX_SESSION_ID_CHARS = 128
29
+ MAX_HISTORY_MESSAGES = 50
30
+ MAX_ANSWERED_QUESTIONS = 200
31
+ MAX_CONTEXT_CHARS = 8000
32
+ MAX_METADATA_BYTES = 4096
33
+ RETRIABLE_STATUS_CODES = frozenset({429, 500, 502, 503, 504})
34
+
35
+
36
+ def _validate_settings(api_key: str, base_url: str, timeout: float, max_retries: int) -> None:
37
+ if not api_key.strip():
38
+ raise ValueError("api_key must not be empty")
39
+ parsed_url = urlsplit(base_url)
40
+ if parsed_url.scheme not in ("https", "http") or not parsed_url.netloc:
41
+ raise ValueError("base_url must be an absolute HTTP(S) URL")
42
+ if parsed_url.username or parsed_url.password:
43
+ raise ValueError("base_url must not contain credentials")
44
+ if parsed_url.query or parsed_url.fragment:
45
+ raise ValueError("base_url must not contain a query string or fragment")
46
+ if timeout <= 0:
47
+ raise ValueError("timeout must be greater than zero")
48
+ if max_retries < 0:
49
+ raise ValueError("max_retries must be zero or greater")
50
+
51
+
52
+ def _request_headers(api_key: str) -> dict[str, str]:
53
+ return {
54
+ "Authorization": f"Bearer {api_key}",
55
+ "Accept": "application/json",
56
+ "Content-Type": "application/json",
57
+ "User-Agent": f"nbq-python/{__version__}",
58
+ }
59
+
60
+
61
+ def _next_payload(
62
+ *,
63
+ session_id: str,
64
+ conversation_history: Sequence[MessageInput],
65
+ context: str | None,
66
+ answered_question_ids: Sequence[str],
67
+ ) -> dict[str, Any]:
68
+ if not session_id.strip():
69
+ raise ValueError("session_id must not be empty")
70
+ if len(session_id) > MAX_SESSION_ID_CHARS:
71
+ raise ValueError(f"session_id must not exceed {MAX_SESSION_ID_CHARS} characters")
72
+ if len(conversation_history) > MAX_HISTORY_MESSAGES:
73
+ raise ValueError(f"conversation_history must not exceed {MAX_HISTORY_MESSAGES} messages")
74
+ if len(answered_question_ids) > MAX_ANSWERED_QUESTIONS:
75
+ raise ValueError(f"answered_question_ids must not exceed {MAX_ANSWERED_QUESTIONS} entries")
76
+ if context is not None and len(context) > MAX_CONTEXT_CHARS:
77
+ raise ValueError(f"context must not exceed {MAX_CONTEXT_CHARS} characters")
78
+
79
+ messages = serialize_messages(conversation_history)
80
+ if not messages and not (context and context.strip()):
81
+ raise ValueError("provide conversation_history or context")
82
+ if messages and messages[-1]["role"] != "user":
83
+ raise ValueError("the last conversation message must have role='user'")
84
+
85
+ return {
86
+ "session_id": session_id,
87
+ "conversation_history": messages,
88
+ "context": context,
89
+ "answered_question_ids": list(answered_question_ids),
90
+ }
91
+
92
+
93
+ def _conversion_payload(*, outcome: Outcome, metadata: Mapping[str, Any] | None) -> dict[str, Any]:
94
+ if outcome not in ("purchase", "lead", "abandon", "other"):
95
+ raise ValueError("outcome must be purchase, lead, abandon or other")
96
+ metadata_payload = dict(metadata or {})
97
+ try:
98
+ metadata_size = len(json.dumps(metadata_payload, ensure_ascii=False).encode("utf-8"))
99
+ except (TypeError, ValueError) as exc:
100
+ raise ValueError("metadata must be JSON serializable") from exc
101
+ if metadata_size > MAX_METADATA_BYTES:
102
+ raise ValueError(f"metadata must not exceed {MAX_METADATA_BYTES} bytes when serialized")
103
+ return {"outcome": outcome, "metadata": metadata_payload}
104
+
105
+
106
+ def _idempotency_key(value: str | None) -> str:
107
+ if value is not None:
108
+ if not value.strip():
109
+ raise ValueError("idempotency_key must not be empty")
110
+ return value
111
+ return str(uuid.uuid4())
112
+
113
+
114
+ def _retry_delay(response: httpx.Response | None, attempt: int) -> float:
115
+ if response is not None:
116
+ retry_after = response.headers.get("Retry-After")
117
+ if retry_after is not None:
118
+ try:
119
+ return min(max(float(retry_after), 0.0), 10.0)
120
+ except ValueError:
121
+ pass
122
+ return float(min(0.25 * (2**attempt), 2.0))
123
+
124
+
125
+ def _response_payload(response: httpx.Response) -> Mapping[str, Any]:
126
+ try:
127
+ payload = response.json()
128
+ except ValueError as exc:
129
+ raise api_error_from_payload(
130
+ status_code=response.status_code,
131
+ payload={"detail": "NBQ API returned a non-JSON response"},
132
+ request_id=response.headers.get("X-Request-Id"),
133
+ ) from exc
134
+ if not isinstance(payload, Mapping):
135
+ raise api_error_from_payload(
136
+ status_code=response.status_code,
137
+ payload={"detail": "NBQ API returned an invalid JSON payload"},
138
+ request_id=response.headers.get("X-Request-Id"),
139
+ )
140
+ return cast(Mapping[str, Any], payload)
141
+
142
+
143
+ def _raise_for_api_error(response: httpx.Response) -> None:
144
+ if response.is_success:
145
+ return
146
+ payload: Mapping[str, Any] | None
147
+ try:
148
+ raw = response.json()
149
+ payload = cast(Mapping[str, Any], raw) if isinstance(raw, Mapping) else None
150
+ except ValueError:
151
+ payload = None
152
+ request_id = response.headers.get("X-Request-Id")
153
+ if payload and payload.get("request_id"):
154
+ request_id = str(payload["request_id"])
155
+ raise api_error_from_payload(
156
+ status_code=response.status_code,
157
+ payload=payload,
158
+ request_id=request_id,
159
+ )
160
+
161
+
162
+ class NBQClient:
163
+ """Blocking client for the hosted NBQ runtime API."""
164
+
165
+ def __init__(
166
+ self,
167
+ *,
168
+ api_key: str,
169
+ base_url: str = DEFAULT_BASE_URL,
170
+ timeout: float = DEFAULT_TIMEOUT_SECONDS,
171
+ max_retries: int = DEFAULT_MAX_RETRIES,
172
+ transport: httpx.BaseTransport | None = None,
173
+ ) -> None:
174
+ _validate_settings(api_key, base_url, timeout, max_retries)
175
+ self._max_retries = max_retries
176
+ self._http = httpx.Client(
177
+ base_url=base_url.rstrip("/"),
178
+ headers=_request_headers(api_key),
179
+ timeout=timeout,
180
+ transport=transport,
181
+ )
182
+
183
+ def __enter__(self) -> NBQClient:
184
+ return self
185
+
186
+ def __exit__(self, *_: object) -> None:
187
+ self.close()
188
+
189
+ def close(self) -> None:
190
+ self._http.close()
191
+
192
+ def _post(
193
+ self, path: str, *, payload: Mapping[str, Any], idempotency_key: str
194
+ ) -> httpx.Response:
195
+ response: httpx.Response | None = None
196
+ for attempt in range(self._max_retries + 1):
197
+ try:
198
+ response = self._http.post(
199
+ path,
200
+ json=payload,
201
+ headers={"Idempotency-Key": idempotency_key},
202
+ )
203
+ except httpx.TransportError as exc:
204
+ if attempt >= self._max_retries:
205
+ raise NBQConnectionError("Unable to reach the NBQ API") from exc
206
+ time.sleep(_retry_delay(None, attempt))
207
+ continue
208
+
209
+ if response.status_code not in RETRIABLE_STATUS_CODES or attempt >= self._max_retries:
210
+ break
211
+ time.sleep(_retry_delay(response, attempt))
212
+
213
+ assert response is not None
214
+ _raise_for_api_error(response)
215
+ return response
216
+
217
+ def next_question(
218
+ self,
219
+ *,
220
+ session_id: str,
221
+ conversation_history: Sequence[MessageInput] = (),
222
+ context: str | None = None,
223
+ answered_question_ids: Sequence[str] = (),
224
+ idempotency_key: str | None = None,
225
+ ) -> NextQuestionsResponse:
226
+ """Return the next best question for a conversation."""
227
+
228
+ response = self._post(
229
+ "/v1/next-questions",
230
+ payload=_next_payload(
231
+ session_id=session_id,
232
+ conversation_history=conversation_history,
233
+ context=context,
234
+ answered_question_ids=answered_question_ids,
235
+ ),
236
+ idempotency_key=_idempotency_key(idempotency_key),
237
+ )
238
+ return NextQuestionsResponse.from_payload(_response_payload(response))
239
+
240
+ def report_conversion(
241
+ self,
242
+ *,
243
+ session_id: str,
244
+ outcome: Outcome,
245
+ metadata: Mapping[str, Any] | None = None,
246
+ idempotency_key: str | None = None,
247
+ ) -> ConversionResponse:
248
+ """Report the final business outcome of a conversation."""
249
+
250
+ if not session_id.strip():
251
+ raise ValueError("session_id must not be empty")
252
+ if len(session_id) > MAX_SESSION_ID_CHARS:
253
+ raise ValueError(f"session_id must not exceed {MAX_SESSION_ID_CHARS} characters")
254
+ response = self._post(
255
+ f"/v1/sessions/{quote(session_id, safe='')}/conversion",
256
+ payload=_conversion_payload(outcome=outcome, metadata=metadata),
257
+ idempotency_key=_idempotency_key(idempotency_key),
258
+ )
259
+ return ConversionResponse.from_payload(_response_payload(response))
260
+
261
+
262
+ class AsyncNBQClient:
263
+ """Async client for the hosted NBQ runtime API."""
264
+
265
+ def __init__(
266
+ self,
267
+ *,
268
+ api_key: str,
269
+ base_url: str = DEFAULT_BASE_URL,
270
+ timeout: float = DEFAULT_TIMEOUT_SECONDS,
271
+ max_retries: int = DEFAULT_MAX_RETRIES,
272
+ transport: httpx.AsyncBaseTransport | None = None,
273
+ ) -> None:
274
+ _validate_settings(api_key, base_url, timeout, max_retries)
275
+ self._max_retries = max_retries
276
+ self._http = httpx.AsyncClient(
277
+ base_url=base_url.rstrip("/"),
278
+ headers=_request_headers(api_key),
279
+ timeout=timeout,
280
+ transport=transport,
281
+ )
282
+
283
+ async def __aenter__(self) -> AsyncNBQClient:
284
+ return self
285
+
286
+ async def __aexit__(self, *_: object) -> None:
287
+ await self.close()
288
+
289
+ async def close(self) -> None:
290
+ await self._http.aclose()
291
+
292
+ async def _post(
293
+ self, path: str, *, payload: Mapping[str, Any], idempotency_key: str
294
+ ) -> httpx.Response:
295
+ response: httpx.Response | None = None
296
+ for attempt in range(self._max_retries + 1):
297
+ try:
298
+ response = await self._http.post(
299
+ path,
300
+ json=payload,
301
+ headers={"Idempotency-Key": idempotency_key},
302
+ )
303
+ except httpx.TransportError as exc:
304
+ if attempt >= self._max_retries:
305
+ raise NBQConnectionError("Unable to reach the NBQ API") from exc
306
+ await asyncio.sleep(_retry_delay(None, attempt))
307
+ continue
308
+
309
+ if response.status_code not in RETRIABLE_STATUS_CODES or attempt >= self._max_retries:
310
+ break
311
+ await asyncio.sleep(_retry_delay(response, attempt))
312
+
313
+ assert response is not None
314
+ _raise_for_api_error(response)
315
+ return response
316
+
317
+ async def next_question(
318
+ self,
319
+ *,
320
+ session_id: str,
321
+ conversation_history: Sequence[MessageInput] = (),
322
+ context: str | None = None,
323
+ answered_question_ids: Sequence[str] = (),
324
+ idempotency_key: str | None = None,
325
+ ) -> NextQuestionsResponse:
326
+ """Return the next best question for a conversation."""
327
+
328
+ response = await self._post(
329
+ "/v1/next-questions",
330
+ payload=_next_payload(
331
+ session_id=session_id,
332
+ conversation_history=conversation_history,
333
+ context=context,
334
+ answered_question_ids=answered_question_ids,
335
+ ),
336
+ idempotency_key=_idempotency_key(idempotency_key),
337
+ )
338
+ return NextQuestionsResponse.from_payload(_response_payload(response))
339
+
340
+ async def report_conversion(
341
+ self,
342
+ *,
343
+ session_id: str,
344
+ outcome: Outcome,
345
+ metadata: Mapping[str, Any] | None = None,
346
+ idempotency_key: str | None = None,
347
+ ) -> ConversionResponse:
348
+ """Report the final business outcome of a conversation."""
349
+
350
+ if not session_id.strip():
351
+ raise ValueError("session_id must not be empty")
352
+ if len(session_id) > MAX_SESSION_ID_CHARS:
353
+ raise ValueError(f"session_id must not exceed {MAX_SESSION_ID_CHARS} characters")
354
+ response = await self._post(
355
+ f"/v1/sessions/{quote(session_id, safe='')}/conversion",
356
+ payload=_conversion_payload(outcome=outcome, metadata=metadata),
357
+ idempotency_key=_idempotency_key(idempotency_key),
358
+ )
359
+ return ConversionResponse.from_payload(_response_payload(response))
@@ -0,0 +1,85 @@
1
+ """Exceptions raised by the NBQ SDK."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping
6
+ from typing import Any
7
+
8
+
9
+ class NBQError(Exception):
10
+ """Base class for every SDK error."""
11
+
12
+
13
+ class NBQConnectionError(NBQError):
14
+ """The API could not be reached after retrying."""
15
+
16
+
17
+ class NBQAPIError(NBQError):
18
+ """The NBQ API returned an unsuccessful response."""
19
+
20
+ def __init__(
21
+ self,
22
+ message: str,
23
+ *,
24
+ status_code: int,
25
+ request_id: str | None = None,
26
+ error_type: str | None = None,
27
+ detail: Any = None,
28
+ ) -> None:
29
+ super().__init__(message)
30
+ self.status_code = status_code
31
+ self.request_id = request_id
32
+ self.error_type = error_type
33
+ self.detail = detail
34
+
35
+
36
+ class NBQAuthenticationError(NBQAPIError):
37
+ """The runtime credential is missing, invalid or not authorised."""
38
+
39
+
40
+ class NBQValidationError(NBQAPIError):
41
+ """The request does not satisfy the API contract."""
42
+
43
+
44
+ class NBQConflictError(NBQAPIError):
45
+ """An idempotency key or future state version conflicts."""
46
+
47
+
48
+ class NBQRateLimitError(NBQAPIError):
49
+ """The runtime credential exceeded its rate limit."""
50
+
51
+
52
+ class NBQServerError(NBQAPIError):
53
+ """The NBQ service failed to process the request."""
54
+
55
+
56
+ def api_error_from_payload(
57
+ *, status_code: int, payload: Mapping[str, Any] | None, request_id: str | None
58
+ ) -> NBQAPIError:
59
+ data = payload or {}
60
+ title = data.get("title")
61
+ detail = data.get("detail")
62
+ error_type = data.get("type")
63
+ message = str(title or detail or f"NBQ API request failed with status {status_code}")
64
+
65
+ error_class: type[NBQAPIError]
66
+ if status_code in (401, 403):
67
+ error_class = NBQAuthenticationError
68
+ elif status_code == 409:
69
+ error_class = NBQConflictError
70
+ elif status_code == 422:
71
+ error_class = NBQValidationError
72
+ elif status_code == 429:
73
+ error_class = NBQRateLimitError
74
+ elif status_code >= 500:
75
+ error_class = NBQServerError
76
+ else:
77
+ error_class = NBQAPIError
78
+
79
+ return error_class(
80
+ message,
81
+ status_code=status_code,
82
+ request_id=request_id,
83
+ error_type=str(error_type) if error_type is not None else None,
84
+ detail=detail,
85
+ )
@@ -0,0 +1,99 @@
1
+ """Public data models returned by the NBQ runtime API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Mapping, Sequence
6
+ from dataclasses import dataclass
7
+ from typing import Any, Literal, TypeAlias, cast
8
+
9
+ Role: TypeAlias = Literal["user", "assistant"]
10
+ Outcome: TypeAlias = Literal["purchase", "lead", "abandon", "other"]
11
+
12
+ MAX_MESSAGE_CHARS = 2000
13
+
14
+
15
+ @dataclass(frozen=True, slots=True)
16
+ class Message:
17
+ """A conversation message accepted by the NBQ runtime API."""
18
+
19
+ role: Role
20
+ content: str
21
+
22
+ def __post_init__(self) -> None:
23
+ if self.role not in ("user", "assistant"):
24
+ raise ValueError("role must be 'user' or 'assistant'")
25
+ if not self.content.strip():
26
+ raise ValueError("content must not be empty")
27
+ if len(self.content) > MAX_MESSAGE_CHARS:
28
+ raise ValueError(f"content must not exceed {MAX_MESSAGE_CHARS} characters")
29
+
30
+ def to_payload(self) -> dict[str, str]:
31
+ return {"role": self.role, "content": self.content}
32
+
33
+
34
+ MessageInput: TypeAlias = Message | Mapping[str, str]
35
+
36
+
37
+ @dataclass(frozen=True, slots=True)
38
+ class NextQuestion:
39
+ external_id: str
40
+ text: str
41
+
42
+ @classmethod
43
+ def from_payload(cls, payload: Mapping[str, Any]) -> NextQuestion:
44
+ return cls(external_id=str(payload["external_id"]), text=str(payload["text"]))
45
+
46
+
47
+ @dataclass(frozen=True, slots=True)
48
+ class NextQuestionsResponse:
49
+ next_question: NextQuestion | None
50
+ exhausted: bool
51
+ nbq_version: str
52
+ request_id: str
53
+
54
+ @classmethod
55
+ def from_payload(cls, payload: Mapping[str, Any]) -> NextQuestionsResponse:
56
+ raw_question = payload.get("next_question")
57
+ question = (
58
+ NextQuestion.from_payload(cast(Mapping[str, Any], raw_question))
59
+ if isinstance(raw_question, Mapping)
60
+ else None
61
+ )
62
+ return cls(
63
+ next_question=question,
64
+ exhausted=bool(payload["exhausted"]),
65
+ nbq_version=str(payload["nbq_version"]),
66
+ request_id=str(payload["request_id"]),
67
+ )
68
+
69
+
70
+ @dataclass(frozen=True, slots=True)
71
+ class ConversionResponse:
72
+ conversion_id: str
73
+ request_id: str
74
+
75
+ @classmethod
76
+ def from_payload(cls, payload: Mapping[str, Any]) -> ConversionResponse:
77
+ return cls(
78
+ conversion_id=str(payload["conversion_id"]),
79
+ request_id=str(payload["request_id"]),
80
+ )
81
+
82
+
83
+ def serialize_messages(messages: Sequence[MessageInput]) -> list[dict[str, str]]:
84
+ result: list[dict[str, str]] = []
85
+ for message in messages:
86
+ if isinstance(message, Message):
87
+ result.append(message.to_payload())
88
+ continue
89
+
90
+ role = message.get("role")
91
+ content = message.get("content")
92
+ if role not in ("user", "assistant"):
93
+ raise ValueError("each message role must be 'user' or 'assistant'")
94
+ if not content or not content.strip():
95
+ raise ValueError("each message content must not be empty")
96
+ if len(content) > MAX_MESSAGE_CHARS:
97
+ raise ValueError(f"each message content must not exceed {MAX_MESSAGE_CHARS} characters")
98
+ result.append({"role": role, "content": content})
99
+ return result
File without changes