langchain-crossly 0.1.0__py3-none-any.whl

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.
@@ -0,0 +1,48 @@
1
+ """LangChain integration for Crossly, the crosslisting platform for resellers."""
2
+
3
+ from langchain_crossly._client import CrosslyAPIWrapper, CrosslyError
4
+ from langchain_crossly._version import __version__
5
+ from langchain_crossly.toolkits import CrosslyToolkit
6
+ from langchain_crossly.tools import (
7
+ ALL_TOOLS,
8
+ CrosslyBaseTool,
9
+ CrosslySearchTool,
10
+ CrosslyListListingsTool,
11
+ CrosslyGetListingTool,
12
+ CrosslyCreateDraftListingTool,
13
+ CrosslyUpdateListingPriceTool,
14
+ CrosslyCrosspostListingTool,
15
+ CrosslyDelistListingTool,
16
+ CrosslyListInventoryTool,
17
+ CrosslyAdjustInventoryQuantityTool,
18
+ CrosslyListOrdersTool,
19
+ CrosslyGetOrderTool,
20
+ CrosslyMarkOrderShippedTool,
21
+ CrosslyListOffersTool,
22
+ CrosslyRespondToOfferTool,
23
+ CrosslyGetSalesSummaryTool,
24
+ )
25
+
26
+ __all__ = [
27
+ "ALL_TOOLS",
28
+ "CrosslyAPIWrapper",
29
+ "CrosslyBaseTool",
30
+ "CrosslyError",
31
+ "CrosslyToolkit",
32
+ "CrosslySearchTool",
33
+ "CrosslyListListingsTool",
34
+ "CrosslyGetListingTool",
35
+ "CrosslyCreateDraftListingTool",
36
+ "CrosslyUpdateListingPriceTool",
37
+ "CrosslyCrosspostListingTool",
38
+ "CrosslyDelistListingTool",
39
+ "CrosslyListInventoryTool",
40
+ "CrosslyAdjustInventoryQuantityTool",
41
+ "CrosslyListOrdersTool",
42
+ "CrosslyGetOrderTool",
43
+ "CrosslyMarkOrderShippedTool",
44
+ "CrosslyListOffersTool",
45
+ "CrosslyRespondToOfferTool",
46
+ "CrosslyGetSalesSummaryTool",
47
+ "__version__",
48
+ ]
@@ -0,0 +1,225 @@
1
+ """A small HTTP client for the Crossly seller REST API (https://crossly.net/api/v1).
2
+
3
+ Every call sends the Personal Access Token as a bearer token, a ``langchain-crossly/<version>`` User-Agent and,
4
+ for writes, an ``Idempotency-Key`` that stays the same across retries of that call. 429 responses are retried for
5
+ every method (honouring ``Retry-After``); 5xx and network errors only for reads.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import email.utils
12
+ import json
13
+ import os
14
+ import time
15
+ import uuid
16
+ from typing import Any, Dict, Mapping, Optional
17
+
18
+ import httpx
19
+ from pydantic import BaseModel, ConfigDict, Field, SecretStr, model_validator
20
+
21
+ from ._version import PACKAGE, __version__
22
+
23
+ DEFAULT_BASE_URL = "https://crossly.net/api"
24
+ API_KEY_ENV = "CROSSLY_API_KEY"
25
+ BASE_URL_ENV = "CROSSLY_BASE_URL"
26
+
27
+ _READS = frozenset(("GET", "HEAD"))
28
+ _TRANSIENT = frozenset((500, 502, 503, 504))
29
+ _MAX_RETRY_WAIT = 10.0
30
+
31
+
32
+ class CrosslyError(Exception):
33
+ """A failed Crossly API call (or missing configuration), with a message an agent can act on."""
34
+
35
+ def __init__(self, message: str, status: Optional[int] = None, code: Optional[str] = None) -> None:
36
+ super().__init__(message)
37
+ self.status = status
38
+ self.code = code
39
+
40
+
41
+ def _retry_after(value: Optional[str]) -> Optional[float]:
42
+ if not value:
43
+ return None
44
+ try:
45
+ return max(0.0, float(value))
46
+ except ValueError:
47
+ pass
48
+ try:
49
+ when = email.utils.parsedate_to_datetime(value)
50
+ except (TypeError, ValueError):
51
+ return None
52
+ return max(0.0, when.timestamp() - time.time())
53
+
54
+
55
+ def _clean(params: Optional[Mapping[str, Any]]) -> Optional[Dict[str, Any]]:
56
+ """Drop unset values and render booleans the way the API's query parser reads them."""
57
+ if not params:
58
+ return None
59
+ out: Dict[str, Any] = {}
60
+ for key, value in params.items():
61
+ if value is None:
62
+ continue
63
+ out[key] = ("true" if value else "false") if isinstance(value, bool) else value
64
+ return out or None
65
+
66
+
67
+ def _error(response: httpx.Response) -> CrosslyError:
68
+ try:
69
+ payload = response.json()
70
+ except ValueError:
71
+ payload = None
72
+ code = message = correlation = None
73
+ if isinstance(payload, dict):
74
+ err = payload.get("error")
75
+ if isinstance(err, dict):
76
+ code, message = err.get("code"), err.get("message")
77
+ elif isinstance(err, str):
78
+ message = err
79
+ message = message or payload.get("message")
80
+ correlation = payload.get("correlationId")
81
+ text = f"Crossly API error {response.status_code}"
82
+ if code:
83
+ text += f" {code}"
84
+ text += f": {message or response.reason_phrase or 'request failed'}"
85
+ if response.status_code == 401:
86
+ text += " (check that CROSSLY_API_KEY is a valid crossly_pat_ token)"
87
+ if correlation:
88
+ text += f" [correlationId {correlation}]"
89
+ return CrosslyError(text, status=response.status_code, code=code)
90
+
91
+
92
+ def _result(response: httpx.Response) -> Any:
93
+ if response.status_code >= 400:
94
+ raise _error(response)
95
+ if not response.content:
96
+ return {"ok": True, "status": response.status_code}
97
+ try:
98
+ return response.json()
99
+ except ValueError:
100
+ return {"ok": True, "status": response.status_code, "body": response.text}
101
+
102
+
103
+ class CrosslyAPIWrapper(BaseModel):
104
+ """Configuration and transport for the Crossly seller API.
105
+
106
+ ``api_key`` defaults to the ``CROSSLY_API_KEY`` environment variable (a Personal Access Token,
107
+ ``crossly_pat_…``, from Crossly → Settings → Developer). It is read when the wrapper is built and checked
108
+ when a tool runs, so a toolkit can be constructed before the key is configured.
109
+ """
110
+
111
+ model_config = ConfigDict(arbitrary_types_allowed=True)
112
+
113
+ api_key: Optional[SecretStr] = Field(default=None)
114
+ base_url: str = Field(default=DEFAULT_BASE_URL)
115
+ timeout: float = Field(default=30.0)
116
+ max_retries: int = Field(default=2)
117
+ user_agent: str = Field(default=f"{PACKAGE}/{__version__}")
118
+
119
+ @model_validator(mode="before")
120
+ @classmethod
121
+ def _from_env(cls, values: Any) -> Any:
122
+ if not isinstance(values, dict):
123
+ return values
124
+ values = dict(values)
125
+ if not values.get("api_key") and os.environ.get(API_KEY_ENV):
126
+ values["api_key"] = os.environ[API_KEY_ENV]
127
+ if not values.get("base_url") and os.environ.get(BASE_URL_ENV):
128
+ values["base_url"] = os.environ[BASE_URL_ENV]
129
+ return values
130
+
131
+ def _headers(self, method: str, idempotency_key: Optional[str]) -> Dict[str, str]:
132
+ if self.api_key is None or not self.api_key.get_secret_value():
133
+ raise CrosslyError(
134
+ f"No Crossly API key. Set the {API_KEY_ENV} environment variable to a Personal Access Token "
135
+ "(crossly_pat_…, from Crossly → Settings → Developer) or pass api_key."
136
+ )
137
+ headers = {
138
+ "Authorization": f"Bearer {self.api_key.get_secret_value()}",
139
+ "Accept": "application/json",
140
+ "User-Agent": self.user_agent,
141
+ }
142
+ if method not in _READS:
143
+ headers["Idempotency-Key"] = idempotency_key or str(uuid.uuid4())
144
+ return headers
145
+
146
+ def _url(self, path: str) -> str:
147
+ return self.base_url.rstrip("/") + path
148
+
149
+ def _wait(self, method: str, attempt: int, response: Optional[httpx.Response]) -> Optional[float]:
150
+ """Seconds to wait before retrying, or None when the call must not be retried."""
151
+ if attempt >= self.max_retries:
152
+ return None
153
+ if response is None:
154
+ retryable = method in _READS
155
+ elif response.status_code == 429:
156
+ retryable = True
157
+ else:
158
+ retryable = method in _READS and response.status_code in _TRANSIENT
159
+ if not retryable:
160
+ return None
161
+ hinted = _retry_after(response.headers.get("Retry-After")) if response is not None else None
162
+ return min(_MAX_RETRY_WAIT, hinted if hinted is not None else 0.5 * (2**attempt))
163
+
164
+ def request(
165
+ self,
166
+ method: str,
167
+ path: str,
168
+ *,
169
+ params: Optional[Mapping[str, Any]] = None,
170
+ body: Any = None,
171
+ ) -> Any:
172
+ """Call the API and return the decoded JSON. Raises CrosslyError on an error response."""
173
+ headers = self._headers(method, None)
174
+ attempt = 0
175
+ with httpx.Client(timeout=self.timeout) as client:
176
+ while True:
177
+ response: Optional[httpx.Response] = None
178
+ try:
179
+ response = client.request(
180
+ method, self._url(path), params=_clean(params), json=body, headers=headers
181
+ )
182
+ except httpx.HTTPError as exc:
183
+ wait = self._wait(method, attempt, None)
184
+ if wait is None:
185
+ raise CrosslyError(f"Could not reach the Crossly API: {exc}") from exc
186
+ else:
187
+ wait = self._wait(method, attempt, response) if response.status_code >= 429 else None
188
+ if wait is None:
189
+ return _result(response)
190
+ time.sleep(wait)
191
+ attempt += 1
192
+
193
+ async def arequest(
194
+ self,
195
+ method: str,
196
+ path: str,
197
+ *,
198
+ params: Optional[Mapping[str, Any]] = None,
199
+ body: Any = None,
200
+ ) -> Any:
201
+ """Async :meth:`request`."""
202
+ headers = self._headers(method, None)
203
+ attempt = 0
204
+ async with httpx.AsyncClient(timeout=self.timeout) as client:
205
+ while True:
206
+ response: Optional[httpx.Response] = None
207
+ try:
208
+ response = await client.request(
209
+ method, self._url(path), params=_clean(params), json=body, headers=headers
210
+ )
211
+ except httpx.HTTPError as exc:
212
+ wait = self._wait(method, attempt, None)
213
+ if wait is None:
214
+ raise CrosslyError(f"Could not reach the Crossly API: {exc}") from exc
215
+ else:
216
+ wait = self._wait(method, attempt, response) if response.status_code >= 429 else None
217
+ if wait is None:
218
+ return _result(response)
219
+ await asyncio.sleep(wait)
220
+ attempt += 1
221
+
222
+
223
+ def to_json(value: Any) -> str:
224
+ """Compact JSON for a tool's string output."""
225
+ return json.dumps(value, ensure_ascii=False, separators=(",", ":"), default=str)