assassinlike commited on
Commit
bd64f48
·
verified ·
1 Parent(s): 6b9cd0a

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. data/conda_envs/evalclaw/lib/python3.11/site-packages/aiofiles/__pycache__/__init__.cpython-311.pyc +0 -0
  2. data/conda_envs/evalclaw/lib/python3.11/site-packages/aiofiles/__pycache__/base.cpython-311.pyc +0 -0
  3. data/conda_envs/evalclaw/lib/python3.11/site-packages/aiofiles/__pycache__/os.cpython-311.pyc +0 -0
  4. data/conda_envs/evalclaw/lib/python3.11/site-packages/aiofiles/__pycache__/ospath.cpython-311.pyc +0 -0
  5. data/conda_envs/evalclaw/lib/python3.11/site-packages/aiofiles/tempfile/__init__.py +357 -0
  6. data/conda_envs/evalclaw/lib/python3.11/site-packages/aiofiles/tempfile/__pycache__/__init__.cpython-311.pyc +0 -0
  7. data/conda_envs/evalclaw/lib/python3.11/site-packages/aiofiles/tempfile/__pycache__/temptypes.cpython-311.pyc +0 -0
  8. data/conda_envs/evalclaw/lib/python3.11/site-packages/aiofiles/tempfile/temptypes.py +70 -0
  9. data/conda_envs/evalclaw/lib/python3.11/site-packages/aiofiles/threadpool/__init__.py +141 -0
  10. data/conda_envs/evalclaw/lib/python3.11/site-packages/aiofiles/threadpool/__pycache__/__init__.cpython-311.pyc +0 -0
  11. data/conda_envs/evalclaw/lib/python3.11/site-packages/aiofiles/threadpool/__pycache__/binary.cpython-311.pyc +0 -0
  12. data/conda_envs/evalclaw/lib/python3.11/site-packages/aiofiles/threadpool/__pycache__/text.cpython-311.pyc +0 -0
  13. data/conda_envs/evalclaw/lib/python3.11/site-packages/aiofiles/threadpool/__pycache__/utils.cpython-311.pyc +0 -0
  14. data/conda_envs/evalclaw/lib/python3.11/site-packages/aiofiles/threadpool/binary.py +104 -0
  15. data/conda_envs/evalclaw/lib/python3.11/site-packages/aiofiles/threadpool/text.py +64 -0
  16. data/conda_envs/evalclaw/lib/python3.11/site-packages/aiofiles/threadpool/utils.py +71 -0
  17. data/conda_envs/evalclaw/lib/python3.11/site-packages/google_api_python_client-2.196.0.dist-info/licenses/LICENSE +201 -0
  18. data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/__pycache__/__init__.cpython-311.pyc +0 -0
  19. data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/__pycache__/__version__.cpython-311.pyc +0 -0
  20. data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/__pycache__/_api.cpython-311.pyc +0 -0
  21. data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/__pycache__/_auth.cpython-311.pyc +0 -0
  22. data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/__pycache__/_client.cpython-311.pyc +0 -0
  23. data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/__pycache__/_config.cpython-311.pyc +0 -0
  24. data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/__pycache__/_content.cpython-311.pyc +0 -0
  25. data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/__pycache__/_decoders.cpython-311.pyc +0 -0
  26. data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/__pycache__/_exceptions.cpython-311.pyc +0 -0
  27. data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/__pycache__/_main.cpython-311.pyc +0 -0
  28. data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/__pycache__/_models.cpython-311.pyc +0 -0
  29. data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/__pycache__/_multipart.cpython-311.pyc +0 -0
  30. data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/__pycache__/_status_codes.cpython-311.pyc +0 -0
  31. data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/__pycache__/_types.cpython-311.pyc +0 -0
  32. data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/__pycache__/_urlparse.cpython-311.pyc +0 -0
  33. data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/__pycache__/_urls.cpython-311.pyc +0 -0
  34. data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/__pycache__/_utils.cpython-311.pyc +0 -0
  35. data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/_transports/__init__.py +15 -0
  36. data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/_transports/__pycache__/__init__.cpython-311.pyc +0 -0
  37. data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/_transports/__pycache__/asgi.cpython-311.pyc +0 -0
  38. data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/_transports/__pycache__/base.cpython-311.pyc +0 -0
  39. data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/_transports/__pycache__/default.cpython-311.pyc +0 -0
  40. data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/_transports/__pycache__/mock.cpython-311.pyc +0 -0
  41. data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/_transports/__pycache__/wsgi.cpython-311.pyc +0 -0
  42. data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/_transports/asgi.py +187 -0
  43. data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/_transports/base.py +86 -0
  44. data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/_transports/default.py +406 -0
  45. data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/_transports/mock.py +43 -0
  46. data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/_transports/wsgi.py +149 -0
  47. data/conda_envs/evalclaw/lib/python3.11/site-packages/langchain_openai/__pycache__/__init__.cpython-311.pyc +0 -0
  48. data/conda_envs/evalclaw/lib/python3.11/site-packages/langchain_openai/chat_models/__init__.py +6 -0
  49. data/conda_envs/evalclaw/lib/python3.11/site-packages/langchain_openai/chat_models/_client_utils.py +683 -0
  50. data/conda_envs/evalclaw/lib/python3.11/site-packages/langchain_openai/chat_models/_compat.py +499 -0
data/conda_envs/evalclaw/lib/python3.11/site-packages/aiofiles/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (628 Bytes). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/aiofiles/__pycache__/base.cpython-311.pyc ADDED
Binary file (5.14 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/aiofiles/__pycache__/os.cpython-311.pyc ADDED
Binary file (1.84 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/aiofiles/__pycache__/ospath.cpython-311.pyc ADDED
Binary file (1.18 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/aiofiles/tempfile/__init__.py ADDED
@@ -0,0 +1,357 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import sys
3
+ from functools import partial, singledispatch
4
+ from io import BufferedRandom, BufferedReader, BufferedWriter, FileIO, TextIOBase
5
+ from tempfile import NamedTemporaryFile as syncNamedTemporaryFile
6
+ from tempfile import SpooledTemporaryFile as syncSpooledTemporaryFile
7
+ from tempfile import TemporaryDirectory as syncTemporaryDirectory
8
+ from tempfile import TemporaryFile as syncTemporaryFile
9
+ from tempfile import _TemporaryFileWrapper as syncTemporaryFileWrapper
10
+
11
+ from ..base import AiofilesContextManager
12
+ from ..threadpool.binary import AsyncBufferedIOBase, AsyncBufferedReader, AsyncFileIO
13
+ from ..threadpool.text import AsyncTextIOWrapper
14
+ from .temptypes import AsyncSpooledTemporaryFile, AsyncTemporaryDirectory
15
+
16
+ __all__ = [
17
+ "NamedTemporaryFile",
18
+ "TemporaryFile",
19
+ "SpooledTemporaryFile",
20
+ "TemporaryDirectory",
21
+ ]
22
+
23
+
24
+ # ================================================================
25
+ # Public methods for async open and return of temp file/directory
26
+ # objects with async interface
27
+ # ================================================================
28
+ if sys.version_info >= (3, 12):
29
+
30
+ def NamedTemporaryFile(
31
+ mode="w+b",
32
+ buffering=-1,
33
+ encoding=None,
34
+ newline=None,
35
+ suffix=None,
36
+ prefix=None,
37
+ dir=None,
38
+ delete=True,
39
+ delete_on_close=True,
40
+ loop=None,
41
+ executor=None,
42
+ ):
43
+ """Async open a named temporary file"""
44
+ return AiofilesContextManager(
45
+ _temporary_file(
46
+ named=True,
47
+ mode=mode,
48
+ buffering=buffering,
49
+ encoding=encoding,
50
+ newline=newline,
51
+ suffix=suffix,
52
+ prefix=prefix,
53
+ dir=dir,
54
+ delete=delete,
55
+ delete_on_close=delete_on_close,
56
+ loop=loop,
57
+ executor=executor,
58
+ )
59
+ )
60
+
61
+ else:
62
+
63
+ def NamedTemporaryFile(
64
+ mode="w+b",
65
+ buffering=-1,
66
+ encoding=None,
67
+ newline=None,
68
+ suffix=None,
69
+ prefix=None,
70
+ dir=None,
71
+ delete=True,
72
+ loop=None,
73
+ executor=None,
74
+ ):
75
+ """Async open a named temporary file"""
76
+ return AiofilesContextManager(
77
+ _temporary_file(
78
+ named=True,
79
+ mode=mode,
80
+ buffering=buffering,
81
+ encoding=encoding,
82
+ newline=newline,
83
+ suffix=suffix,
84
+ prefix=prefix,
85
+ dir=dir,
86
+ delete=delete,
87
+ loop=loop,
88
+ executor=executor,
89
+ )
90
+ )
91
+
92
+
93
+ def TemporaryFile(
94
+ mode="w+b",
95
+ buffering=-1,
96
+ encoding=None,
97
+ newline=None,
98
+ suffix=None,
99
+ prefix=None,
100
+ dir=None,
101
+ loop=None,
102
+ executor=None,
103
+ ):
104
+ """Async open an unnamed temporary file"""
105
+ return AiofilesContextManager(
106
+ _temporary_file(
107
+ named=False,
108
+ mode=mode,
109
+ buffering=buffering,
110
+ encoding=encoding,
111
+ newline=newline,
112
+ suffix=suffix,
113
+ prefix=prefix,
114
+ dir=dir,
115
+ loop=loop,
116
+ executor=executor,
117
+ )
118
+ )
119
+
120
+
121
+ def SpooledTemporaryFile(
122
+ max_size=0,
123
+ mode="w+b",
124
+ buffering=-1,
125
+ encoding=None,
126
+ newline=None,
127
+ suffix=None,
128
+ prefix=None,
129
+ dir=None,
130
+ loop=None,
131
+ executor=None,
132
+ ):
133
+ """Async open a spooled temporary file"""
134
+ return AiofilesContextManager(
135
+ _spooled_temporary_file(
136
+ max_size=max_size,
137
+ mode=mode,
138
+ buffering=buffering,
139
+ encoding=encoding,
140
+ newline=newline,
141
+ suffix=suffix,
142
+ prefix=prefix,
143
+ dir=dir,
144
+ loop=loop,
145
+ executor=executor,
146
+ )
147
+ )
148
+
149
+
150
+ def TemporaryDirectory(suffix=None, prefix=None, dir=None, loop=None, executor=None):
151
+ """Async open a temporary directory"""
152
+ return AiofilesContextManagerTempDir(
153
+ _temporary_directory(
154
+ suffix=suffix, prefix=prefix, dir=dir, loop=loop, executor=executor
155
+ )
156
+ )
157
+
158
+
159
+ # =========================================================
160
+ # Internal coroutines to open new temp files/directories
161
+ # =========================================================
162
+ if sys.version_info >= (3, 12):
163
+
164
+ async def _temporary_file(
165
+ named=True,
166
+ mode="w+b",
167
+ buffering=-1,
168
+ encoding=None,
169
+ newline=None,
170
+ suffix=None,
171
+ prefix=None,
172
+ dir=None,
173
+ delete=True,
174
+ delete_on_close=True,
175
+ loop=None,
176
+ executor=None,
177
+ max_size=0,
178
+ ):
179
+ """Async method to open a temporary file with async interface"""
180
+ if loop is None:
181
+ loop = asyncio.get_running_loop()
182
+
183
+ if named:
184
+ cb = partial(
185
+ syncNamedTemporaryFile,
186
+ mode=mode,
187
+ buffering=buffering,
188
+ encoding=encoding,
189
+ newline=newline,
190
+ suffix=suffix,
191
+ prefix=prefix,
192
+ dir=dir,
193
+ delete=delete,
194
+ delete_on_close=delete_on_close,
195
+ )
196
+ else:
197
+ cb = partial(
198
+ syncTemporaryFile,
199
+ mode=mode,
200
+ buffering=buffering,
201
+ encoding=encoding,
202
+ newline=newline,
203
+ suffix=suffix,
204
+ prefix=prefix,
205
+ dir=dir,
206
+ )
207
+
208
+ f = await loop.run_in_executor(executor, cb)
209
+
210
+ # Wrap based on type of underlying IO object
211
+ if type(f) is syncTemporaryFileWrapper:
212
+ # _TemporaryFileWrapper was used (named files)
213
+ result = wrap(f.file, f, loop=loop, executor=executor)
214
+ result._closer = f._closer
215
+ return result
216
+ # IO object was returned directly without wrapper
217
+ return wrap(f, f, loop=loop, executor=executor)
218
+
219
+ else:
220
+
221
+ async def _temporary_file(
222
+ named=True,
223
+ mode="w+b",
224
+ buffering=-1,
225
+ encoding=None,
226
+ newline=None,
227
+ suffix=None,
228
+ prefix=None,
229
+ dir=None,
230
+ delete=True,
231
+ loop=None,
232
+ executor=None,
233
+ max_size=0,
234
+ ):
235
+ """Async method to open a temporary file with async interface"""
236
+ if loop is None:
237
+ loop = asyncio.get_running_loop()
238
+
239
+ if named:
240
+ cb = partial(
241
+ syncNamedTemporaryFile,
242
+ mode=mode,
243
+ buffering=buffering,
244
+ encoding=encoding,
245
+ newline=newline,
246
+ suffix=suffix,
247
+ prefix=prefix,
248
+ dir=dir,
249
+ delete=delete,
250
+ )
251
+ else:
252
+ cb = partial(
253
+ syncTemporaryFile,
254
+ mode=mode,
255
+ buffering=buffering,
256
+ encoding=encoding,
257
+ newline=newline,
258
+ suffix=suffix,
259
+ prefix=prefix,
260
+ dir=dir,
261
+ )
262
+
263
+ f = await loop.run_in_executor(executor, cb)
264
+
265
+ # Wrap based on type of underlying IO object
266
+ if type(f) is syncTemporaryFileWrapper:
267
+ # _TemporaryFileWrapper was used (named files)
268
+ result = wrap(f.file, f, loop=loop, executor=executor)
269
+ # add delete property
270
+ result.delete = f.delete
271
+ return result
272
+ # IO object was returned directly without wrapper
273
+ return wrap(f, f, loop=loop, executor=executor)
274
+
275
+
276
+ async def _spooled_temporary_file(
277
+ max_size=0,
278
+ mode="w+b",
279
+ buffering=-1,
280
+ encoding=None,
281
+ newline=None,
282
+ suffix=None,
283
+ prefix=None,
284
+ dir=None,
285
+ loop=None,
286
+ executor=None,
287
+ ):
288
+ """Open a spooled temporary file with async interface"""
289
+ if loop is None:
290
+ loop = asyncio.get_running_loop()
291
+
292
+ cb = partial(
293
+ syncSpooledTemporaryFile,
294
+ max_size=max_size,
295
+ mode=mode,
296
+ buffering=buffering,
297
+ encoding=encoding,
298
+ newline=newline,
299
+ suffix=suffix,
300
+ prefix=prefix,
301
+ dir=dir,
302
+ )
303
+
304
+ f = await loop.run_in_executor(executor, cb)
305
+
306
+ # Single interface provided by SpooledTemporaryFile for all modes
307
+ return AsyncSpooledTemporaryFile(f, loop=loop, executor=executor)
308
+
309
+
310
+ async def _temporary_directory(
311
+ suffix=None, prefix=None, dir=None, loop=None, executor=None
312
+ ):
313
+ """Async method to open a temporary directory with async interface"""
314
+ if loop is None:
315
+ loop = asyncio.get_running_loop()
316
+
317
+ cb = partial(syncTemporaryDirectory, suffix, prefix, dir)
318
+ f = await loop.run_in_executor(executor, cb)
319
+
320
+ return AsyncTemporaryDirectory(f, loop=loop, executor=executor)
321
+
322
+
323
+ class AiofilesContextManagerTempDir(AiofilesContextManager):
324
+ """With returns the directory location, not the object (matching sync lib)"""
325
+
326
+ async def __aenter__(self):
327
+ self._obj = await self._coro
328
+ return self._obj.name
329
+
330
+
331
+ @singledispatch
332
+ def wrap(base_io_obj, file, *, loop=None, executor=None):
333
+ """Wrap the object with interface based on type of underlying IO"""
334
+
335
+ msg = f"Unsupported IO type: {base_io_obj}"
336
+ raise TypeError(msg)
337
+
338
+
339
+ @wrap.register(TextIOBase)
340
+ def _(base_io_obj, file, *, loop=None, executor=None):
341
+ return AsyncTextIOWrapper(file, loop=loop, executor=executor)
342
+
343
+
344
+ @wrap.register(BufferedWriter)
345
+ def _(base_io_obj, file, *, loop=None, executor=None):
346
+ return AsyncBufferedIOBase(file, loop=loop, executor=executor)
347
+
348
+
349
+ @wrap.register(BufferedReader)
350
+ @wrap.register(BufferedRandom)
351
+ def _(base_io_obj, file, *, loop=None, executor=None):
352
+ return AsyncBufferedReader(file, loop=loop, executor=executor)
353
+
354
+
355
+ @wrap.register(FileIO)
356
+ def _(base_io_obj, file, *, loop=None, executor=None):
357
+ return AsyncFileIO(file, loop=loop, executor=executor)
data/conda_envs/evalclaw/lib/python3.11/site-packages/aiofiles/tempfile/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (9.34 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/aiofiles/tempfile/__pycache__/temptypes.cpython-311.pyc ADDED
Binary file (3.95 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/aiofiles/tempfile/temptypes.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Async wrappers for spooled temp files and temp directory objects"""
2
+
3
+ from functools import partial
4
+
5
+ from ..base import AsyncBase
6
+ from ..threadpool.utils import (
7
+ cond_delegate_to_executor,
8
+ delegate_to_executor,
9
+ proxy_property_directly,
10
+ )
11
+
12
+
13
+ @delegate_to_executor("fileno", "rollover")
14
+ @cond_delegate_to_executor(
15
+ "close",
16
+ "flush",
17
+ "isatty",
18
+ "read",
19
+ "readline",
20
+ "readlines",
21
+ "seek",
22
+ "tell",
23
+ "truncate",
24
+ )
25
+ @proxy_property_directly("closed", "encoding", "mode", "name", "newlines")
26
+ class AsyncSpooledTemporaryFile(AsyncBase):
27
+ """Async wrapper for SpooledTemporaryFile class"""
28
+
29
+ async def _check(self):
30
+ if self._file._rolled:
31
+ return
32
+ max_size = self._file._max_size
33
+ if max_size and self._file.tell() > max_size:
34
+ await self.rollover()
35
+
36
+ async def write(self, s):
37
+ """Implementation to anticipate rollover"""
38
+ if self._file._rolled:
39
+ cb = partial(self._file.write, s)
40
+ return await self._loop.run_in_executor(self._executor, cb)
41
+
42
+ file = self._file._file # reference underlying base IO object
43
+ rv = file.write(s)
44
+ await self._check()
45
+ return rv
46
+
47
+ async def writelines(self, iterable):
48
+ """Implementation to anticipate rollover"""
49
+ if self._file._rolled:
50
+ cb = partial(self._file.writelines, iterable)
51
+ return await self._loop.run_in_executor(self._executor, cb)
52
+
53
+ file = self._file._file # reference underlying base IO object
54
+ rv = file.writelines(iterable)
55
+ await self._check()
56
+ return rv
57
+
58
+
59
+ @delegate_to_executor("cleanup")
60
+ @proxy_property_directly("name")
61
+ class AsyncTemporaryDirectory:
62
+ """Async wrapper for TemporaryDirectory class"""
63
+
64
+ def __init__(self, file, loop, executor):
65
+ self._file = file
66
+ self._loop = loop
67
+ self._executor = executor
68
+
69
+ async def close(self):
70
+ await self.cleanup()
data/conda_envs/evalclaw/lib/python3.11/site-packages/aiofiles/threadpool/__init__.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Handle files using a thread pool executor."""
2
+
3
+ import asyncio
4
+ import sys
5
+ from functools import partial, singledispatch
6
+ from io import (
7
+ BufferedIOBase,
8
+ BufferedRandom,
9
+ BufferedReader,
10
+ BufferedWriter,
11
+ FileIO,
12
+ TextIOBase,
13
+ )
14
+
15
+ from ..base import AiofilesContextManager
16
+ from .binary import (
17
+ AsyncBufferedIOBase,
18
+ AsyncBufferedReader,
19
+ AsyncFileIO,
20
+ AsyncIndirectBufferedIOBase,
21
+ )
22
+ from .text import AsyncTextIndirectIOWrapper, AsyncTextIOWrapper
23
+
24
+ sync_open = open
25
+
26
+ __all__ = (
27
+ "open",
28
+ "stdin",
29
+ "stdout",
30
+ "stderr",
31
+ "stdin_bytes",
32
+ "stdout_bytes",
33
+ "stderr_bytes",
34
+ )
35
+
36
+
37
+ def open(
38
+ file,
39
+ mode="r",
40
+ buffering=-1,
41
+ encoding=None,
42
+ errors=None,
43
+ newline=None,
44
+ closefd=True,
45
+ opener=None,
46
+ *,
47
+ loop=None,
48
+ executor=None,
49
+ ):
50
+ return AiofilesContextManager(
51
+ _open(
52
+ file,
53
+ mode=mode,
54
+ buffering=buffering,
55
+ encoding=encoding,
56
+ errors=errors,
57
+ newline=newline,
58
+ closefd=closefd,
59
+ opener=opener,
60
+ loop=loop,
61
+ executor=executor,
62
+ )
63
+ )
64
+
65
+
66
+ async def _open(
67
+ file,
68
+ mode="r",
69
+ buffering=-1,
70
+ encoding=None,
71
+ errors=None,
72
+ newline=None,
73
+ closefd=True,
74
+ opener=None,
75
+ *,
76
+ loop=None,
77
+ executor=None,
78
+ ):
79
+ """Open an asyncio file."""
80
+ if loop is None:
81
+ loop = asyncio.get_running_loop()
82
+ cb = partial(
83
+ sync_open,
84
+ file,
85
+ mode=mode,
86
+ buffering=buffering,
87
+ encoding=encoding,
88
+ errors=errors,
89
+ newline=newline,
90
+ closefd=closefd,
91
+ opener=opener,
92
+ )
93
+ f = await loop.run_in_executor(executor, cb)
94
+
95
+ return wrap(f, loop=loop, executor=executor)
96
+
97
+
98
+ @singledispatch
99
+ def wrap(file, *, loop=None, executor=None):
100
+ msg = f"Unsupported io type: {file}."
101
+ raise TypeError(msg)
102
+
103
+
104
+ @wrap.register(TextIOBase)
105
+ def _(file, *, loop=None, executor=None):
106
+ return AsyncTextIOWrapper(file, loop=loop, executor=executor)
107
+
108
+
109
+ @wrap.register(BufferedWriter)
110
+ @wrap.register(BufferedIOBase)
111
+ def _(file, *, loop=None, executor=None):
112
+ return AsyncBufferedIOBase(file, loop=loop, executor=executor)
113
+
114
+
115
+ @wrap.register(BufferedReader)
116
+ @wrap.register(BufferedRandom)
117
+ def _(file, *, loop=None, executor=None):
118
+ return AsyncBufferedReader(file, loop=loop, executor=executor)
119
+
120
+
121
+ @wrap.register(FileIO)
122
+ def _(file, *, loop=None, executor=None):
123
+ return AsyncFileIO(file, loop=loop, executor=executor)
124
+
125
+
126
+ stdin = AsyncTextIndirectIOWrapper("sys.stdin", None, None, indirect=lambda: sys.stdin)
127
+ stdout = AsyncTextIndirectIOWrapper(
128
+ "sys.stdout", None, None, indirect=lambda: sys.stdout
129
+ )
130
+ stderr = AsyncTextIndirectIOWrapper(
131
+ "sys.stderr", None, None, indirect=lambda: sys.stderr
132
+ )
133
+ stdin_bytes = AsyncIndirectBufferedIOBase(
134
+ "sys.stdin.buffer", None, None, indirect=lambda: sys.stdin.buffer
135
+ )
136
+ stdout_bytes = AsyncIndirectBufferedIOBase(
137
+ "sys.stdout.buffer", None, None, indirect=lambda: sys.stdout.buffer
138
+ )
139
+ stderr_bytes = AsyncIndirectBufferedIOBase(
140
+ "sys.stderr.buffer", None, None, indirect=lambda: sys.stderr.buffer
141
+ )
data/conda_envs/evalclaw/lib/python3.11/site-packages/aiofiles/threadpool/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (5.11 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/aiofiles/threadpool/__pycache__/binary.cpython-311.pyc ADDED
Binary file (3.58 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/aiofiles/threadpool/__pycache__/text.cpython-311.pyc ADDED
Binary file (1.84 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/aiofiles/threadpool/__pycache__/utils.cpython-311.pyc ADDED
Binary file (4.15 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/aiofiles/threadpool/binary.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ..base import AsyncBase, AsyncIndirectBase
2
+ from .utils import delegate_to_executor, proxy_method_directly, proxy_property_directly
3
+
4
+
5
+ @delegate_to_executor(
6
+ "close",
7
+ "flush",
8
+ "isatty",
9
+ "read",
10
+ "read1",
11
+ "readinto",
12
+ "readline",
13
+ "readlines",
14
+ "seek",
15
+ "seekable",
16
+ "tell",
17
+ "truncate",
18
+ "writable",
19
+ "write",
20
+ "writelines",
21
+ )
22
+ @proxy_method_directly("detach", "fileno", "readable")
23
+ @proxy_property_directly("closed", "raw", "name", "mode")
24
+ class AsyncBufferedIOBase(AsyncBase):
25
+ """The asyncio executor version of io.BufferedWriter and BufferedIOBase."""
26
+
27
+
28
+ @delegate_to_executor("peek")
29
+ class AsyncBufferedReader(AsyncBufferedIOBase):
30
+ """The asyncio executor version of io.BufferedReader and Random."""
31
+
32
+
33
+ @delegate_to_executor(
34
+ "close",
35
+ "flush",
36
+ "isatty",
37
+ "read",
38
+ "readall",
39
+ "readinto",
40
+ "readline",
41
+ "readlines",
42
+ "seek",
43
+ "seekable",
44
+ "tell",
45
+ "truncate",
46
+ "writable",
47
+ "write",
48
+ "writelines",
49
+ )
50
+ @proxy_method_directly("fileno", "readable")
51
+ @proxy_property_directly("closed", "name", "mode")
52
+ class AsyncFileIO(AsyncBase):
53
+ """The asyncio executor version of io.FileIO."""
54
+
55
+
56
+ @delegate_to_executor(
57
+ "close",
58
+ "flush",
59
+ "isatty",
60
+ "read",
61
+ "read1",
62
+ "readinto",
63
+ "readline",
64
+ "readlines",
65
+ "seek",
66
+ "seekable",
67
+ "tell",
68
+ "truncate",
69
+ "writable",
70
+ "write",
71
+ "writelines",
72
+ )
73
+ @proxy_method_directly("detach", "fileno", "readable")
74
+ @proxy_property_directly("closed", "raw", "name", "mode")
75
+ class AsyncIndirectBufferedIOBase(AsyncIndirectBase):
76
+ """The indirect asyncio executor version of io.BufferedWriter and BufferedIOBase."""
77
+
78
+
79
+ @delegate_to_executor("peek")
80
+ class AsyncIndirectBufferedReader(AsyncIndirectBufferedIOBase):
81
+ """The indirect asyncio executor version of io.BufferedReader and Random."""
82
+
83
+
84
+ @delegate_to_executor(
85
+ "close",
86
+ "flush",
87
+ "isatty",
88
+ "read",
89
+ "readall",
90
+ "readinto",
91
+ "readline",
92
+ "readlines",
93
+ "seek",
94
+ "seekable",
95
+ "tell",
96
+ "truncate",
97
+ "writable",
98
+ "write",
99
+ "writelines",
100
+ )
101
+ @proxy_method_directly("fileno", "readable")
102
+ @proxy_property_directly("closed", "name", "mode")
103
+ class AsyncIndirectFileIO(AsyncIndirectBase):
104
+ """The indirect asyncio executor version of io.FileIO."""
data/conda_envs/evalclaw/lib/python3.11/site-packages/aiofiles/threadpool/text.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ..base import AsyncBase, AsyncIndirectBase
2
+ from .utils import delegate_to_executor, proxy_method_directly, proxy_property_directly
3
+
4
+
5
+ @delegate_to_executor(
6
+ "close",
7
+ "flush",
8
+ "isatty",
9
+ "read",
10
+ "readable",
11
+ "readline",
12
+ "readlines",
13
+ "seek",
14
+ "seekable",
15
+ "tell",
16
+ "truncate",
17
+ "write",
18
+ "writable",
19
+ "writelines",
20
+ )
21
+ @proxy_method_directly("detach", "fileno", "readable")
22
+ @proxy_property_directly(
23
+ "buffer",
24
+ "closed",
25
+ "encoding",
26
+ "errors",
27
+ "line_buffering",
28
+ "newlines",
29
+ "name",
30
+ "mode",
31
+ )
32
+ class AsyncTextIOWrapper(AsyncBase):
33
+ """The asyncio executor version of io.TextIOWrapper."""
34
+
35
+
36
+ @delegate_to_executor(
37
+ "close",
38
+ "flush",
39
+ "isatty",
40
+ "read",
41
+ "readable",
42
+ "readline",
43
+ "readlines",
44
+ "seek",
45
+ "seekable",
46
+ "tell",
47
+ "truncate",
48
+ "write",
49
+ "writable",
50
+ "writelines",
51
+ )
52
+ @proxy_method_directly("detach", "fileno", "readable")
53
+ @proxy_property_directly(
54
+ "buffer",
55
+ "closed",
56
+ "encoding",
57
+ "errors",
58
+ "line_buffering",
59
+ "newlines",
60
+ "name",
61
+ "mode",
62
+ )
63
+ class AsyncTextIndirectIOWrapper(AsyncIndirectBase):
64
+ """The indirect asyncio executor version of io.TextIOWrapper."""
data/conda_envs/evalclaw/lib/python3.11/site-packages/aiofiles/threadpool/utils.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+
3
+
4
+ def delegate_to_executor(*attrs):
5
+ def cls_builder(cls):
6
+ for attr_name in attrs:
7
+ setattr(cls, attr_name, _make_delegate_method(attr_name))
8
+ return cls
9
+
10
+ return cls_builder
11
+
12
+
13
+ def proxy_method_directly(*attrs):
14
+ def cls_builder(cls):
15
+ for attr_name in attrs:
16
+ setattr(cls, attr_name, _make_proxy_method(attr_name))
17
+ return cls
18
+
19
+ return cls_builder
20
+
21
+
22
+ def proxy_property_directly(*attrs):
23
+ def cls_builder(cls):
24
+ for attr_name in attrs:
25
+ setattr(cls, attr_name, _make_proxy_property(attr_name))
26
+ return cls
27
+
28
+ return cls_builder
29
+
30
+
31
+ def cond_delegate_to_executor(*attrs):
32
+ def cls_builder(cls):
33
+ for attr_name in attrs:
34
+ setattr(cls, attr_name, _make_cond_delegate_method(attr_name))
35
+ return cls
36
+
37
+ return cls_builder
38
+
39
+
40
+ def _make_delegate_method(attr_name):
41
+ async def method(self, *args, **kwargs):
42
+ cb = functools.partial(getattr(self._file, attr_name), *args, **kwargs)
43
+ return await self._loop.run_in_executor(self._executor, cb)
44
+
45
+ return method
46
+
47
+
48
+ def _make_proxy_method(attr_name):
49
+ def method(self, *args, **kwargs):
50
+ return getattr(self._file, attr_name)(*args, **kwargs)
51
+
52
+ return method
53
+
54
+
55
+ def _make_proxy_property(attr_name):
56
+ def proxy_property(self):
57
+ return getattr(self._file, attr_name)
58
+
59
+ return property(proxy_property)
60
+
61
+
62
+ def _make_cond_delegate_method(attr_name):
63
+ """For spooled temp files, delegate only if rolled to file object"""
64
+
65
+ async def method(self, *args, **kwargs):
66
+ if self._file._rolled:
67
+ cb = functools.partial(getattr(self._file, attr_name), *args, **kwargs)
68
+ return await self._loop.run_in_executor(self._executor, cb)
69
+ return getattr(self._file, attr_name)(*args, **kwargs)
70
+
71
+ return method
data/conda_envs/evalclaw/lib/python3.11/site-packages/google_api_python_client-2.196.0.dist-info/licenses/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.
data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (2.38 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/__pycache__/__version__.cpython-311.pyc ADDED
Binary file (316 Bytes). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/__pycache__/_api.cpython-311.pyc ADDED
Binary file (9.71 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/__pycache__/_auth.cpython-311.pyc ADDED
Binary file (17.1 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/__pycache__/_client.cpython-311.pyc ADDED
Binary file (65.5 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/__pycache__/_config.cpython-311.pyc ADDED
Binary file (11.5 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/__pycache__/_content.cpython-311.pyc ADDED
Binary file (12 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/__pycache__/_decoders.cpython-311.pyc ADDED
Binary file (18.9 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/__pycache__/_exceptions.cpython-311.pyc ADDED
Binary file (14.5 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/__pycache__/_main.cpython-311.pyc ADDED
Binary file (23.1 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/__pycache__/_models.cpython-311.pyc ADDED
Binary file (66.4 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/__pycache__/_multipart.cpython-311.pyc ADDED
Binary file (15.6 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/__pycache__/_status_codes.cpython-311.pyc ADDED
Binary file (7.56 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/__pycache__/_types.cpython-311.pyc ADDED
Binary file (4.66 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/__pycache__/_urlparse.cpython-311.pyc ADDED
Binary file (20.3 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/__pycache__/_urls.cpython-311.pyc ADDED
Binary file (30.8 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/__pycache__/_utils.cpython-311.pyc ADDED
Binary file (10.4 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/_transports/__init__.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .asgi import *
2
+ from .base import *
3
+ from .default import *
4
+ from .mock import *
5
+ from .wsgi import *
6
+
7
+ __all__ = [
8
+ "ASGITransport",
9
+ "AsyncBaseTransport",
10
+ "BaseTransport",
11
+ "AsyncHTTPTransport",
12
+ "HTTPTransport",
13
+ "MockTransport",
14
+ "WSGITransport",
15
+ ]
data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/_transports/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (490 Bytes). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/_transports/__pycache__/asgi.cpython-311.pyc ADDED
Binary file (8.13 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/_transports/__pycache__/base.cpython-311.pyc ADDED
Binary file (4.22 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/_transports/__pycache__/default.cpython-311.pyc ADDED
Binary file (17.5 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/_transports/__pycache__/mock.cpython-311.pyc ADDED
Binary file (2.14 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/_transports/__pycache__/wsgi.cpython-311.pyc ADDED
Binary file (7.4 kB). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/_transports/asgi.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import typing
4
+
5
+ from .._models import Request, Response
6
+ from .._types import AsyncByteStream
7
+ from .base import AsyncBaseTransport
8
+
9
+ if typing.TYPE_CHECKING: # pragma: no cover
10
+ import asyncio
11
+
12
+ import trio
13
+
14
+ Event = typing.Union[asyncio.Event, trio.Event]
15
+
16
+
17
+ _Message = typing.MutableMapping[str, typing.Any]
18
+ _Receive = typing.Callable[[], typing.Awaitable[_Message]]
19
+ _Send = typing.Callable[
20
+ [typing.MutableMapping[str, typing.Any]], typing.Awaitable[None]
21
+ ]
22
+ _ASGIApp = typing.Callable[
23
+ [typing.MutableMapping[str, typing.Any], _Receive, _Send], typing.Awaitable[None]
24
+ ]
25
+
26
+ __all__ = ["ASGITransport"]
27
+
28
+
29
+ def is_running_trio() -> bool:
30
+ try:
31
+ # sniffio is a dependency of trio.
32
+
33
+ # See https://github.com/python-trio/trio/issues/2802
34
+ import sniffio
35
+
36
+ if sniffio.current_async_library() == "trio":
37
+ return True
38
+ except ImportError: # pragma: nocover
39
+ pass
40
+
41
+ return False
42
+
43
+
44
+ def create_event() -> Event:
45
+ if is_running_trio():
46
+ import trio
47
+
48
+ return trio.Event()
49
+
50
+ import asyncio
51
+
52
+ return asyncio.Event()
53
+
54
+
55
+ class ASGIResponseStream(AsyncByteStream):
56
+ def __init__(self, body: list[bytes]) -> None:
57
+ self._body = body
58
+
59
+ async def __aiter__(self) -> typing.AsyncIterator[bytes]:
60
+ yield b"".join(self._body)
61
+
62
+
63
+ class ASGITransport(AsyncBaseTransport):
64
+ """
65
+ A custom AsyncTransport that handles sending requests directly to an ASGI app.
66
+
67
+ ```python
68
+ transport = httpx.ASGITransport(
69
+ app=app,
70
+ root_path="/submount",
71
+ client=("1.2.3.4", 123)
72
+ )
73
+ client = httpx.AsyncClient(transport=transport)
74
+ ```
75
+
76
+ Arguments:
77
+
78
+ * `app` - The ASGI application.
79
+ * `raise_app_exceptions` - Boolean indicating if exceptions in the application
80
+ should be raised. Default to `True`. Can be set to `False` for use cases
81
+ such as testing the content of a client 500 response.
82
+ * `root_path` - The root path on which the ASGI application should be mounted.
83
+ * `client` - A two-tuple indicating the client IP and port of incoming requests.
84
+ ```
85
+ """
86
+
87
+ def __init__(
88
+ self,
89
+ app: _ASGIApp,
90
+ raise_app_exceptions: bool = True,
91
+ root_path: str = "",
92
+ client: tuple[str, int] = ("127.0.0.1", 123),
93
+ ) -> None:
94
+ self.app = app
95
+ self.raise_app_exceptions = raise_app_exceptions
96
+ self.root_path = root_path
97
+ self.client = client
98
+
99
+ async def handle_async_request(
100
+ self,
101
+ request: Request,
102
+ ) -> Response:
103
+ assert isinstance(request.stream, AsyncByteStream)
104
+
105
+ # ASGI scope.
106
+ scope = {
107
+ "type": "http",
108
+ "asgi": {"version": "3.0"},
109
+ "http_version": "1.1",
110
+ "method": request.method,
111
+ "headers": [(k.lower(), v) for (k, v) in request.headers.raw],
112
+ "scheme": request.url.scheme,
113
+ "path": request.url.path,
114
+ "raw_path": request.url.raw_path.split(b"?")[0],
115
+ "query_string": request.url.query,
116
+ "server": (request.url.host, request.url.port),
117
+ "client": self.client,
118
+ "root_path": self.root_path,
119
+ }
120
+
121
+ # Request.
122
+ request_body_chunks = request.stream.__aiter__()
123
+ request_complete = False
124
+
125
+ # Response.
126
+ status_code = None
127
+ response_headers = None
128
+ body_parts = []
129
+ response_started = False
130
+ response_complete = create_event()
131
+
132
+ # ASGI callables.
133
+
134
+ async def receive() -> dict[str, typing.Any]:
135
+ nonlocal request_complete
136
+
137
+ if request_complete:
138
+ await response_complete.wait()
139
+ return {"type": "http.disconnect"}
140
+
141
+ try:
142
+ body = await request_body_chunks.__anext__()
143
+ except StopAsyncIteration:
144
+ request_complete = True
145
+ return {"type": "http.request", "body": b"", "more_body": False}
146
+ return {"type": "http.request", "body": body, "more_body": True}
147
+
148
+ async def send(message: typing.MutableMapping[str, typing.Any]) -> None:
149
+ nonlocal status_code, response_headers, response_started
150
+
151
+ if message["type"] == "http.response.start":
152
+ assert not response_started
153
+
154
+ status_code = message["status"]
155
+ response_headers = message.get("headers", [])
156
+ response_started = True
157
+
158
+ elif message["type"] == "http.response.body":
159
+ assert not response_complete.is_set()
160
+ body = message.get("body", b"")
161
+ more_body = message.get("more_body", False)
162
+
163
+ if body and request.method != "HEAD":
164
+ body_parts.append(body)
165
+
166
+ if not more_body:
167
+ response_complete.set()
168
+
169
+ try:
170
+ await self.app(scope, receive, send)
171
+ except Exception: # noqa: PIE-786
172
+ if self.raise_app_exceptions:
173
+ raise
174
+
175
+ response_complete.set()
176
+ if status_code is None:
177
+ status_code = 500
178
+ if response_headers is None:
179
+ response_headers = {}
180
+
181
+ assert response_complete.is_set()
182
+ assert status_code is not None
183
+ assert response_headers is not None
184
+
185
+ stream = ASGIResponseStream(body_parts)
186
+
187
+ return Response(status_code, headers=response_headers, stream=stream)
data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/_transports/base.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import typing
4
+ from types import TracebackType
5
+
6
+ from .._models import Request, Response
7
+
8
+ T = typing.TypeVar("T", bound="BaseTransport")
9
+ A = typing.TypeVar("A", bound="AsyncBaseTransport")
10
+
11
+ __all__ = ["AsyncBaseTransport", "BaseTransport"]
12
+
13
+
14
+ class BaseTransport:
15
+ def __enter__(self: T) -> T:
16
+ return self
17
+
18
+ def __exit__(
19
+ self,
20
+ exc_type: type[BaseException] | None = None,
21
+ exc_value: BaseException | None = None,
22
+ traceback: TracebackType | None = None,
23
+ ) -> None:
24
+ self.close()
25
+
26
+ def handle_request(self, request: Request) -> Response:
27
+ """
28
+ Send a single HTTP request and return a response.
29
+
30
+ Developers shouldn't typically ever need to call into this API directly,
31
+ since the Client class provides all the higher level user-facing API
32
+ niceties.
33
+
34
+ In order to properly release any network resources, the response
35
+ stream should *either* be consumed immediately, with a call to
36
+ `response.stream.read()`, or else the `handle_request` call should
37
+ be followed with a try/finally block to ensuring the stream is
38
+ always closed.
39
+
40
+ Example usage:
41
+
42
+ with httpx.HTTPTransport() as transport:
43
+ req = httpx.Request(
44
+ method=b"GET",
45
+ url=(b"https", b"www.example.com", 443, b"/"),
46
+ headers=[(b"Host", b"www.example.com")],
47
+ )
48
+ resp = transport.handle_request(req)
49
+ body = resp.stream.read()
50
+ print(resp.status_code, resp.headers, body)
51
+
52
+
53
+ Takes a `Request` instance as the only argument.
54
+
55
+ Returns a `Response` instance.
56
+ """
57
+ raise NotImplementedError(
58
+ "The 'handle_request' method must be implemented."
59
+ ) # pragma: no cover
60
+
61
+ def close(self) -> None:
62
+ pass
63
+
64
+
65
+ class AsyncBaseTransport:
66
+ async def __aenter__(self: A) -> A:
67
+ return self
68
+
69
+ async def __aexit__(
70
+ self,
71
+ exc_type: type[BaseException] | None = None,
72
+ exc_value: BaseException | None = None,
73
+ traceback: TracebackType | None = None,
74
+ ) -> None:
75
+ await self.aclose()
76
+
77
+ async def handle_async_request(
78
+ self,
79
+ request: Request,
80
+ ) -> Response:
81
+ raise NotImplementedError(
82
+ "The 'handle_async_request' method must be implemented."
83
+ ) # pragma: no cover
84
+
85
+ async def aclose(self) -> None:
86
+ pass
data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/_transports/default.py ADDED
@@ -0,0 +1,406 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Custom transports, with nicely configured defaults.
3
+
4
+ The following additional keyword arguments are currently supported by httpcore...
5
+
6
+ * uds: str
7
+ * local_address: str
8
+ * retries: int
9
+
10
+ Example usages...
11
+
12
+ # Disable HTTP/2 on a single specific domain.
13
+ mounts = {
14
+ "all://": httpx.HTTPTransport(http2=True),
15
+ "all://*example.org": httpx.HTTPTransport()
16
+ }
17
+
18
+ # Using advanced httpcore configuration, with connection retries.
19
+ transport = httpx.HTTPTransport(retries=1)
20
+ client = httpx.Client(transport=transport)
21
+
22
+ # Using advanced httpcore configuration, with unix domain sockets.
23
+ transport = httpx.HTTPTransport(uds="socket.uds")
24
+ client = httpx.Client(transport=transport)
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import contextlib
30
+ import typing
31
+ from types import TracebackType
32
+
33
+ if typing.TYPE_CHECKING:
34
+ import ssl # pragma: no cover
35
+
36
+ import httpx # pragma: no cover
37
+
38
+ from .._config import DEFAULT_LIMITS, Limits, Proxy, create_ssl_context
39
+ from .._exceptions import (
40
+ ConnectError,
41
+ ConnectTimeout,
42
+ LocalProtocolError,
43
+ NetworkError,
44
+ PoolTimeout,
45
+ ProtocolError,
46
+ ProxyError,
47
+ ReadError,
48
+ ReadTimeout,
49
+ RemoteProtocolError,
50
+ TimeoutException,
51
+ UnsupportedProtocol,
52
+ WriteError,
53
+ WriteTimeout,
54
+ )
55
+ from .._models import Request, Response
56
+ from .._types import AsyncByteStream, CertTypes, ProxyTypes, SyncByteStream
57
+ from .._urls import URL
58
+ from .base import AsyncBaseTransport, BaseTransport
59
+
60
+ T = typing.TypeVar("T", bound="HTTPTransport")
61
+ A = typing.TypeVar("A", bound="AsyncHTTPTransport")
62
+
63
+ SOCKET_OPTION = typing.Union[
64
+ typing.Tuple[int, int, int],
65
+ typing.Tuple[int, int, typing.Union[bytes, bytearray]],
66
+ typing.Tuple[int, int, None, int],
67
+ ]
68
+
69
+ __all__ = ["AsyncHTTPTransport", "HTTPTransport"]
70
+
71
+ HTTPCORE_EXC_MAP: dict[type[Exception], type[httpx.HTTPError]] = {}
72
+
73
+
74
+ def _load_httpcore_exceptions() -> dict[type[Exception], type[httpx.HTTPError]]:
75
+ import httpcore
76
+
77
+ return {
78
+ httpcore.TimeoutException: TimeoutException,
79
+ httpcore.ConnectTimeout: ConnectTimeout,
80
+ httpcore.ReadTimeout: ReadTimeout,
81
+ httpcore.WriteTimeout: WriteTimeout,
82
+ httpcore.PoolTimeout: PoolTimeout,
83
+ httpcore.NetworkError: NetworkError,
84
+ httpcore.ConnectError: ConnectError,
85
+ httpcore.ReadError: ReadError,
86
+ httpcore.WriteError: WriteError,
87
+ httpcore.ProxyError: ProxyError,
88
+ httpcore.UnsupportedProtocol: UnsupportedProtocol,
89
+ httpcore.ProtocolError: ProtocolError,
90
+ httpcore.LocalProtocolError: LocalProtocolError,
91
+ httpcore.RemoteProtocolError: RemoteProtocolError,
92
+ }
93
+
94
+
95
+ @contextlib.contextmanager
96
+ def map_httpcore_exceptions() -> typing.Iterator[None]:
97
+ global HTTPCORE_EXC_MAP
98
+ if len(HTTPCORE_EXC_MAP) == 0:
99
+ HTTPCORE_EXC_MAP = _load_httpcore_exceptions()
100
+ try:
101
+ yield
102
+ except Exception as exc:
103
+ mapped_exc = None
104
+
105
+ for from_exc, to_exc in HTTPCORE_EXC_MAP.items():
106
+ if not isinstance(exc, from_exc):
107
+ continue
108
+ # We want to map to the most specific exception we can find.
109
+ # Eg if `exc` is an `httpcore.ReadTimeout`, we want to map to
110
+ # `httpx.ReadTimeout`, not just `httpx.TimeoutException`.
111
+ if mapped_exc is None or issubclass(to_exc, mapped_exc):
112
+ mapped_exc = to_exc
113
+
114
+ if mapped_exc is None: # pragma: no cover
115
+ raise
116
+
117
+ message = str(exc)
118
+ raise mapped_exc(message) from exc
119
+
120
+
121
+ class ResponseStream(SyncByteStream):
122
+ def __init__(self, httpcore_stream: typing.Iterable[bytes]) -> None:
123
+ self._httpcore_stream = httpcore_stream
124
+
125
+ def __iter__(self) -> typing.Iterator[bytes]:
126
+ with map_httpcore_exceptions():
127
+ for part in self._httpcore_stream:
128
+ yield part
129
+
130
+ def close(self) -> None:
131
+ if hasattr(self._httpcore_stream, "close"):
132
+ self._httpcore_stream.close()
133
+
134
+
135
+ class HTTPTransport(BaseTransport):
136
+ def __init__(
137
+ self,
138
+ verify: ssl.SSLContext | str | bool = True,
139
+ cert: CertTypes | None = None,
140
+ trust_env: bool = True,
141
+ http1: bool = True,
142
+ http2: bool = False,
143
+ limits: Limits = DEFAULT_LIMITS,
144
+ proxy: ProxyTypes | None = None,
145
+ uds: str | None = None,
146
+ local_address: str | None = None,
147
+ retries: int = 0,
148
+ socket_options: typing.Iterable[SOCKET_OPTION] | None = None,
149
+ ) -> None:
150
+ import httpcore
151
+
152
+ proxy = Proxy(url=proxy) if isinstance(proxy, (str, URL)) else proxy
153
+ ssl_context = create_ssl_context(verify=verify, cert=cert, trust_env=trust_env)
154
+
155
+ if proxy is None:
156
+ self._pool = httpcore.ConnectionPool(
157
+ ssl_context=ssl_context,
158
+ max_connections=limits.max_connections,
159
+ max_keepalive_connections=limits.max_keepalive_connections,
160
+ keepalive_expiry=limits.keepalive_expiry,
161
+ http1=http1,
162
+ http2=http2,
163
+ uds=uds,
164
+ local_address=local_address,
165
+ retries=retries,
166
+ socket_options=socket_options,
167
+ )
168
+ elif proxy.url.scheme in ("http", "https"):
169
+ self._pool = httpcore.HTTPProxy(
170
+ proxy_url=httpcore.URL(
171
+ scheme=proxy.url.raw_scheme,
172
+ host=proxy.url.raw_host,
173
+ port=proxy.url.port,
174
+ target=proxy.url.raw_path,
175
+ ),
176
+ proxy_auth=proxy.raw_auth,
177
+ proxy_headers=proxy.headers.raw,
178
+ ssl_context=ssl_context,
179
+ proxy_ssl_context=proxy.ssl_context,
180
+ max_connections=limits.max_connections,
181
+ max_keepalive_connections=limits.max_keepalive_connections,
182
+ keepalive_expiry=limits.keepalive_expiry,
183
+ http1=http1,
184
+ http2=http2,
185
+ socket_options=socket_options,
186
+ )
187
+ elif proxy.url.scheme in ("socks5", "socks5h"):
188
+ try:
189
+ import socksio # noqa
190
+ except ImportError: # pragma: no cover
191
+ raise ImportError(
192
+ "Using SOCKS proxy, but the 'socksio' package is not installed. "
193
+ "Make sure to install httpx using `pip install httpx[socks]`."
194
+ ) from None
195
+
196
+ self._pool = httpcore.SOCKSProxy(
197
+ proxy_url=httpcore.URL(
198
+ scheme=proxy.url.raw_scheme,
199
+ host=proxy.url.raw_host,
200
+ port=proxy.url.port,
201
+ target=proxy.url.raw_path,
202
+ ),
203
+ proxy_auth=proxy.raw_auth,
204
+ ssl_context=ssl_context,
205
+ max_connections=limits.max_connections,
206
+ max_keepalive_connections=limits.max_keepalive_connections,
207
+ keepalive_expiry=limits.keepalive_expiry,
208
+ http1=http1,
209
+ http2=http2,
210
+ )
211
+ else: # pragma: no cover
212
+ raise ValueError(
213
+ "Proxy protocol must be either 'http', 'https', 'socks5', or 'socks5h',"
214
+ f" but got {proxy.url.scheme!r}."
215
+ )
216
+
217
+ def __enter__(self: T) -> T: # Use generics for subclass support.
218
+ self._pool.__enter__()
219
+ return self
220
+
221
+ def __exit__(
222
+ self,
223
+ exc_type: type[BaseException] | None = None,
224
+ exc_value: BaseException | None = None,
225
+ traceback: TracebackType | None = None,
226
+ ) -> None:
227
+ with map_httpcore_exceptions():
228
+ self._pool.__exit__(exc_type, exc_value, traceback)
229
+
230
+ def handle_request(
231
+ self,
232
+ request: Request,
233
+ ) -> Response:
234
+ assert isinstance(request.stream, SyncByteStream)
235
+ import httpcore
236
+
237
+ req = httpcore.Request(
238
+ method=request.method,
239
+ url=httpcore.URL(
240
+ scheme=request.url.raw_scheme,
241
+ host=request.url.raw_host,
242
+ port=request.url.port,
243
+ target=request.url.raw_path,
244
+ ),
245
+ headers=request.headers.raw,
246
+ content=request.stream,
247
+ extensions=request.extensions,
248
+ )
249
+ with map_httpcore_exceptions():
250
+ resp = self._pool.handle_request(req)
251
+
252
+ assert isinstance(resp.stream, typing.Iterable)
253
+
254
+ return Response(
255
+ status_code=resp.status,
256
+ headers=resp.headers,
257
+ stream=ResponseStream(resp.stream),
258
+ extensions=resp.extensions,
259
+ )
260
+
261
+ def close(self) -> None:
262
+ self._pool.close()
263
+
264
+
265
+ class AsyncResponseStream(AsyncByteStream):
266
+ def __init__(self, httpcore_stream: typing.AsyncIterable[bytes]) -> None:
267
+ self._httpcore_stream = httpcore_stream
268
+
269
+ async def __aiter__(self) -> typing.AsyncIterator[bytes]:
270
+ with map_httpcore_exceptions():
271
+ async for part in self._httpcore_stream:
272
+ yield part
273
+
274
+ async def aclose(self) -> None:
275
+ if hasattr(self._httpcore_stream, "aclose"):
276
+ await self._httpcore_stream.aclose()
277
+
278
+
279
+ class AsyncHTTPTransport(AsyncBaseTransport):
280
+ def __init__(
281
+ self,
282
+ verify: ssl.SSLContext | str | bool = True,
283
+ cert: CertTypes | None = None,
284
+ trust_env: bool = True,
285
+ http1: bool = True,
286
+ http2: bool = False,
287
+ limits: Limits = DEFAULT_LIMITS,
288
+ proxy: ProxyTypes | None = None,
289
+ uds: str | None = None,
290
+ local_address: str | None = None,
291
+ retries: int = 0,
292
+ socket_options: typing.Iterable[SOCKET_OPTION] | None = None,
293
+ ) -> None:
294
+ import httpcore
295
+
296
+ proxy = Proxy(url=proxy) if isinstance(proxy, (str, URL)) else proxy
297
+ ssl_context = create_ssl_context(verify=verify, cert=cert, trust_env=trust_env)
298
+
299
+ if proxy is None:
300
+ self._pool = httpcore.AsyncConnectionPool(
301
+ ssl_context=ssl_context,
302
+ max_connections=limits.max_connections,
303
+ max_keepalive_connections=limits.max_keepalive_connections,
304
+ keepalive_expiry=limits.keepalive_expiry,
305
+ http1=http1,
306
+ http2=http2,
307
+ uds=uds,
308
+ local_address=local_address,
309
+ retries=retries,
310
+ socket_options=socket_options,
311
+ )
312
+ elif proxy.url.scheme in ("http", "https"):
313
+ self._pool = httpcore.AsyncHTTPProxy(
314
+ proxy_url=httpcore.URL(
315
+ scheme=proxy.url.raw_scheme,
316
+ host=proxy.url.raw_host,
317
+ port=proxy.url.port,
318
+ target=proxy.url.raw_path,
319
+ ),
320
+ proxy_auth=proxy.raw_auth,
321
+ proxy_headers=proxy.headers.raw,
322
+ proxy_ssl_context=proxy.ssl_context,
323
+ ssl_context=ssl_context,
324
+ max_connections=limits.max_connections,
325
+ max_keepalive_connections=limits.max_keepalive_connections,
326
+ keepalive_expiry=limits.keepalive_expiry,
327
+ http1=http1,
328
+ http2=http2,
329
+ socket_options=socket_options,
330
+ )
331
+ elif proxy.url.scheme in ("socks5", "socks5h"):
332
+ try:
333
+ import socksio # noqa
334
+ except ImportError: # pragma: no cover
335
+ raise ImportError(
336
+ "Using SOCKS proxy, but the 'socksio' package is not installed. "
337
+ "Make sure to install httpx using `pip install httpx[socks]`."
338
+ ) from None
339
+
340
+ self._pool = httpcore.AsyncSOCKSProxy(
341
+ proxy_url=httpcore.URL(
342
+ scheme=proxy.url.raw_scheme,
343
+ host=proxy.url.raw_host,
344
+ port=proxy.url.port,
345
+ target=proxy.url.raw_path,
346
+ ),
347
+ proxy_auth=proxy.raw_auth,
348
+ ssl_context=ssl_context,
349
+ max_connections=limits.max_connections,
350
+ max_keepalive_connections=limits.max_keepalive_connections,
351
+ keepalive_expiry=limits.keepalive_expiry,
352
+ http1=http1,
353
+ http2=http2,
354
+ )
355
+ else: # pragma: no cover
356
+ raise ValueError(
357
+ "Proxy protocol must be either 'http', 'https', 'socks5', or 'socks5h',"
358
+ " but got {proxy.url.scheme!r}."
359
+ )
360
+
361
+ async def __aenter__(self: A) -> A: # Use generics for subclass support.
362
+ await self._pool.__aenter__()
363
+ return self
364
+
365
+ async def __aexit__(
366
+ self,
367
+ exc_type: type[BaseException] | None = None,
368
+ exc_value: BaseException | None = None,
369
+ traceback: TracebackType | None = None,
370
+ ) -> None:
371
+ with map_httpcore_exceptions():
372
+ await self._pool.__aexit__(exc_type, exc_value, traceback)
373
+
374
+ async def handle_async_request(
375
+ self,
376
+ request: Request,
377
+ ) -> Response:
378
+ assert isinstance(request.stream, AsyncByteStream)
379
+ import httpcore
380
+
381
+ req = httpcore.Request(
382
+ method=request.method,
383
+ url=httpcore.URL(
384
+ scheme=request.url.raw_scheme,
385
+ host=request.url.raw_host,
386
+ port=request.url.port,
387
+ target=request.url.raw_path,
388
+ ),
389
+ headers=request.headers.raw,
390
+ content=request.stream,
391
+ extensions=request.extensions,
392
+ )
393
+ with map_httpcore_exceptions():
394
+ resp = await self._pool.handle_async_request(req)
395
+
396
+ assert isinstance(resp.stream, typing.AsyncIterable)
397
+
398
+ return Response(
399
+ status_code=resp.status,
400
+ headers=resp.headers,
401
+ stream=AsyncResponseStream(resp.stream),
402
+ extensions=resp.extensions,
403
+ )
404
+
405
+ async def aclose(self) -> None:
406
+ await self._pool.aclose()
data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/_transports/mock.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import typing
4
+
5
+ from .._models import Request, Response
6
+ from .base import AsyncBaseTransport, BaseTransport
7
+
8
+ SyncHandler = typing.Callable[[Request], Response]
9
+ AsyncHandler = typing.Callable[[Request], typing.Coroutine[None, None, Response]]
10
+
11
+
12
+ __all__ = ["MockTransport"]
13
+
14
+
15
+ class MockTransport(AsyncBaseTransport, BaseTransport):
16
+ def __init__(self, handler: SyncHandler | AsyncHandler) -> None:
17
+ self.handler = handler
18
+
19
+ def handle_request(
20
+ self,
21
+ request: Request,
22
+ ) -> Response:
23
+ request.read()
24
+ response = self.handler(request)
25
+ if not isinstance(response, Response): # pragma: no cover
26
+ raise TypeError("Cannot use an async handler in a sync Client")
27
+ return response
28
+
29
+ async def handle_async_request(
30
+ self,
31
+ request: Request,
32
+ ) -> Response:
33
+ await request.aread()
34
+ response = self.handler(request)
35
+
36
+ # Allow handler to *optionally* be an `async` function.
37
+ # If it is, then the `response` variable need to be awaited to actually
38
+ # return the result.
39
+
40
+ if not isinstance(response, Response):
41
+ response = await response
42
+
43
+ return response
data/conda_envs/evalclaw/lib/python3.11/site-packages/httpx/_transports/wsgi.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import io
4
+ import itertools
5
+ import sys
6
+ import typing
7
+
8
+ from .._models import Request, Response
9
+ from .._types import SyncByteStream
10
+ from .base import BaseTransport
11
+
12
+ if typing.TYPE_CHECKING:
13
+ from _typeshed import OptExcInfo # pragma: no cover
14
+ from _typeshed.wsgi import WSGIApplication # pragma: no cover
15
+
16
+ _T = typing.TypeVar("_T")
17
+
18
+
19
+ __all__ = ["WSGITransport"]
20
+
21
+
22
+ def _skip_leading_empty_chunks(body: typing.Iterable[_T]) -> typing.Iterable[_T]:
23
+ body = iter(body)
24
+ for chunk in body:
25
+ if chunk:
26
+ return itertools.chain([chunk], body)
27
+ return []
28
+
29
+
30
+ class WSGIByteStream(SyncByteStream):
31
+ def __init__(self, result: typing.Iterable[bytes]) -> None:
32
+ self._close = getattr(result, "close", None)
33
+ self._result = _skip_leading_empty_chunks(result)
34
+
35
+ def __iter__(self) -> typing.Iterator[bytes]:
36
+ for part in self._result:
37
+ yield part
38
+
39
+ def close(self) -> None:
40
+ if self._close is not None:
41
+ self._close()
42
+
43
+
44
+ class WSGITransport(BaseTransport):
45
+ """
46
+ A custom transport that handles sending requests directly to an WSGI app.
47
+ The simplest way to use this functionality is to use the `app` argument.
48
+
49
+ ```
50
+ client = httpx.Client(app=app)
51
+ ```
52
+
53
+ Alternatively, you can setup the transport instance explicitly.
54
+ This allows you to include any additional configuration arguments specific
55
+ to the WSGITransport class:
56
+
57
+ ```
58
+ transport = httpx.WSGITransport(
59
+ app=app,
60
+ script_name="/submount",
61
+ remote_addr="1.2.3.4"
62
+ )
63
+ client = httpx.Client(transport=transport)
64
+ ```
65
+
66
+ Arguments:
67
+
68
+ * `app` - The WSGI application.
69
+ * `raise_app_exceptions` - Boolean indicating if exceptions in the application
70
+ should be raised. Default to `True`. Can be set to `False` for use cases
71
+ such as testing the content of a client 500 response.
72
+ * `script_name` - The root path on which the WSGI application should be mounted.
73
+ * `remote_addr` - A string indicating the client IP of incoming requests.
74
+ ```
75
+ """
76
+
77
+ def __init__(
78
+ self,
79
+ app: WSGIApplication,
80
+ raise_app_exceptions: bool = True,
81
+ script_name: str = "",
82
+ remote_addr: str = "127.0.0.1",
83
+ wsgi_errors: typing.TextIO | None = None,
84
+ ) -> None:
85
+ self.app = app
86
+ self.raise_app_exceptions = raise_app_exceptions
87
+ self.script_name = script_name
88
+ self.remote_addr = remote_addr
89
+ self.wsgi_errors = wsgi_errors
90
+
91
+ def handle_request(self, request: Request) -> Response:
92
+ request.read()
93
+ wsgi_input = io.BytesIO(request.content)
94
+
95
+ port = request.url.port or {"http": 80, "https": 443}[request.url.scheme]
96
+ environ = {
97
+ "wsgi.version": (1, 0),
98
+ "wsgi.url_scheme": request.url.scheme,
99
+ "wsgi.input": wsgi_input,
100
+ "wsgi.errors": self.wsgi_errors or sys.stderr,
101
+ "wsgi.multithread": True,
102
+ "wsgi.multiprocess": False,
103
+ "wsgi.run_once": False,
104
+ "REQUEST_METHOD": request.method,
105
+ "SCRIPT_NAME": self.script_name,
106
+ "PATH_INFO": request.url.path,
107
+ "QUERY_STRING": request.url.query.decode("ascii"),
108
+ "SERVER_NAME": request.url.host,
109
+ "SERVER_PORT": str(port),
110
+ "SERVER_PROTOCOL": "HTTP/1.1",
111
+ "REMOTE_ADDR": self.remote_addr,
112
+ }
113
+ for header_key, header_value in request.headers.raw:
114
+ key = header_key.decode("ascii").upper().replace("-", "_")
115
+ if key not in ("CONTENT_TYPE", "CONTENT_LENGTH"):
116
+ key = "HTTP_" + key
117
+ environ[key] = header_value.decode("ascii")
118
+
119
+ seen_status = None
120
+ seen_response_headers = None
121
+ seen_exc_info = None
122
+
123
+ def start_response(
124
+ status: str,
125
+ response_headers: list[tuple[str, str]],
126
+ exc_info: OptExcInfo | None = None,
127
+ ) -> typing.Callable[[bytes], typing.Any]:
128
+ nonlocal seen_status, seen_response_headers, seen_exc_info
129
+ seen_status = status
130
+ seen_response_headers = response_headers
131
+ seen_exc_info = exc_info
132
+ return lambda _: None
133
+
134
+ result = self.app(environ, start_response)
135
+
136
+ stream = WSGIByteStream(result)
137
+
138
+ assert seen_status is not None
139
+ assert seen_response_headers is not None
140
+ if seen_exc_info and seen_exc_info[0] and self.raise_app_exceptions:
141
+ raise seen_exc_info[1]
142
+
143
+ status_code = int(seen_status.split()[0])
144
+ headers = [
145
+ (key.encode("ascii"), value.encode("ascii"))
146
+ for key, value in seen_response_headers
147
+ ]
148
+
149
+ return Response(status_code, headers=headers, stream=stream)
data/conda_envs/evalclaw/lib/python3.11/site-packages/langchain_openai/__pycache__/__init__.cpython-311.pyc ADDED
Binary file (837 Bytes). View file
 
data/conda_envs/evalclaw/lib/python3.11/site-packages/langchain_openai/chat_models/__init__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ """Module for OpenAI chat models."""
2
+
3
+ from langchain_openai.chat_models.azure import AzureChatOpenAI
4
+ from langchain_openai.chat_models.base import ChatOpenAI
5
+
6
+ __all__ = ["AzureChatOpenAI", "ChatOpenAI"]
data/conda_envs/evalclaw/lib/python3.11/site-packages/langchain_openai/chat_models/_client_utils.py ADDED
@@ -0,0 +1,683 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Helpers for OpenAI httpx client construction, transport tuning, and streaming.
2
+
3
+ Covers cached default client builders, proxy-aware variants for the
4
+ `openai_proxy` path, kernel-level TCP keepalive / `TCP_USER_TIMEOUT` socket
5
+ options, and the `_astream_with_chunk_timeout` wrapper that bounds per-chunk
6
+ wall-clock time on async SSE streams.
7
+
8
+ Client-builder boilerplate mirrors the patterns in `openai._base_client`;
9
+ socket-option tuning and the streaming timeout are original to this module.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import asyncio
15
+ import inspect
16
+ import logging
17
+ import os
18
+ import socket
19
+ import sys
20
+ import urllib.request
21
+ from collections.abc import AsyncIterator, Awaitable, Callable, Sequence
22
+ from functools import lru_cache
23
+ from typing import Any, TypeVar, cast
24
+
25
+ import httpx
26
+ import openai
27
+ from pydantic import SecretStr
28
+
29
+ logger = logging.getLogger(__name__)
30
+
31
+ SocketOption = tuple[int, int, int]
32
+
33
+ # socket.TCP_KEEPIDLE etc. are absent on darwin/win32; use raw UAPI constants.
34
+ _LINUX_TCP_KEEPIDLE = 4
35
+ _LINUX_TCP_KEEPINTVL = 5
36
+ _LINUX_TCP_KEEPCNT = 6
37
+ _LINUX_TCP_USER_TIMEOUT = 18
38
+
39
+ # macOS: same semantics, different constants from <netinet/tcp.h>.
40
+ _DARWIN_TCP_KEEPALIVE = 0x10 # idle seconds before first probe
41
+ _DARWIN_TCP_KEEPINTVL = 0x101
42
+ _DARWIN_TCP_KEEPCNT = 0x102
43
+
44
+ # Mirrors the openai SDK's pool defaults. Hardcoded to avoid depending on
45
+ # an internal module path (openai._constants) that can move across SDK versions.
46
+ _DEFAULT_CONNECTION_LIMITS = httpx.Limits(
47
+ max_connections=1000,
48
+ max_keepalive_connections=100,
49
+ keepalive_expiry=5.0,
50
+ )
51
+
52
+
53
+ def _int_env(name: str, default: int, *, allow_negative: bool = False) -> int:
54
+ """Read an int env var with graceful fallback + discoverable warning.
55
+
56
+ Unparseable or (by default) negative values fall back to `default` and
57
+ emit a single `WARNING` naming the offending variable. A misconfigured
58
+ environment still loads, but operators see the fallback in their logs
59
+ rather than silently getting a surprising default.
60
+ """
61
+ raw = os.environ.get(name)
62
+ if raw is None:
63
+ return default
64
+ try:
65
+ value = int(raw)
66
+ except (TypeError, ValueError):
67
+ logger.warning(
68
+ "Invalid value for %s=%r (not an int); falling back to %d.",
69
+ name,
70
+ raw,
71
+ default,
72
+ )
73
+ return default
74
+ if not allow_negative and value < 0:
75
+ logger.warning(
76
+ "Invalid value for %s=%r (negative); falling back to %d.",
77
+ name,
78
+ raw,
79
+ default,
80
+ )
81
+ return default
82
+ return value
83
+
84
+
85
+ def _float_env(name: str, default: float, *, allow_negative: bool = False) -> float:
86
+ """Read a float env var with graceful fallback + discoverable warning.
87
+
88
+ See `_int_env`. Negative values are rejected by default so a typo in
89
+ `LANGCHAIN_OPENAI_STREAM_CHUNK_TIMEOUT_S=-10` can't silently disable the
90
+ wrapper it was meant to configure.
91
+ """
92
+ raw = os.environ.get(name)
93
+ if raw is None:
94
+ return default
95
+ try:
96
+ value = float(raw)
97
+ except (TypeError, ValueError):
98
+ logger.warning(
99
+ "Invalid value for %s=%r (not a float); falling back to %s.",
100
+ name,
101
+ raw,
102
+ default,
103
+ )
104
+ return default
105
+ if not allow_negative and value < 0:
106
+ logger.warning(
107
+ "Invalid value for %s=%r (negative); falling back to %s.",
108
+ name,
109
+ raw,
110
+ default,
111
+ )
112
+ return default
113
+ return value
114
+
115
+
116
+ def _filter_supported(opts: list[SocketOption]) -> list[SocketOption]:
117
+ """Drop socket options the running platform rejects.
118
+
119
+ Probes each option against a throwaway socket via `setsockopt` and keeps
120
+ only those the kernel accepts. This keeps the library-computed defaults
121
+ non-fatal across platforms that don't implement every Linux option —
122
+ `TCP_USER_TIMEOUT` in particular is Linux-only and silently missing on
123
+ macOS, some minimal kernels, and older gVisor builds. Dropped options
124
+ are logged at `DEBUG` so an operator can confirm whether a kernel-level
125
+ knob took effect on their platform.
126
+
127
+ If the probe socket cannot be created (sandboxed runtimes, `pytest-socket`
128
+ under `--disable-socket`, tight seccomp policies), the input list is
129
+ returned unfiltered. This preserves the pass-through behavior used for
130
+ explicit user overrides: unsupported options will surface as a clear
131
+ `OSError` at the first real `connect()` rather than being silently
132
+ dropped during `ChatOpenAI` construction.
133
+ """
134
+ try:
135
+ probe = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
136
+ except Exception:
137
+ # Broad catch is deliberate: `pytest_socket` under `--disable-socket`
138
+ # raises `SocketBlockedError` (a `RuntimeError`, not `OSError`), and
139
+ # seccomp/sandboxed runtimes have been observed to raise other
140
+ # `OSError` subclasses and `PermissionError`. The intent is "any
141
+ # inability to create a probe socket -> pass through unfiltered,"
142
+ # and narrowing the type would silently regress sandboxed CI.
143
+ return list(opts)
144
+ try:
145
+ supported: list[SocketOption] = []
146
+ dropped: list[SocketOption] = []
147
+ for level, optname, optval in opts:
148
+ try:
149
+ probe.setsockopt(level, optname, optval)
150
+ except OSError:
151
+ dropped.append((level, optname, optval))
152
+ continue
153
+ supported.append((level, optname, optval))
154
+ if dropped:
155
+ logger.debug(
156
+ "Dropped %d unsupported socket option(s) on %s: %s",
157
+ len(dropped),
158
+ sys.platform,
159
+ dropped,
160
+ )
161
+ return supported
162
+ finally:
163
+ probe.close()
164
+
165
+
166
+ def _default_socket_options() -> tuple[SocketOption, ...]:
167
+ """Return default TCP socket options, or `()` if disabled via env.
168
+
169
+ Always returns a tuple (never None) so callers and `@lru_cache` keys
170
+ remain uniform: `()` is the single shape for "no options".
171
+
172
+ Target behavior on Linux/gVisor with the full option set: silent peers
173
+ are surfaced within ~90-120s via `SO_KEEPALIVE` + `TCP_USER_TIMEOUT`
174
+ (keepalive path gives a ~90s floor at the defaults; `TCP_USER_TIMEOUT`
175
+ caps at 120s). On platforms that reject some options,
176
+ `_filter_supported` drops them and the bound degrades to whatever the
177
+ remaining options provide.
178
+ """
179
+ if os.environ.get("LANGCHAIN_OPENAI_TCP_KEEPALIVE", "1") == "0":
180
+ return ()
181
+
182
+ keepidle = _int_env("LANGCHAIN_OPENAI_TCP_KEEPIDLE", 60)
183
+ keepintvl = _int_env("LANGCHAIN_OPENAI_TCP_KEEPINTVL", 10)
184
+ keepcnt = _int_env("LANGCHAIN_OPENAI_TCP_KEEPCNT", 3)
185
+ user_timeout_ms = _int_env("LANGCHAIN_OPENAI_TCP_USER_TIMEOUT_MS", 120000)
186
+
187
+ opts: list[SocketOption] = [(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)]
188
+ if sys.platform == "linux":
189
+ opts += [
190
+ (socket.IPPROTO_TCP, _LINUX_TCP_KEEPIDLE, keepidle),
191
+ (socket.IPPROTO_TCP, _LINUX_TCP_KEEPINTVL, keepintvl),
192
+ (socket.IPPROTO_TCP, _LINUX_TCP_KEEPCNT, keepcnt),
193
+ (socket.IPPROTO_TCP, _LINUX_TCP_USER_TIMEOUT, user_timeout_ms),
194
+ ]
195
+ elif sys.platform == "darwin":
196
+ opts += [
197
+ (socket.IPPROTO_TCP, _DARWIN_TCP_KEEPALIVE, keepidle),
198
+ (socket.IPPROTO_TCP, _DARWIN_TCP_KEEPINTVL, keepintvl),
199
+ (socket.IPPROTO_TCP, _DARWIN_TCP_KEEPCNT, keepcnt),
200
+ ]
201
+ # Windows (win32): SO_KEEPALIVE only; per-option tuning requires WSAIoctl.
202
+ return tuple(_filter_supported(opts))
203
+
204
+
205
+ _PROXY_ENV_VARS = (
206
+ "HTTP_PROXY",
207
+ "HTTPS_PROXY",
208
+ "ALL_PROXY",
209
+ "http_proxy",
210
+ "https_proxy",
211
+ "all_proxy",
212
+ )
213
+ _proxy_env_warning_emitted = False
214
+ _proxy_env_bypass_info_emitted = False
215
+
216
+
217
+ def _proxy_env_detected() -> bool:
218
+ """True when httpx would pick up a proxy from env or system config.
219
+
220
+ Mirrors the surface httpx reads (`urllib.request.getproxies()` plus the
221
+ uppercase env var names) so a positive result means env-proxy
222
+ auto-detection is live on pre-PR code paths.
223
+ """
224
+ if any(os.environ.get(name) for name in _PROXY_ENV_VARS):
225
+ return True
226
+ try:
227
+ return bool(urllib.request.getproxies())
228
+ except Exception:
229
+ return False
230
+
231
+
232
+ def _should_bypass_socket_options_for_proxy_env(
233
+ *,
234
+ http_socket_options: Sequence[SocketOption] | None,
235
+ http_client: Any,
236
+ http_async_client: Any,
237
+ openai_proxy: str | None,
238
+ ) -> bool:
239
+ """True when default shape + env proxy detected → skip transport injection.
240
+
241
+ Preserves pre-PR behavior for apps relying on httpx's env-proxy
242
+ auto-detection. Only triggers when the user has made no explicit choice
243
+ that would signal they want the custom transport:
244
+
245
+ - `http_socket_options` left at `None` (default, not `()` or a sequence)
246
+ - `LANGCHAIN_OPENAI_TCP_KEEPALIVE` is not `0` (kill-switch is its own path)
247
+ - No `http_client` or `http_async_client` supplied
248
+ - No `openai_proxy` supplied
249
+ - A proxy env var / system proxy is visible to httpx
250
+
251
+ If any of those are set, the user has opted in to the transport path
252
+ (directly or via `openai_proxy`) and normal behavior — including the
253
+ shadowed-proxy WARNING — applies. When the kill-switch is set,
254
+ `_default_socket_options` already returns `()`, so the bypass INFO
255
+ would be noise; route through the normal path instead.
256
+ """
257
+ if http_socket_options is not None:
258
+ return False
259
+ if os.environ.get("LANGCHAIN_OPENAI_TCP_KEEPALIVE", "1") == "0":
260
+ return False
261
+ if http_client is not None or http_async_client is not None:
262
+ return False
263
+ if openai_proxy:
264
+ return False
265
+ return _proxy_env_detected()
266
+
267
+
268
+ def _log_proxy_env_bypass_once() -> None:
269
+ """Emit a one-time INFO when the proxy-env bypass triggers.
270
+
271
+ Visibility for operators running with a custom log pipeline: the bypass
272
+ is the *safe* outcome (env-proxy auto-detection preserved), but it means
273
+ socket-level keepalive / `TCP_USER_TIMEOUT` aren't applied on this
274
+ instance. INFO-level, since it's not a problem — just a diagnostic.
275
+ """
276
+ global _proxy_env_bypass_info_emitted
277
+ if _proxy_env_bypass_info_emitted:
278
+ return
279
+ _proxy_env_bypass_info_emitted = True
280
+ active = [name for name in _PROXY_ENV_VARS if os.environ.get(name)]
281
+ source = ", ".join(active) if active else "system proxy configuration"
282
+ logger.info(
283
+ "langchain-openai detected %s and no explicit `http_socket_options` / "
284
+ "`http_client` / `http_async_client` / `openai_proxy`; skipping the "
285
+ "custom `httpx` transport so httpx's env-proxy auto-detection applies. "
286
+ "Pass `http_socket_options=[...]` to opt back into kernel-level TCP "
287
+ "keepalive tuning on top of the env proxy.",
288
+ source,
289
+ )
290
+
291
+
292
+ def _warn_if_proxy_env_shadowed(
293
+ socket_options: tuple[SocketOption, ...],
294
+ *,
295
+ openai_proxy: str | None,
296
+ ) -> None:
297
+ """Warn once if a custom transport will shadow httpx's proxy auto-detection.
298
+
299
+ When `socket_options` is non-empty we pass a custom `httpx` transport,
300
+ which disables httpx's native proxy auto-detection — both the uppercase
301
+ `HTTP_PROXY` / `HTTPS_PROXY` / `ALL_PROXY` env vars and their lowercase
302
+ equivalents, plus macOS/Windows system proxy config. If the user
303
+ supplies `openai_proxy` explicitly we route through it and the env-var
304
+ handling is moot. Otherwise, a user whose app was transparently relying
305
+ on any of those sources will silently stop using them on upgrade —
306
+ emit a single WARNING so the behavior change is discoverable.
307
+
308
+ Detection uses `urllib.request.getproxies()` — the same surface httpx
309
+ reads — so lowercase env vars and macOS/Windows system proxy settings
310
+ are caught alongside the uppercase names.
311
+ """
312
+ global _proxy_env_warning_emitted
313
+ if _proxy_env_warning_emitted or not socket_options or openai_proxy:
314
+ return
315
+ active = [name for name in _PROXY_ENV_VARS if os.environ.get(name)]
316
+ try:
317
+ detected = bool(urllib.request.getproxies())
318
+ except Exception:
319
+ detected = False
320
+ if not active and not detected:
321
+ return
322
+ _proxy_env_warning_emitted = True
323
+ if active:
324
+ source = ", ".join(active) + " set in environment"
325
+ else:
326
+ source = "system proxy configuration detected"
327
+ logger.warning(
328
+ "langchain-openai injected a custom httpx transport to apply "
329
+ "`http_socket_options`, which disables httpx's proxy "
330
+ "auto-detection (%s). Set "
331
+ "`LANGCHAIN_OPENAI_TCP_KEEPALIVE=0` or pass `http_socket_options=()` "
332
+ "to restore default proxy behavior, or supply `openai_proxy` / your "
333
+ "own `http_client` / `http_async_client` to take full control.",
334
+ source,
335
+ )
336
+
337
+
338
+ def _resolve_socket_options(
339
+ value: Sequence[SocketOption] | None,
340
+ ) -> tuple[SocketOption, ...]:
341
+ """Normalize the user-facing field to the tuple form builders expect.
342
+
343
+ - `None` => env-driven defaults (may itself be `()` if the user set
344
+ `LANGCHAIN_OPENAI_TCP_KEEPALIVE=0`). This path runs through
345
+ `_filter_supported()` inside `_default_socket_options()` because
346
+ the library-computed option set is aspirational and silent degradation
347
+ is the right posture.
348
+ - Any other sequence (including empty) => retupled for cache hashability.
349
+ An empty tuple is the explicit "disabled" signal. A non-empty sequence
350
+ is passed verbatim — **not** filtered. The user chose these options
351
+ explicitly, so an unsupported constant should surface as a clear
352
+ `OSError` at connect time, not be silently dropped.
353
+
354
+ Always returns a tuple — never `None` — so downstream signatures take
355
+ `tuple[SocketOption, ...]` with `()` as the single "no options" shape.
356
+ """
357
+ if value is None:
358
+ return _default_socket_options()
359
+ return tuple(value)
360
+
361
+
362
+ class _SyncHttpxClientWrapper(openai.DefaultHttpxClient):
363
+ """Borrowed from openai._base_client."""
364
+
365
+ def __del__(self) -> None:
366
+ try:
367
+ if self.is_closed:
368
+ return
369
+ self.close()
370
+ except Exception: # noqa: S110
371
+ pass
372
+
373
+
374
+ class _AsyncHttpxClientWrapper(openai.DefaultAsyncHttpxClient):
375
+ """Borrowed from openai._base_client."""
376
+
377
+ def __del__(self) -> None:
378
+ try:
379
+ if self.is_closed:
380
+ return
381
+ # TODO(someday): support non asyncio runtimes here
382
+ asyncio.get_running_loop().create_task(self.aclose())
383
+ except Exception: # noqa: S110
384
+ pass
385
+
386
+
387
+ def _build_sync_httpx_client(
388
+ base_url: str | None,
389
+ timeout: Any,
390
+ socket_options: tuple[SocketOption, ...] = (),
391
+ ) -> _SyncHttpxClientWrapper:
392
+ kwargs: dict[str, Any] = {
393
+ "base_url": base_url
394
+ or os.environ.get("OPENAI_BASE_URL")
395
+ or "https://api.openai.com/v1",
396
+ "timeout": timeout,
397
+ }
398
+ if socket_options:
399
+ # httpx ignores limits= when transport= is provided; set it explicitly
400
+ # on the transport to avoid silently shrinking the connection pool.
401
+ kwargs["transport"] = httpx.HTTPTransport(
402
+ socket_options=list(socket_options),
403
+ limits=_DEFAULT_CONNECTION_LIMITS,
404
+ )
405
+ return _SyncHttpxClientWrapper(**kwargs)
406
+
407
+
408
+ def _build_async_httpx_client(
409
+ base_url: str | None,
410
+ timeout: Any,
411
+ socket_options: tuple[SocketOption, ...] = (),
412
+ ) -> _AsyncHttpxClientWrapper:
413
+ kwargs: dict[str, Any] = {
414
+ "base_url": base_url
415
+ or os.environ.get("OPENAI_BASE_URL")
416
+ or "https://api.openai.com/v1",
417
+ "timeout": timeout,
418
+ }
419
+ if socket_options:
420
+ # See _build_sync_httpx_client for the limits= rationale.
421
+ kwargs["transport"] = httpx.AsyncHTTPTransport(
422
+ socket_options=list(socket_options),
423
+ limits=_DEFAULT_CONNECTION_LIMITS,
424
+ )
425
+ return _AsyncHttpxClientWrapper(**kwargs)
426
+
427
+
428
+ def _build_proxied_sync_httpx_client(
429
+ proxy: str,
430
+ verify: Any,
431
+ socket_options: tuple[SocketOption, ...] = (),
432
+ ) -> httpx.Client:
433
+ """httpx.Client for the openai_proxy code path.
434
+
435
+ When socket options are disabled (`()`), returns a plain
436
+ `httpx.Client(proxy=..., verify=...)` with no transport injected.
437
+ """
438
+ if not socket_options:
439
+ return httpx.Client(proxy=proxy, verify=verify)
440
+ # Mount under `all://` (not `transport=`) so `Client._mounts` mirrors the
441
+ # shape produced by httpx's own `proxy=` path — a single-entry dict keyed
442
+ # by `URLPattern("all://")`. Callers (and the existing proxy integration
443
+ # test) reach into `_mounts` to introspect the proxy URL; a bare
444
+ # `transport=` leaves `_mounts` empty.
445
+ #
446
+ # `httpx.HTTPTransport(proxy=...)` is stricter about string coercion than
447
+ # `httpx.Client(proxy=...)`; wrap in the public `httpx.Proxy` type for
448
+ # version-stable behavior.
449
+ transport = httpx.HTTPTransport(
450
+ proxy=httpx.Proxy(proxy),
451
+ verify=verify,
452
+ socket_options=list(socket_options),
453
+ limits=_DEFAULT_CONNECTION_LIMITS,
454
+ )
455
+ return httpx.Client(mounts={"all://": transport})
456
+
457
+
458
+ def _build_proxied_async_httpx_client(
459
+ proxy: str,
460
+ verify: Any,
461
+ socket_options: tuple[SocketOption, ...] = (),
462
+ ) -> httpx.AsyncClient:
463
+ """httpx.AsyncClient for the openai_proxy code path.
464
+
465
+ See `_build_proxied_sync_httpx_client` for the opt-out fallback,
466
+ the `mounts={"all://": ...}` shape, and the `httpx.Proxy` wrapping
467
+ rationale.
468
+ """
469
+ if not socket_options:
470
+ return httpx.AsyncClient(proxy=proxy, verify=verify)
471
+ transport = httpx.AsyncHTTPTransport(
472
+ proxy=httpx.Proxy(proxy),
473
+ verify=verify,
474
+ socket_options=list(socket_options),
475
+ limits=_DEFAULT_CONNECTION_LIMITS,
476
+ )
477
+ return httpx.AsyncClient(mounts={"all://": transport})
478
+
479
+
480
+ @lru_cache
481
+ def _cached_sync_httpx_client(
482
+ base_url: str | None,
483
+ timeout: Any,
484
+ socket_options: tuple[SocketOption, ...] = (),
485
+ ) -> _SyncHttpxClientWrapper:
486
+ return _build_sync_httpx_client(base_url, timeout, socket_options)
487
+
488
+
489
+ @lru_cache
490
+ def _cached_async_httpx_client(
491
+ base_url: str | None,
492
+ timeout: Any,
493
+ socket_options: tuple[SocketOption, ...] = (),
494
+ ) -> _AsyncHttpxClientWrapper:
495
+ return _build_async_httpx_client(base_url, timeout, socket_options)
496
+
497
+
498
+ def _get_default_httpx_client(
499
+ base_url: str | None,
500
+ timeout: Any,
501
+ socket_options: tuple[SocketOption, ...] = (),
502
+ ) -> _SyncHttpxClientWrapper:
503
+ """Get default httpx client.
504
+
505
+ Uses cached client unless timeout is `httpx.Timeout`, which is not hashable.
506
+ """
507
+ try:
508
+ hash(timeout)
509
+ except TypeError:
510
+ return _build_sync_httpx_client(base_url, timeout, socket_options)
511
+ else:
512
+ return _cached_sync_httpx_client(base_url, timeout, socket_options)
513
+
514
+
515
+ def _get_default_async_httpx_client(
516
+ base_url: str | None,
517
+ timeout: Any,
518
+ socket_options: tuple[SocketOption, ...] = (),
519
+ ) -> _AsyncHttpxClientWrapper:
520
+ """Get default httpx client.
521
+
522
+ Uses cached client unless timeout is `httpx.Timeout`, which is not hashable.
523
+ """
524
+ try:
525
+ hash(timeout)
526
+ except TypeError:
527
+ return _build_async_httpx_client(base_url, timeout, socket_options)
528
+ else:
529
+ return _cached_async_httpx_client(base_url, timeout, socket_options)
530
+
531
+
532
+ def _resolve_sync_and_async_api_keys(
533
+ api_key: SecretStr | Callable[[], str] | Callable[[], Awaitable[str]],
534
+ ) -> tuple[str | None | Callable[[], str], str | Callable[[], Awaitable[str]]]:
535
+ """Resolve sync and async API key values.
536
+
537
+ Because OpenAI and AsyncOpenAI clients support either sync or async callables for
538
+ the API key, we need to resolve separate values here.
539
+ """
540
+ if isinstance(api_key, SecretStr):
541
+ sync_api_key_value: str | None | Callable[[], str] = api_key.get_secret_value()
542
+ async_api_key_value: str | Callable[[], Awaitable[str]] = (
543
+ api_key.get_secret_value()
544
+ )
545
+ elif callable(api_key):
546
+ if inspect.iscoroutinefunction(api_key):
547
+ async_api_key_value = api_key
548
+ sync_api_key_value = None
549
+ else:
550
+ sync_api_key_value = cast(Callable, api_key)
551
+
552
+ async def async_api_key_wrapper() -> str:
553
+ return await asyncio.get_event_loop().run_in_executor(
554
+ None, cast(Callable, api_key)
555
+ )
556
+
557
+ async_api_key_value = async_api_key_wrapper
558
+
559
+ return sync_api_key_value, async_api_key_value
560
+
561
+
562
+ T = TypeVar("T")
563
+
564
+ # On Python ≤3.10, asyncio.TimeoutError and builtins.TimeoutError are distinct
565
+ # hierarchies, so subclassing only asyncio.TimeoutError would not be caught by
566
+ # `except TimeoutError:`. On Python ≥3.11 they are the same object, so listing
567
+ # both bases would raise TypeError: duplicate base class. We resolve this at
568
+ # class-definition time.
569
+ _StreamChunkTimeoutBases: tuple[type, ...] = (
570
+ (asyncio.TimeoutError,)
571
+ if issubclass(asyncio.TimeoutError, TimeoutError)
572
+ else (asyncio.TimeoutError, TimeoutError)
573
+ )
574
+
575
+
576
+ class StreamChunkTimeoutError(*_StreamChunkTimeoutBases): # type: ignore[misc]
577
+ """Raised when no streaming chunk arrives within `stream_chunk_timeout`.
578
+
579
+ `issubclass(StreamChunkTimeoutError, asyncio.TimeoutError)` and
580
+ `issubclass(StreamChunkTimeoutError, TimeoutError)` both hold on all
581
+ supported Python versions, so existing `except asyncio.TimeoutError:`
582
+ and `except TimeoutError:` handlers keep catching the exception. On
583
+ Python 3.11+ the two exceptions are the same object, so only
584
+ `asyncio.TimeoutError` appears in `__bases__`.
585
+
586
+ Structured attributes (`timeout_s`, `model_name`, `chunks_received`)
587
+ mirror the WARNING log's `extra=` payload so diagnostic code doesn't
588
+ need to regex the message.
589
+ """
590
+
591
+ def __init__(
592
+ self,
593
+ timeout_s: float,
594
+ *,
595
+ model_name: str | None = None,
596
+ chunks_received: int = 0,
597
+ ) -> None:
598
+ self.timeout_s = timeout_s
599
+ self.model_name = model_name
600
+ self.chunks_received = chunks_received
601
+ context = []
602
+ if model_name:
603
+ context.append(f"model={model_name}")
604
+ context.append(f"chunks_received={chunks_received}")
605
+ suffix = f" ({', '.join(context)})"
606
+ super().__init__(
607
+ f"No streaming chunk received for {timeout_s:.1f}s{suffix}. The "
608
+ f"connection may be alive at the TCP layer but is not producing "
609
+ f"content. Tune or disable via the `stream_chunk_timeout` "
610
+ f"constructor kwarg (set to None or 0 to disable) or the "
611
+ f"`LANGCHAIN_OPENAI_STREAM_CHUNK_TIMEOUT_S` env var. See also "
612
+ f"`http_socket_options` for the kernel-level TCP timeout that "
613
+ f"catches dead TCP peers."
614
+ )
615
+
616
+
617
+ async def _astream_with_chunk_timeout(
618
+ source: AsyncIterator[T],
619
+ timeout: float | None,
620
+ *,
621
+ model_name: str | None = None,
622
+ ) -> AsyncIterator[T]:
623
+ """Yield from `source` but bound the per-chunk wait time.
624
+
625
+ If `timeout` is None or <=0, yields directly with no wall-clock bound.
626
+ Otherwise, each `__anext__` is wrapped in
627
+ `asyncio.wait_for(..., timeout)`. A timeout raises
628
+ `StreamChunkTimeoutError` (a `TimeoutError` subclass) whose message
629
+ names the knob, the env-var override, the model, and how many chunks
630
+ were received before the stall. A single-line structured log also
631
+ fires at WARNING so the signal is visible in aggregate logging systems
632
+ even when the exception is caught upstream.
633
+
634
+ When the timeout is active, the source iterator is explicitly
635
+ `aclose()`-d on early exit (timeout, consumer break, any exception) so
636
+ the underlying httpx streaming connection is released promptly. The
637
+ pass-through branch (timeout disabled) relies on httpx's GC-driven
638
+ cleanup instead — matching the behavior of unwrapped streams.
639
+ """
640
+ if not timeout or timeout <= 0:
641
+ async for item in source:
642
+ yield item
643
+ return
644
+
645
+ chunks_received = 0
646
+ it = source.__aiter__()
647
+ try:
648
+ while True:
649
+ try:
650
+ chunk = await asyncio.wait_for(it.__anext__(), timeout=timeout)
651
+ except StopAsyncIteration:
652
+ return
653
+ except asyncio.TimeoutError as e:
654
+ logger.warning(
655
+ "langchain_openai.stream_chunk_timeout fired",
656
+ extra={
657
+ "source": "stream_chunk_timeout",
658
+ "timeout_s": timeout,
659
+ "model_name": model_name,
660
+ "chunks_received": chunks_received,
661
+ },
662
+ )
663
+ raise StreamChunkTimeoutError(
664
+ timeout,
665
+ model_name=model_name,
666
+ chunks_received=chunks_received,
667
+ ) from e
668
+ chunks_received += 1
669
+ yield chunk
670
+ finally:
671
+ aclose = getattr(it, "aclose", None)
672
+ if aclose is not None:
673
+ try:
674
+ await aclose()
675
+ except Exception as cleanup_exc:
676
+ # Best-effort cleanup; don't mask the original exception,
677
+ # but leave a DEBUG trace so pool/transport bugs stay
678
+ # discoverable at the right log level.
679
+ logger.debug(
680
+ "aclose() during _astream_with_chunk_timeout cleanup "
681
+ "raised; ignoring",
682
+ exc_info=cleanup_exc,
683
+ )
data/conda_envs/evalclaw/lib/python3.11/site-packages/langchain_openai/chat_models/_compat.py ADDED
@@ -0,0 +1,499 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Converts between AIMessage output formats, governed by `output_version`.
2
+
3
+ `output_version` is an attribute on ChatOpenAI.
4
+
5
+ Supported values are `None`, `'v0'`, and `'responses/v1'`.
6
+
7
+ `'v0'` corresponds to the format as of `ChatOpenAI` v0.3. For the Responses API, it
8
+ stores reasoning and tool outputs in `AIMessage.additional_kwargs`:
9
+
10
+ ```python
11
+ AIMessage(
12
+ content=[
13
+ {"type": "text", "text": "Hello, world!", "annotations": [{"type": "foo"}]}
14
+ ],
15
+ additional_kwargs={
16
+ "reasoning": {
17
+ "type": "reasoning",
18
+ "id": "rs_123",
19
+ "summary": [{"type": "summary_text", "text": "Reasoning summary"}],
20
+ },
21
+ "tool_outputs": [
22
+ {
23
+ "type": "web_search_call",
24
+ "id": "websearch_123",
25
+ "status": "completed",
26
+ }
27
+ ],
28
+ "refusal": "I cannot assist with that.",
29
+ },
30
+ response_metadata={"id": "resp_123"},
31
+ id="msg_123",
32
+ )
33
+ ```
34
+
35
+ `'responses/v1'` is only applicable to the Responses API. It retains information
36
+ about response item sequencing and accommodates multiple reasoning items by
37
+ representing these items in the content sequence:
38
+
39
+ ```python
40
+ AIMessage(
41
+ content=[
42
+ {
43
+ "type": "reasoning",
44
+ "summary": [{"type": "summary_text", "text": "Reasoning summary"}],
45
+ "id": "rs_123",
46
+ },
47
+ {
48
+ "type": "text",
49
+ "text": "Hello, world!",
50
+ "annotations": [{"type": "foo"}],
51
+ "id": "msg_123",
52
+ },
53
+ {"type": "refusal", "refusal": "I cannot assist with that."},
54
+ {"type": "web_search_call", "id": "websearch_123", "status": "completed"},
55
+ ],
56
+ response_metadata={"id": "resp_123"},
57
+ id="resp_123",
58
+ )
59
+ ```
60
+
61
+ There are other, small improvements as well-- e.g., we store message IDs on text
62
+ content blocks, rather than on the AIMessage.id, which now stores the response ID.
63
+
64
+ For backwards compatibility, this module provides functions to convert between the
65
+ formats. The functions are used internally by ChatOpenAI.
66
+ """
67
+
68
+ from __future__ import annotations
69
+
70
+ import json
71
+ from collections.abc import Iterable, Iterator
72
+ from typing import Any, cast
73
+
74
+ from langchain_core.messages import AIMessage, is_data_content_block
75
+ from langchain_core.messages import content as types
76
+
77
+ _FUNCTION_CALL_IDS_MAP_KEY = "__openai_function_call_ids__"
78
+
79
+
80
+ # v0.3 / Responses
81
+ def _convert_to_v03_ai_message(
82
+ message: AIMessage, has_reasoning: bool = False
83
+ ) -> AIMessage:
84
+ """Mutate an `AIMessage` to the old-style v0.3 format."""
85
+ if isinstance(message.content, list):
86
+ new_content: list[dict | str] = []
87
+ for block in message.content:
88
+ if isinstance(block, dict):
89
+ if block.get("type") == "reasoning":
90
+ # Store a reasoning item in additional_kwargs (overwriting as in
91
+ # v0.3)
92
+ _ = block.pop("index", None)
93
+ if has_reasoning:
94
+ _ = block.pop("id", None)
95
+ _ = block.pop("type", None)
96
+ message.additional_kwargs["reasoning"] = block
97
+ elif block.get("type") in (
98
+ "web_search_call",
99
+ "file_search_call",
100
+ "computer_call",
101
+ "code_interpreter_call",
102
+ "mcp_call",
103
+ "mcp_list_tools",
104
+ "mcp_approval_request",
105
+ "image_generation_call",
106
+ "tool_search_call",
107
+ "tool_search_output",
108
+ ):
109
+ # Store built-in tool calls in additional_kwargs
110
+ if "tool_outputs" not in message.additional_kwargs:
111
+ message.additional_kwargs["tool_outputs"] = []
112
+ message.additional_kwargs["tool_outputs"].append(block)
113
+ elif block.get("type") == "function_call":
114
+ # Store function call item IDs in additional_kwargs, otherwise
115
+ # discard function call items.
116
+ if _FUNCTION_CALL_IDS_MAP_KEY not in message.additional_kwargs:
117
+ message.additional_kwargs[_FUNCTION_CALL_IDS_MAP_KEY] = {}
118
+ if (call_id := block.get("call_id")) and (
119
+ function_call_id := block.get("id")
120
+ ):
121
+ message.additional_kwargs[_FUNCTION_CALL_IDS_MAP_KEY][
122
+ call_id
123
+ ] = function_call_id
124
+ elif (block.get("type") == "refusal") and (
125
+ refusal := block.get("refusal")
126
+ ):
127
+ # Store a refusal item in additional_kwargs (overwriting as in
128
+ # v0.3)
129
+ message.additional_kwargs["refusal"] = refusal
130
+ elif block.get("type") == "text":
131
+ # Store a message item ID on AIMessage.id
132
+ if "id" in block:
133
+ message.id = block["id"]
134
+ new_content.append({k: v for k, v in block.items() if k != "id"})
135
+ elif (
136
+ set(block.keys()) == {"id", "index"}
137
+ and isinstance(block["id"], str)
138
+ and block["id"].startswith("msg_")
139
+ ):
140
+ # Drop message IDs in streaming case
141
+ new_content.append({"index": block["index"]})
142
+ else:
143
+ new_content.append(block)
144
+ else:
145
+ new_content.append(block)
146
+ message.content = new_content
147
+ if isinstance(message.id, str) and message.id.startswith("resp_"):
148
+ message.id = None
149
+ else:
150
+ pass
151
+
152
+ return message
153
+
154
+
155
+ # v1 / Chat Completions
156
+ def _convert_from_v1_to_chat_completions(message: AIMessage) -> AIMessage:
157
+ """Convert a v1 message to the Chat Completions format."""
158
+ if isinstance(message.content, list):
159
+ new_content: list = []
160
+ for block in message.content:
161
+ if isinstance(block, dict):
162
+ block_type = block.get("type")
163
+ if block_type == "text":
164
+ # Strip annotations
165
+ new_content.append({"type": "text", "text": block["text"]})
166
+ elif block_type in ("reasoning", "tool_call"):
167
+ pass
168
+ else:
169
+ new_content.append(block)
170
+ else:
171
+ new_content.append(block)
172
+ return message.model_copy(update={"content": new_content})
173
+
174
+ return message
175
+
176
+
177
+ # v1 / Responses
178
+ def _convert_annotation_from_v1(annotation: types.Annotation) -> dict[str, Any]:
179
+ """Convert a v1 `Annotation` to the v0.3 format (for Responses API)."""
180
+ if annotation["type"] == "citation":
181
+ new_ann: dict[str, Any] = {}
182
+ for field in ("end_index", "start_index"):
183
+ if field in annotation:
184
+ new_ann[field] = annotation[field]
185
+
186
+ if "url" in annotation:
187
+ # URL citation
188
+ if "title" in annotation:
189
+ new_ann["title"] = annotation["title"]
190
+ new_ann["type"] = "url_citation"
191
+ new_ann["url"] = annotation["url"]
192
+
193
+ if extra_fields := annotation.get("extras"):
194
+ new_ann.update(dict(extra_fields.items()))
195
+ else:
196
+ # Document citation
197
+ new_ann["type"] = "file_citation"
198
+
199
+ if extra_fields := annotation.get("extras"):
200
+ new_ann.update(dict(extra_fields.items()))
201
+
202
+ if "title" in annotation:
203
+ new_ann["filename"] = annotation["title"]
204
+
205
+ return new_ann
206
+
207
+ if annotation["type"] == "non_standard_annotation":
208
+ return annotation["value"]
209
+
210
+ return dict(annotation)
211
+
212
+
213
+ def _implode_reasoning_blocks(blocks: list[dict[str, Any]]) -> Iterable[dict[str, Any]]:
214
+ i = 0
215
+ n = len(blocks)
216
+
217
+ while i < n:
218
+ block = blocks[i]
219
+
220
+ # Skip non-reasoning blocks or blocks already in Responses format
221
+ if block.get("type") != "reasoning" or "summary" in block:
222
+ yield dict(block)
223
+ i += 1
224
+ continue
225
+ elif "reasoning" not in block and "summary" not in block:
226
+ # {"type": "reasoning", "id": "rs_..."}
227
+ oai_format = {**block, "summary": []}
228
+ if "extras" in oai_format:
229
+ oai_format.update(oai_format.pop("extras"))
230
+ oai_format["type"] = oai_format.pop("type", "reasoning")
231
+ if "encrypted_content" in oai_format:
232
+ oai_format["encrypted_content"] = oai_format.pop("encrypted_content")
233
+ yield oai_format
234
+ i += 1
235
+ continue
236
+ else:
237
+ pass
238
+
239
+ summary: list[dict[str, str]] = [
240
+ {"type": "summary_text", "text": block.get("reasoning", "")}
241
+ ]
242
+ # 'common' is every field except the exploded 'reasoning'
243
+ common = {k: v for k, v in block.items() if k != "reasoning"}
244
+ if "extras" in common:
245
+ common.update(common.pop("extras"))
246
+
247
+ i += 1
248
+ while i < n:
249
+ next_ = blocks[i]
250
+ if next_.get("type") == "reasoning" and "reasoning" in next_:
251
+ summary.append(
252
+ {"type": "summary_text", "text": next_.get("reasoning", "")}
253
+ )
254
+ i += 1
255
+ else:
256
+ break
257
+
258
+ merged = dict(common)
259
+ merged["summary"] = summary
260
+ merged["type"] = merged.pop("type", "reasoning")
261
+ yield merged
262
+
263
+
264
+ def _consolidate_calls(items: Iterable[dict[str, Any]]) -> Iterator[dict[str, Any]]:
265
+ """Generator that walks through *items* and, whenever it meets the pair.
266
+
267
+ {"type": "server_tool_call", "name": "web_search", "id": X, ...}
268
+ {"type": "server_tool_result", "id": X}
269
+
270
+ merges them into
271
+
272
+ {"id": X,
273
+ "output": ...,
274
+ "status": ...,
275
+ "type": "web_search_call"}
276
+
277
+ keeping every other element untouched.
278
+ """
279
+ items = iter(items) # make sure we have a true iterator
280
+ for current in items:
281
+ # Only a call can start a pair worth collapsing
282
+ if current.get("type") != "server_tool_call":
283
+ yield current
284
+ continue
285
+
286
+ try:
287
+ nxt = next(items) # look-ahead one element
288
+ except StopIteration: # no “result” - just yield the call back
289
+ yield current
290
+ break
291
+
292
+ # If this really is the matching “result” - collapse
293
+ if nxt.get("type") == "server_tool_result" and nxt.get(
294
+ "tool_call_id"
295
+ ) == current.get("id"):
296
+ if current.get("name") == "web_search":
297
+ collapsed = {"id": current["id"]}
298
+ if "args" in current:
299
+ # N.B. as of 2025-09-17 OpenAI raises BadRequestError if sources
300
+ # are passed back in
301
+ collapsed["action"] = current["args"]
302
+
303
+ if status := nxt.get("status"):
304
+ if status == "success":
305
+ collapsed["status"] = "completed"
306
+ elif status == "error":
307
+ collapsed["status"] = "failed"
308
+ elif nxt.get("extras", {}).get("status"):
309
+ collapsed["status"] = nxt["extras"]["status"]
310
+ else:
311
+ pass
312
+ collapsed["type"] = "web_search_call"
313
+
314
+ if current.get("name") == "file_search":
315
+ collapsed = {"id": current["id"]}
316
+ if "args" in current and "queries" in current["args"]:
317
+ collapsed["queries"] = current["args"]["queries"]
318
+
319
+ if "output" in nxt:
320
+ collapsed["results"] = nxt["output"]
321
+ if status := nxt.get("status"):
322
+ if status == "success":
323
+ collapsed["status"] = "completed"
324
+ elif status == "error":
325
+ collapsed["status"] = "failed"
326
+ elif nxt.get("extras", {}).get("status"):
327
+ collapsed["status"] = nxt["extras"]["status"]
328
+ else:
329
+ pass
330
+ collapsed["type"] = "file_search_call"
331
+
332
+ elif current.get("name") == "code_interpreter":
333
+ collapsed = {"id": current["id"]}
334
+ if "args" in current and "code" in current["args"]:
335
+ collapsed["code"] = current["args"]["code"]
336
+ for key in ("container_id",):
337
+ if key in current:
338
+ collapsed[key] = current[key]
339
+ elif key in current.get("extras", {}):
340
+ collapsed[key] = current["extras"][key]
341
+ else:
342
+ pass
343
+
344
+ if "output" in nxt:
345
+ collapsed["outputs"] = nxt["output"]
346
+ if status := nxt.get("status"):
347
+ if status == "success":
348
+ collapsed["status"] = "completed"
349
+ elif status == "error":
350
+ collapsed["status"] = "failed"
351
+ elif nxt.get("extras", {}).get("status"):
352
+ collapsed["status"] = nxt["extras"]["status"]
353
+ collapsed["type"] = "code_interpreter_call"
354
+
355
+ elif current.get("name") == "remote_mcp":
356
+ collapsed = {"id": current["id"]}
357
+ if "args" in current:
358
+ collapsed["arguments"] = json.dumps(
359
+ current["args"], separators=(",", ":")
360
+ )
361
+ elif "arguments" in current.get("extras", {}):
362
+ collapsed["arguments"] = current["extras"]["arguments"]
363
+ else:
364
+ pass
365
+
366
+ if tool_name := current.get("extras", {}).get("tool_name"):
367
+ collapsed["name"] = tool_name
368
+ if server_label := current.get("extras", {}).get("server_label"):
369
+ collapsed["server_label"] = server_label
370
+ collapsed["type"] = "mcp_call"
371
+
372
+ if approval_id := current.get("extras", {}).get("approval_request_id"):
373
+ collapsed["approval_request_id"] = approval_id
374
+ if error := nxt.get("extras", {}).get("error"):
375
+ collapsed["error"] = error
376
+ if "output" in nxt:
377
+ collapsed["output"] = nxt["output"]
378
+ for k, v in current.get("extras", {}).items():
379
+ if k not in ("server_label", "arguments", "tool_name", "error"):
380
+ collapsed[k] = v
381
+
382
+ elif current.get("name") == "mcp_list_tools":
383
+ collapsed = {"id": current["id"]}
384
+ if server_label := current.get("extras", {}).get("server_label"):
385
+ collapsed["server_label"] = server_label
386
+ if "output" in nxt:
387
+ collapsed["tools"] = nxt["output"]
388
+ collapsed["type"] = "mcp_list_tools"
389
+ if error := nxt.get("extras", {}).get("error"):
390
+ collapsed["error"] = error
391
+ for k, v in current.get("extras", {}).items():
392
+ if k not in ("server_label", "error"):
393
+ collapsed[k] = v
394
+ else:
395
+ pass
396
+
397
+ yield collapsed
398
+
399
+ else:
400
+ # Not a matching pair - emit both, in original order
401
+ yield current
402
+ yield nxt
403
+
404
+
405
+ def _convert_from_v1_to_responses(
406
+ content: list[types.ContentBlock], tool_calls: list[types.ToolCall]
407
+ ) -> list[dict[str, Any]]:
408
+ new_content: list = []
409
+ for block in content:
410
+ if "type" not in block:
411
+ continue
412
+ if block["type"] == "text" and "annotations" in block:
413
+ # Need a copy because we're changing the annotations list
414
+ new_block = dict(block)
415
+ new_block["annotations"] = [
416
+ _convert_annotation_from_v1(a) for a in block["annotations"]
417
+ ]
418
+ new_content.append(new_block)
419
+ elif block["type"] == "tool_call":
420
+ new_block = {"type": "function_call", "call_id": block["id"]}
421
+ if "extras" in block and "item_id" in block["extras"]:
422
+ new_block["id"] = block["extras"]["item_id"]
423
+ if "name" in block:
424
+ new_block["name"] = block["name"]
425
+ if "extras" in block and "arguments" in block["extras"]:
426
+ new_block["arguments"] = block["extras"]["arguments"]
427
+ if any(key not in new_block for key in ("name", "arguments")):
428
+ matching_tool_calls = [
429
+ call for call in tool_calls if call["id"] == block["id"]
430
+ ]
431
+ if matching_tool_calls:
432
+ tool_call = matching_tool_calls[0]
433
+ if "name" not in new_block:
434
+ new_block["name"] = tool_call["name"]
435
+ if "arguments" not in new_block:
436
+ new_block["arguments"] = json.dumps(
437
+ tool_call["args"], separators=(",", ":")
438
+ )
439
+ if "extras" in block:
440
+ for extra_key in ("status", "namespace"):
441
+ if extra_key in block["extras"]:
442
+ new_block[extra_key] = block["extras"][extra_key]
443
+ new_content.append(new_block)
444
+
445
+ elif block["type"] == "server_tool_call" and block.get("name") == "tool_search":
446
+ extras = block.get("extras", {})
447
+ new_block = {"id": block["id"]}
448
+ status = extras.get("status")
449
+ if status:
450
+ new_block["status"] = status
451
+ new_block["type"] = "tool_search_call"
452
+ if "args" in block:
453
+ new_block["arguments"] = block["args"]
454
+ execution = extras.get("execution")
455
+ if execution:
456
+ new_block["execution"] = execution
457
+ new_content.append(new_block)
458
+
459
+ elif (
460
+ block["type"] == "server_tool_result"
461
+ and block.get("extras", {}).get("name") == "tool_search"
462
+ ):
463
+ extras = block.get("extras", {})
464
+ new_block = {"id": block.get("tool_call_id", "")}
465
+ status = block.get("status")
466
+ if status == "success":
467
+ new_block["status"] = "completed"
468
+ elif status == "error":
469
+ new_block["status"] = "failed"
470
+ elif status:
471
+ new_block["status"] = status
472
+ new_block["type"] = "tool_search_output"
473
+ new_block["execution"] = "server"
474
+ output: dict = block.get("output", {})
475
+ if isinstance(output, dict) and "tools" in output:
476
+ new_block["tools"] = output["tools"]
477
+ new_content.append(new_block)
478
+
479
+ elif (
480
+ is_data_content_block(cast(dict, block))
481
+ and block["type"] == "image"
482
+ and "base64" in block
483
+ and isinstance(block.get("id"), str)
484
+ and block["id"].startswith("ig_")
485
+ ):
486
+ new_block = {"type": "image_generation_call", "result": block["base64"]}
487
+ for extra_key in ("id", "status"):
488
+ if extra_key in block:
489
+ new_block[extra_key] = block[extra_key] # type: ignore[literal-required]
490
+ elif extra_key in block.get("extras", {}):
491
+ new_block[extra_key] = block["extras"][extra_key]
492
+ new_content.append(new_block)
493
+ elif block["type"] == "non_standard" and "value" in block:
494
+ new_content.append(block["value"])
495
+ else:
496
+ new_content.append(block)
497
+
498
+ new_content = list(_implode_reasoning_blocks(new_content))
499
+ return list(_consolidate_calls(new_content))