@gullabs/xai 0.2.0

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.
package/LICENSE ADDED
@@ -0,0 +1,191 @@
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 made available under
36
+ the License, as indicated by a copyright notice that is included in
37
+ or attached to the work (an example is provided in the Appendix below).
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other
42
+ transformations represent, as a whole, an original work of authorship.
43
+ For the purposes of this License, Derivative Works shall not include
44
+ works that remain separable from, or merely link (or bind by name)
45
+ to the interfaces of, the Work and Derivative Works thereof.
46
+
47
+ "Contribution" shall mean, as submitted to the Licensor for inclusion
48
+ in the Work by the copyright owner or by an individual or Legal Entity
49
+ authorized to submit on behalf of the copyright owner. For the purposes
50
+ of this definition, "submitted" means any form of electronic, verbal,
51
+ or written communication sent to the Licensor or its representatives,
52
+ including but not limited to communication on electronic mailing lists,
53
+ source code control systems, and issue tracking systems that are managed
54
+ by, or on behalf of, the Licensor for the purpose of discussing and
55
+ improving the Work, but excluding communication that is conspicuously
56
+ marked or designated in writing by the copyright owner as "Not a
57
+ Contribution."
58
+
59
+ "Contributor" shall mean Licensor and any Legal Entity on behalf of
60
+ whom a Contribution has been received by the Licensor and included
61
+ within the Work.
62
+
63
+ 2. Grant of Copyright License. Subject to the terms and conditions of
64
+ this License, each Contributor hereby grants to You a perpetual,
65
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
66
+ copyright license to reproduce, prepare Derivative Works of,
67
+ publicly display, publicly perform, sublicense, and distribute the
68
+ Work and such Derivative Works in Source or Object form.
69
+
70
+ 3. Grant of Patent License. Subject to the terms and conditions of
71
+ this License, each Contributor hereby grants to You a perpetual,
72
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
73
+ (except as stated in this section) patent license to make, have made,
74
+ use, offer to sell, sell, import, and otherwise transfer the Work,
75
+ where such license applies only to those patent claims licensable
76
+ by such Contributor that are necessarily infringed by their
77
+ Contribution(s) alone or by the combination of their Contribution(s)
78
+ with the Work to which such Contribution(s) was submitted. If You
79
+ institute patent litigation against any entity (including a cross-claim
80
+ or counterclaim in a lawsuit) alleging that the Work or any patent
81
+ claim embodied in the Work constitutes direct or contributory patent
82
+ infringement, then any patent licenses granted to You under this
83
+ License for that Work shall terminate as of the date such litigation
84
+ is filed.
85
+
86
+ 4. Redistribution. You may reproduce and distribute copies of the
87
+ Work or Derivative Works thereof in any medium, with or without
88
+ modifications, and in Source or Object form, provided that You
89
+ meet the following conditions:
90
+
91
+ (a) You must give any other recipients of the Work or Derivative
92
+ Works a copy of this License; and
93
+
94
+ (b) You must cause any modified files to carry prominent notices
95
+ stating that You changed the files; and
96
+
97
+ (c) You must retain, in the Source form of any Derivative Works
98
+ that You distribute, all copyright, patent, trademark, and
99
+ attribution notices from the Source form of the Work,
100
+ excluding those notices that do not pertain to any part of
101
+ the Derivative Works; and
102
+
103
+ (d) If the Work includes a "NOTICE" text file as part of its
104
+ distribution, You must include a readable copy of the
105
+ attribution notices contained within such NOTICE file, in
106
+ at least one of the following places: within a NOTICE text
107
+ file distributed as part of the Derivative Works; within
108
+ the Source form or documentation, if provided along with the
109
+ Derivative Works; or, within a display generated by the
110
+ Derivative Works, if and wherever such third-party notices
111
+ normally appear. The contents of the NOTICE file are for
112
+ informational purposes only and do not modify the License.
113
+ You may add Your own attribution notices within Derivative
114
+ Works that You distribute, alongside or in addition to the
115
+ NOTICE text from the Work, provided that such additional
116
+ attribution notices cannot be construed as modifying the
117
+ License.
118
+
119
+ You may add Your own license statement for Your modifications and
120
+ may provide additional grant of rights to use, reproduce, modify,
121
+ and distribute Your modifications as a separate agreement from
122
+ this License.
123
+
124
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
125
+ any Contribution intentionally submitted for inclusion in the Work
126
+ by You to the Licensor shall be under the terms and conditions of
127
+ this License, without any additional terms or conditions.
128
+ Notwithstanding the above, nothing herein shall supersede or modify
129
+ the terms of any separate license agreement you may have executed
130
+ with Licensor regarding such Contributions.
131
+
132
+ 6. Trademarks. This License does not grant permission to use the trade
133
+ names, trademarks, service marks, or product names of the Licensor,
134
+ except as required for reasonable and customary use in describing the
135
+ origin of the Work and reproducing the content of the NOTICE file.
136
+
137
+ 7. Disclaimer of Warranty. Unless required by applicable law or
138
+ agreed to in writing, Licensor provides the Work (and each
139
+ Contributor provides its Contributions) on an "AS IS" BASIS,
140
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
141
+ implied, including, without limitation, any warranties or conditions
142
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
143
+ PARTICULAR PURPOSE. You are solely responsible for determining the
144
+ appropriateness of using or reproducing the Work and assume any
145
+ risks associated with Your exercise of permissions under this License.
146
+
147
+ 8. Limitation of Liability. In no event and under no legal theory,
148
+ whether in tort (including negligence), contract, or otherwise,
149
+ unless required by applicable law (such as deliberate and grossly
150
+ negligent acts) or agreed to in writing, shall any Contributor be
151
+ liable to You for damages, including any direct, indirect, special,
152
+ incidental, or exemplary damages of any character arising as a
153
+ result of this License or out of the use or inability to use the
154
+ Work (including but not limited to damages for loss of goodwill,
155
+ work stoppage, computer failure or malfunction, or all other
156
+ commercial damages or losses), even if such Contributor has been
157
+ advised of the possibility of such damages.
158
+
159
+ 9. Accepting Warranty or Additional Liability. While redistributing
160
+ the Work or Derivative Works thereof, You may choose to offer,
161
+ and charge a fee for, acceptance of support, warranty, indemnity,
162
+ or other liability obligations and/or rights consistent with this
163
+ License. However, in accepting such obligations, You may offer only
164
+ conditions that are consistent with this terms and conditions of this
165
+ License, and may charge a fee for such acceptance only in a manner
166
+ consistent with the terms of this License.
167
+
168
+ END OF TERMS AND CONDITIONS
169
+
170
+ APPENDIX: How to apply the Apache License to your work.
171
+
172
+ To apply the Apache License to your work, attach the following
173
+ boilerplate notice, with the fields enclosed by brackets "[]"
174
+ replaced with your own identifying information. (Don't include
175
+ the brackets!) The text should be enclosed in the appropriate
176
+ comment syntax for the file format in please. Also attach a copy of
177
+ this License to your work.
178
+
179
+ Copyright 2026 Gul Labs
180
+
181
+ Licensed under the Apache License, Version 2.0 (the "License");
182
+ you may not use this file except in compliance with the License.
183
+ You may obtain a copy of the License at
184
+
185
+ http://www.apache.org/licenses/LICENSE-2.0
186
+
187
+ Unless required by applicable law or agreed to in writing, software
188
+ distributed under the License is distributed on an "AS IS" BASIS,
189
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
190
+ See the License for the specific language governing permissions and
191
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,115 @@
1
+ # @gullabs/xai
2
+
3
+ xAI Grok provider adapter for any-llm. A thin mapping layer over the `openai` npm SDK's Responses API pointed at xAI's `https://api.x.ai/v1` base URL — converts `ResolvedRequest` → xAI Responses API params and maps the response back to `AdapterResult`. Never persists, never computes cost itself outside the pricing port, never loops — pure request/response.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ pnpm add @gullabs/xai @gullabs/core openai
9
+ ```
10
+
11
+ **Peer dependency:** `openai ^6`
12
+
13
+ xAI has no first-party TypeScript SDK. xAI's own quickstart recommends using the `openai` npm package with a `baseURL` override pointed at xAI's endpoint — that is the path this adapter takes. `buildXaiClient` is the only place in `packages/xai/src` that imports `openai`, so the rest of the adapter (and its tests) stay decoupled from the real SDK via the structural `XaiClientLike` interface.
14
+
15
+ ## Key exports
16
+
17
+ | Export | What it is |
18
+ | ----------------------- | ----------------------------------------------------------------------------------------------- |
19
+ | `xaiProvider(opts?)` | `ProviderPlugin` factory — bundles the adapter, `grok-4.5` model descriptor, and pricing source |
20
+ | `xaiAdapter(opts?)` | Creates the `ProviderAdapter` for xAI |
21
+ | `XaiAdapterOptions` | `{ client?: XaiClientLike }` — inject a pre-built or fake client |
22
+ | `XaiClientLike` | Structural interface the adapter depends on (satisfied by real SDK and fakes) |
23
+ | `buildXaiClient(auth)` | Builds the real `openai`-SDK-backed client from `AuthMaterial`, pointed at xAI's base URL |
24
+ | `classifyXaiError(err)` | Classifies a raw thrown error into a typed `LlmError`, including xAI's 400-for-auth quirk |
25
+ | `grok45ModelDescriptor` | The `grok-4.5` `ModelDescriptor` |
26
+ | `xaiModelDescriptors` | Every model descriptor this package contributes (v1: just `grok45ModelDescriptor`) |
27
+ | `xaiRegistry` | Pre-built `ModelRegistry` over `xaiModelDescriptors` |
28
+ | `xaiPricingSource()` | Built-in xAI `PricingSource` port implementation, backed by `XAI_PRICING` |
29
+ | `XAI_PRICING` | Frozen xAI pricing snapshot (µUSD per million tokens) |
30
+ | `XaiModelRates` | Per-model rate entry type (`inputPerM`, `cachedPerM`, `outputPerM`, optional `gt200k`) |
31
+ | `Grok45ConfigSchema` | Strict Zod config schema for `grok-4.5` |
32
+ | `XaiProviderOptions` | `{ promptCacheKey? }` — typed `providerOptions.xai` extension shape |
33
+
34
+ ## Quick example
35
+
36
+ ```ts
37
+ import { createClient, composeProviders } from '@gullabs/core'
38
+ import { xaiProvider } from '@gullabs/xai'
39
+
40
+ const client = createClient({
41
+ ...composeProviders([xaiProvider()]),
42
+ })
43
+
44
+ // Auth is required per call — the library never reads environment variables.
45
+ const result = await client.generate(
46
+ {
47
+ provider: 'xai',
48
+ model: 'grok-4.5',
49
+ messages: [{ role: 'user', parts: [{ kind: 'text', text: 'Hello' }] }],
50
+ },
51
+ { auth: { apiKey: 'YOUR_XAI_API_KEY' } },
52
+ )
53
+ ```
54
+
55
+ ## grok-4.5
56
+
57
+ The default registry ships exactly one model: `grok-4.5` (500k token context window). It routes through this adapter and supports:
58
+
59
+ - **Reasoning** — level-api (`reasoningApi: 'level'`), mapped to the Responses API `reasoning.effort` field. `admittedReasoningEfforts: ['low', 'high']` — this is deliberately narrower than Gemini's effort vocabulary: `'none'` and `'medium'` are **rejected by the live xAI API**, not merely unsupported by this library. The config schema (`Grok45ConfigSchema`) enforces `reasoning.effort` as `'low' | 'high'` only, and there is no `budgetTokens` field at all (xAI uses level-style reasoning, not token budgets) — passing it throws `bad_request`. The schema does not set a default effort; if `reasoning` is omitted, no `reasoning` field is sent and xAI's own server-side default applies.
60
+ - **Structured output** — native. `output.jsonSchema` maps to the Responses API's `text.format` field with `{ type: 'json_schema', name, schema, strict: true }`, **not** `response_format` — this differs from OpenAI's own convention for the same underlying concept.
61
+ - **Sampling** — `temperature` and `topP` are forwarded verbatim. No `topK`.
62
+ - **No penalties/stop** — `presence_penalty`, `frequency_penalty`, and `stop` are not in the config schema at all; xAI hard-rejects these on reasoning models, so the schema never admits them (reject-don't-map).
63
+ - **No service tiers** — xAI has no service-tier concept for `grok-4.5`; setting `serviceTier` on the request throws `bad_request`.
64
+
65
+ ## Vision constraints
66
+
67
+ `grok-4.5` accepts image input as an `inline-media` or `file-uri` `Part`:
68
+
69
+ - **`inline-media`** — only `image/jpeg` and `image/png` are accepted; anything else throws `bad_request`. The decoded payload must be at most 20 MiB (xAI's documented inline-image ceiling); larger images throw `bad_request` before the request is sent.
70
+ - **`file-uri`** — only accepted when the URI is a public `http(s)://` URL **and** the declared `mimeType` is jpg/png. A provider-hosted URI from another provider — for example a Gemini Files API URI (`https://generativelanguage.googleapis.com/...`) — is technically `https://` but is not dereferenceable by xAI and is not portable across providers. The adapter rejects it rather than trying to map or proxy it (reject-don't-map).
71
+ - **Undocumented minimum size** — xAI enforces an undocumented server-side minimum image size (observed ~8px/side, ~512 total px). This adapter does **not** pre-validate pixel dimensions; a too-small image surfaces as a live `bad_request` error from the xAI API itself, classified normally by `classifyXaiError`, not rejected client-side.
72
+
73
+ ## Caching
74
+
75
+ xAI caching is automatic — there is no explicit cache-create/cache-store API comparable to Gemini's Context Cache. `providerOptions.xai.promptCacheKey` maps to the Responses API's `prompt_cache_key` field and is strongly recommended for reliable cache routing across calls to the same conversation/context.
76
+
77
+ ## Pricing
78
+
79
+ `XAI_PRICING` is a frozen, versioned snapshot (`xaiPricingVersion: 'xai-2026-07-09'`) — a point-in-time capture, not a live lookup, following the same frozen-snapshot precedent as Gemini pricing (ADR-005). Rates are in µUSD per million tokens:
80
+
81
+ | Model | Tier | Input | Cached input | Output |
82
+ | ---------- | ---------------------------- | ------- | ------------ | -------- |
83
+ | `grok-4.5` | standard (≤200k gross input) | $2.00/M | $0.50/M | $6.00/M |
84
+ | `grok-4.5` | `gt200k` (>200k gross input) | $4.00/M | $1.00/M | $12.00/M |
85
+
86
+ The `gt200k` long-context tier is selected by **gross** `inputTokens` (including cached), not billable input — strictly greater than 200,000 tokens, mirroring core's `selectRates` convention. `grok-4.5` has no service-tier concept; a defined `tier` argument to `xaiPricingSource().price()` always resolves to unpriced (`microUsd: null`) rather than guessing a multiplier.
87
+
88
+ ## EU unavailability
89
+
90
+ xAI has no EU region at launch — its documented regions are `us-east-1` and `us-west-2` only. This is a hosting/deployment concern for callers, not something this library can route around; it is documented here so consumers are not surprised by data-residency constraints.
91
+
92
+ ## Aliases are not registered
93
+
94
+ xAI's own `/v1/models` listing surfaces `grok-4.5-latest` and `grok-build-latest` as aliases of `grok-4.5`. Neither is registered as a separate `ModelDescriptor` or `XAI_PRICING` key. Callers must use the canonical id `grok-4.5` verbatim — passing an alias resolves to "model not found" in the registry, not to `grok-4.5`'s config or pricing (reject-don't-map).
95
+
96
+ ## Explicitly deferred (not built in v1)
97
+
98
+ - Server-side agentic tools (`web_search`, `x_search`, `code_interpreter`, file/collections search, remote MCP) and their per-invocation billing (e.g. `web_search` at $5/1k) — no `Cost` lane exists for these yet.
99
+ - `/v1/chat/completions` (documented by xAI as legacy) and `/v1/messages` (the Anthropic-compatible migration shim) — this adapter only targets `/v1/responses`.
100
+ - Batch API (`grok-4.5` is not eligible at launch) and image generation models.
101
+ - Stateful conversations — `store` is always sent as `false`, and `previous_response_id` is not supported.
102
+ - Streaming — core has no streaming seam at all yet; this is a library-wide gap, not specific to xai.
103
+
104
+ ## What it maps
105
+
106
+ - `providerOptions.xai.promptCacheKey` → `prompt_cache_key`
107
+ - `reasoning.effort` → `reasoning.effort` (`'low' | 'high'` only)
108
+ - `output.jsonSchema` → `text.format: { type: 'json_schema', name, schema, strict: true }`
109
+ - Usage: `usage.input_tokens` → `inputTokens`, `usage.output_tokens` → `outputTokens` (both already GROSS on xAI, unlike Gemini's sub-field summation); numeric extras (`num_sources_used`, `cost_in_usd_ticks`, etc.) surface into `usage.details` under their raw names, and the full raw payload is always in `usage.raw`
110
+ - Errors: xAI's Responses API returns **HTTP 400 (not 401) for an invalid API key**. `classifyXaiError` special-cases the exact structured error-body signature (`code: 'invalid-argument'` with message prefix `"Incorrect API key provided"`, taken verbatim from a recorded live fixture) and reclassifies it as `invalid_auth`. It only inspects the STRUCTURED parsed error body — never free-form `Error.message` text — so a 400 that merely _mentions_ an API key (e.g. a schema-validation error echoing user content) stays `bad_request`. Any other 400, `429`→`rate_limited`, `5xx`→`server`, and timeouts fall through to `@gullabs/core`'s generic `classifyError`.
111
+
112
+ ## Learn more
113
+
114
+ - [Monorepo root README](../../README.md) — full architecture, auth model, and package overview
115
+ - [`@gullabs/core` README](../core/README.md) — engine, ports, and the `LlmError` contract