paperminertoolkit 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- paperminertoolkit/__init__.py +10 -0
- paperminertoolkit/_version.py +11 -0
- paperminertoolkit/cli.py +1053 -0
- paperminertoolkit/corpus/__init__.py +1 -0
- paperminertoolkit/corpus/database.py +1542 -0
- paperminertoolkit/corpus/documents.py +313 -0
- paperminertoolkit/corpus/filtering.py +1390 -0
- paperminertoolkit/corpus/metadata.py +532 -0
- paperminertoolkit/extraction/__init__.py +1 -0
- paperminertoolkit/extraction/compression.py +486 -0
- paperminertoolkit/extraction/extract.py +573 -0
- paperminertoolkit/extraction/models.py +784 -0
- paperminertoolkit/extraction/recipes.py +241 -0
- paperminertoolkit/extraction/scrape.py +737 -0
- paperminertoolkit/extraction/store.py +244 -0
- paperminertoolkit/extraction/tokenizer.py +313 -0
- paperminertoolkit/providers/__init__.py +1 -0
- paperminertoolkit/providers/arxiv.py +760 -0
- paperminertoolkit/providers/base.py +514 -0
- paperminertoolkit/providers/biorxiv.py +561 -0
- paperminertoolkit/providers/chemrxiv.py +1115 -0
- paperminertoolkit/providers/core.py +423 -0
- paperminertoolkit/providers/crossref.py +649 -0
- paperminertoolkit/providers/elsevier.py +455 -0
- paperminertoolkit/providers/medrxiv.py +548 -0
- paperminertoolkit/providers/openalex.py +471 -0
- paperminertoolkit/providers/pubmed.py +1272 -0
- paperminertoolkit/providers/registry.py +521 -0
- paperminertoolkit/providers/rxiv.py +936 -0
- paperminertoolkit/providers/unpaywall.py +162 -0
- paperminertoolkit/resources/recipes.json +1670 -0
- paperminertoolkit/settings.py +661 -0
- paperminertoolkit/workflows/__init__.py +1 -0
- paperminertoolkit/workflows/download.py +1748 -0
- paperminertoolkit/workflows/enrichment.py +1906 -0
- paperminertoolkit/workflows/imports.py +121 -0
- paperminertoolkit/workflows/search.py +877 -0
- paperminertoolkit/workflows/topics.py +2837 -0
- paperminertoolkit/workflows/utilities.py +73 -0
- paperminertoolkit-1.0.0.dist-info/METADATA +126 -0
- paperminertoolkit-1.0.0.dist-info/RECORD +45 -0
- paperminertoolkit-1.0.0.dist-info/WHEEL +5 -0
- paperminertoolkit-1.0.0.dist-info/entry_points.txt +2 -0
- paperminertoolkit-1.0.0.dist-info/licenses/LICENSE +21 -0
- paperminertoolkit-1.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,784 @@
|
|
|
1
|
+
"""Model configuration and provider clients for text and vision requests.
|
|
2
|
+
|
|
3
|
+
This module hides provider differences behind a small client interface used by
|
|
4
|
+
the extraction code. It supports OpenAI Responses, Anthropic Messages, and
|
|
5
|
+
OpenAI-compatible local chat servers.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import base64
|
|
11
|
+
import mimetypes
|
|
12
|
+
import openai
|
|
13
|
+
import requests
|
|
14
|
+
from dataclasses import dataclass, field
|
|
15
|
+
from typing import Any, Self, TypedDict, Unpack
|
|
16
|
+
|
|
17
|
+
from paperminertoolkit.extraction.compression import CompressionConfig, maybe_compress_image_messages
|
|
18
|
+
from paperminertoolkit.settings import DEFAULT_INPUT_TOKEN_LIMIT, DEFAULT_MODEL, get_model_profile, load_settings
|
|
19
|
+
|
|
20
|
+
OPENAI_FIXED_SAMPLING_PREFIXES = ('gpt-5', 'o1', 'o3', 'o4')
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class _ModelOverrides(TypedDict, total=False):
|
|
24
|
+
"""Describe explicit overrides accepted by a model profile."""
|
|
25
|
+
|
|
26
|
+
provider: str
|
|
27
|
+
name: str
|
|
28
|
+
model: str
|
|
29
|
+
base_url: str | None
|
|
30
|
+
api_key: str | None
|
|
31
|
+
capabilities: str | list[str] | set[str] | tuple[str, ...]
|
|
32
|
+
temperature: float | int | str
|
|
33
|
+
top_p: float | int | str
|
|
34
|
+
input_token_limit: int | str
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class ModelCapabilityError(ValueError):
|
|
38
|
+
"""Raised when a configured model is asked to handle an unsupported input type."""
|
|
39
|
+
|
|
40
|
+
pass
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass
|
|
44
|
+
class ModelConfig:
|
|
45
|
+
"""Configure one text or vision model profile.
|
|
46
|
+
|
|
47
|
+
Attributes
|
|
48
|
+
----------
|
|
49
|
+
provider : str
|
|
50
|
+
Model provider name.
|
|
51
|
+
name : str
|
|
52
|
+
Provider model identifier.
|
|
53
|
+
base_url : str | None
|
|
54
|
+
Optional provider API base URL.
|
|
55
|
+
api_key : str | None
|
|
56
|
+
Optional provider API key.
|
|
57
|
+
capabilities : set[str]
|
|
58
|
+
Supported input capabilities, such as ``"text"`` and ``"vision"``.
|
|
59
|
+
temperature : float
|
|
60
|
+
Sampling temperature.
|
|
61
|
+
top_p : float
|
|
62
|
+
Nucleus sampling probability.
|
|
63
|
+
input_token_limit : int
|
|
64
|
+
Maximum model input size in tokens.
|
|
65
|
+
"""
|
|
66
|
+
|
|
67
|
+
provider: str = 'openai'
|
|
68
|
+
name: str = DEFAULT_MODEL
|
|
69
|
+
base_url: str | None = None
|
|
70
|
+
api_key: str | None = None
|
|
71
|
+
capabilities: set[str] = field(default_factory=lambda: {'text'})
|
|
72
|
+
temperature: float = 0
|
|
73
|
+
top_p: float = 1
|
|
74
|
+
input_token_limit: int = DEFAULT_INPUT_TOKEN_LIMIT
|
|
75
|
+
|
|
76
|
+
@classmethod
|
|
77
|
+
def from_profile(cls, profile: str = 'text', **overrides: Unpack[_ModelOverrides]) -> Self:
|
|
78
|
+
"""Build a configuration from a settings profile.
|
|
79
|
+
|
|
80
|
+
Parameters
|
|
81
|
+
----------
|
|
82
|
+
profile : str, optional
|
|
83
|
+
Settings profile to load.
|
|
84
|
+
**overrides : Unpack[_ModelOverrides]
|
|
85
|
+
Explicit configuration values that replace profile settings.
|
|
86
|
+
|
|
87
|
+
Returns
|
|
88
|
+
-------
|
|
89
|
+
ModelConfig
|
|
90
|
+
Resolved model configuration.
|
|
91
|
+
|
|
92
|
+
Raises
|
|
93
|
+
------
|
|
94
|
+
ValueError
|
|
95
|
+
If the provider changes without an explicit model name or a
|
|
96
|
+
numeric setting cannot be converted.
|
|
97
|
+
"""
|
|
98
|
+
configured = get_model_profile(profile)
|
|
99
|
+
capabilities = overrides.get('capabilities', configured.get('capabilities', ['text']))
|
|
100
|
+
if isinstance(capabilities, str):
|
|
101
|
+
capabilities = [cap.strip() for cap in capabilities.split(',') if cap.strip()]
|
|
102
|
+
settings = load_settings()
|
|
103
|
+
configured_provider = configured.get('provider') or 'openai'
|
|
104
|
+
provider = overrides.get('provider') or configured_provider
|
|
105
|
+
provider_changed = provider.lower().replace('_', '-') != configured_provider.lower().replace('_', '-')
|
|
106
|
+
name = overrides.get('name') or overrides.get('model')
|
|
107
|
+
if provider_changed and not name:
|
|
108
|
+
raise ValueError('Changing model provider requires an explicit model name.')
|
|
109
|
+
provider_key = f'{provider.lower()}_api_key'
|
|
110
|
+
profile_api_key = None if provider_changed else configured.get('api_key')
|
|
111
|
+
profile_base_url = None if provider_changed else configured.get('base_url')
|
|
112
|
+
return cls(
|
|
113
|
+
provider=provider,
|
|
114
|
+
name=name or configured.get('model') or DEFAULT_MODEL,
|
|
115
|
+
base_url=overrides.get('base_url') or profile_base_url,
|
|
116
|
+
api_key=overrides.get('api_key') or profile_api_key or settings.get(provider_key),
|
|
117
|
+
capabilities=set(capabilities or ['text']),
|
|
118
|
+
temperature=float(overrides.get('temperature', configured.get('temperature', 0))),
|
|
119
|
+
top_p=float(overrides.get('top_p', configured.get('top_p', 1))),
|
|
120
|
+
input_token_limit=int(
|
|
121
|
+
overrides.get('input_token_limit', configured.get('input_token_limit', DEFAULT_INPUT_TOKEN_LIMIT))
|
|
122
|
+
),
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
def generation_args(self) -> dict[str, float]:
|
|
126
|
+
"""Build provider-specific generation parameters.
|
|
127
|
+
|
|
128
|
+
Returns
|
|
129
|
+
-------
|
|
130
|
+
dict[str, float]
|
|
131
|
+
Supported sampling arguments for the configured provider and
|
|
132
|
+
model.
|
|
133
|
+
"""
|
|
134
|
+
provider = self.provider.lower().replace('_', '-')
|
|
135
|
+
model = self.name.lower()
|
|
136
|
+
if provider == 'openai' and model.startswith(OPENAI_FIXED_SAMPLING_PREFIXES):
|
|
137
|
+
return {}
|
|
138
|
+
args = {'temperature': self.temperature, 'top_p': self.top_p}
|
|
139
|
+
if provider == 'anthropic':
|
|
140
|
+
args.pop('top_p')
|
|
141
|
+
return args
|
|
142
|
+
|
|
143
|
+
def require(self, capability: str) -> None:
|
|
144
|
+
"""Require a model input capability.
|
|
145
|
+
|
|
146
|
+
Parameters
|
|
147
|
+
----------
|
|
148
|
+
capability : str
|
|
149
|
+
Capability required by the pending request.
|
|
150
|
+
|
|
151
|
+
Raises
|
|
152
|
+
------
|
|
153
|
+
ModelCapabilityError
|
|
154
|
+
If the configured model does not declare the capability.
|
|
155
|
+
"""
|
|
156
|
+
if capability not in self.capabilities:
|
|
157
|
+
caps = ', '.join(sorted(self.capabilities)) or 'none'
|
|
158
|
+
raise ModelCapabilityError(
|
|
159
|
+
f'Model "{self.name}" is configured for [{caps}] and cannot handle {capability} inputs.'
|
|
160
|
+
)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _image_to_data_url(path: str) -> str:
|
|
164
|
+
"""Encode a local image as a data URL.
|
|
165
|
+
|
|
166
|
+
Parameters
|
|
167
|
+
----------
|
|
168
|
+
path : str
|
|
169
|
+
Path to the image file.
|
|
170
|
+
|
|
171
|
+
Returns
|
|
172
|
+
-------
|
|
173
|
+
str
|
|
174
|
+
MIME-typed base64 data URL.
|
|
175
|
+
"""
|
|
176
|
+
mime_type = mimetypes.guess_type(path)[0] or 'image/png'
|
|
177
|
+
with open(path, 'rb') as image_file:
|
|
178
|
+
encoded = base64.b64encode(image_file.read()).decode('ascii')
|
|
179
|
+
return f'data:{mime_type};base64,{encoded}'
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
class BaseModelClient:
|
|
183
|
+
"""Abstract interface implemented by concrete model provider clients."""
|
|
184
|
+
|
|
185
|
+
def __init__(self, config: ModelConfig) -> None:
|
|
186
|
+
"""Initialize a model client.
|
|
187
|
+
|
|
188
|
+
Parameters
|
|
189
|
+
----------
|
|
190
|
+
config : ModelConfig
|
|
191
|
+
Configuration used for provider requests.
|
|
192
|
+
"""
|
|
193
|
+
self.config = config
|
|
194
|
+
|
|
195
|
+
def query(self, messages: list[dict[str, Any]], max_output_tokens: int = 10000) -> str:
|
|
196
|
+
"""Send a text-only request.
|
|
197
|
+
|
|
198
|
+
Parameters
|
|
199
|
+
----------
|
|
200
|
+
messages : list[dict[str, Any]]
|
|
201
|
+
Provider-neutral chat messages.
|
|
202
|
+
max_output_tokens : int, optional
|
|
203
|
+
Maximum number of tokens to generate.
|
|
204
|
+
|
|
205
|
+
Returns
|
|
206
|
+
-------
|
|
207
|
+
str
|
|
208
|
+
Model response text.
|
|
209
|
+
|
|
210
|
+
Raises
|
|
211
|
+
------
|
|
212
|
+
NotImplementedError
|
|
213
|
+
Always; subclasses must implement text requests.
|
|
214
|
+
"""
|
|
215
|
+
raise NotImplementedError
|
|
216
|
+
|
|
217
|
+
def query_with_images(self,
|
|
218
|
+
prompt: str,
|
|
219
|
+
image_paths: list[str],
|
|
220
|
+
context: str | None = None,
|
|
221
|
+
max_output_tokens: int = 10000,
|
|
222
|
+
compression_config: CompressionConfig | None = None) -> str:
|
|
223
|
+
"""Send a vision request with local images.
|
|
224
|
+
|
|
225
|
+
Parameters
|
|
226
|
+
----------
|
|
227
|
+
prompt : str
|
|
228
|
+
Instructions for image analysis.
|
|
229
|
+
image_paths : list[str]
|
|
230
|
+
Local images to include in the request.
|
|
231
|
+
context : str, optional
|
|
232
|
+
Additional text context.
|
|
233
|
+
max_output_tokens : int, optional
|
|
234
|
+
Maximum number of tokens to generate.
|
|
235
|
+
compression_config : CompressionConfig | None, optional
|
|
236
|
+
Compression policy for the provider payload.
|
|
237
|
+
|
|
238
|
+
Returns
|
|
239
|
+
-------
|
|
240
|
+
str
|
|
241
|
+
Model response text.
|
|
242
|
+
|
|
243
|
+
Raises
|
|
244
|
+
------
|
|
245
|
+
NotImplementedError
|
|
246
|
+
Always; subclasses must implement vision requests.
|
|
247
|
+
"""
|
|
248
|
+
raise NotImplementedError
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
class OpenAIResponsesClient(BaseModelClient):
|
|
252
|
+
"""Client for OpenAI's Responses API."""
|
|
253
|
+
|
|
254
|
+
def __init__(self, config: ModelConfig) -> None:
|
|
255
|
+
"""Initialize an OpenAI Responses client.
|
|
256
|
+
|
|
257
|
+
Parameters
|
|
258
|
+
----------
|
|
259
|
+
config : ModelConfig
|
|
260
|
+
OpenAI model and connection configuration.
|
|
261
|
+
"""
|
|
262
|
+
super().__init__(config)
|
|
263
|
+
kwargs = {}
|
|
264
|
+
if config.api_key:
|
|
265
|
+
kwargs['api_key'] = config.api_key
|
|
266
|
+
if config.base_url:
|
|
267
|
+
kwargs['base_url'] = config.base_url
|
|
268
|
+
self.client = openai.OpenAI(**kwargs)
|
|
269
|
+
|
|
270
|
+
def _response_text(self, response: object) -> str:
|
|
271
|
+
"""Extract text from an OpenAI response.
|
|
272
|
+
|
|
273
|
+
Parameters
|
|
274
|
+
----------
|
|
275
|
+
response : object
|
|
276
|
+
Responses API result object.
|
|
277
|
+
|
|
278
|
+
Returns
|
|
279
|
+
-------
|
|
280
|
+
str
|
|
281
|
+
First available response text.
|
|
282
|
+
|
|
283
|
+
Raises
|
|
284
|
+
------
|
|
285
|
+
RuntimeError
|
|
286
|
+
If the response contains no text output.
|
|
287
|
+
"""
|
|
288
|
+
if getattr(response, 'output_text', None):
|
|
289
|
+
return response.output_text
|
|
290
|
+
for output in getattr(response, 'output', []):
|
|
291
|
+
for content in getattr(output, 'content', []):
|
|
292
|
+
text = getattr(content, 'text', None)
|
|
293
|
+
if text:
|
|
294
|
+
return text
|
|
295
|
+
raise RuntimeError('Model response did not contain text output.')
|
|
296
|
+
|
|
297
|
+
def query(self, messages: list[dict[str, Any]], max_output_tokens: int = 10000) -> str:
|
|
298
|
+
"""Send a text request through OpenAI Responses.
|
|
299
|
+
|
|
300
|
+
Parameters
|
|
301
|
+
----------
|
|
302
|
+
messages : list[dict[str, Any]]
|
|
303
|
+
Responses API input messages.
|
|
304
|
+
max_output_tokens : int, optional
|
|
305
|
+
Maximum number of tokens to generate.
|
|
306
|
+
|
|
307
|
+
Returns
|
|
308
|
+
-------
|
|
309
|
+
str
|
|
310
|
+
Model response text.
|
|
311
|
+
|
|
312
|
+
Raises
|
|
313
|
+
------
|
|
314
|
+
ModelCapabilityError
|
|
315
|
+
If the model lacks text capability.
|
|
316
|
+
RuntimeError
|
|
317
|
+
If the OpenAI request fails or returns no text.
|
|
318
|
+
"""
|
|
319
|
+
self.config.require('text')
|
|
320
|
+
try:
|
|
321
|
+
response = self.client.responses.create(
|
|
322
|
+
model=self.config.name,
|
|
323
|
+
input=messages,
|
|
324
|
+
max_output_tokens=max_output_tokens,
|
|
325
|
+
**self.config.generation_args(),
|
|
326
|
+
)
|
|
327
|
+
except openai.OpenAIError as e:
|
|
328
|
+
raise RuntimeError(f'OpenAI request failed: {e}') from e
|
|
329
|
+
return self._response_text(response)
|
|
330
|
+
|
|
331
|
+
def query_with_images(self,
|
|
332
|
+
prompt: str,
|
|
333
|
+
image_paths: list[str],
|
|
334
|
+
context: str | None = None,
|
|
335
|
+
max_output_tokens: int = 10000,
|
|
336
|
+
compression_config: CompressionConfig | None = None) -> str:
|
|
337
|
+
"""Send an image request through OpenAI Responses.
|
|
338
|
+
|
|
339
|
+
Parameters
|
|
340
|
+
----------
|
|
341
|
+
prompt : str
|
|
342
|
+
Instructions for image analysis.
|
|
343
|
+
image_paths : list[str]
|
|
344
|
+
Local images to include in the request.
|
|
345
|
+
context : str, optional
|
|
346
|
+
Additional text context.
|
|
347
|
+
max_output_tokens : int, optional
|
|
348
|
+
Maximum number of tokens to generate.
|
|
349
|
+
compression_config : CompressionConfig | None, optional
|
|
350
|
+
Compression policy for the provider payload.
|
|
351
|
+
|
|
352
|
+
Returns
|
|
353
|
+
-------
|
|
354
|
+
str
|
|
355
|
+
Model response text.
|
|
356
|
+
|
|
357
|
+
Raises
|
|
358
|
+
------
|
|
359
|
+
ModelCapabilityError
|
|
360
|
+
If the model lacks vision capability.
|
|
361
|
+
RuntimeError
|
|
362
|
+
If the OpenAI request fails or returns no text.
|
|
363
|
+
"""
|
|
364
|
+
self.config.require('vision')
|
|
365
|
+
content = [{'type': 'input_text', 'text': prompt}]
|
|
366
|
+
if context:
|
|
367
|
+
content.append({'type': 'input_text', 'text': context})
|
|
368
|
+
for image_path in image_paths:
|
|
369
|
+
content.append({'type': 'input_image', 'image_url': _image_to_data_url(image_path)})
|
|
370
|
+
messages = [{'role': 'user', 'content': content}]
|
|
371
|
+
messages = maybe_compress_image_messages(
|
|
372
|
+
messages,
|
|
373
|
+
image_paths,
|
|
374
|
+
prompt,
|
|
375
|
+
context,
|
|
376
|
+
self.config,
|
|
377
|
+
compression_config,
|
|
378
|
+
)
|
|
379
|
+
try:
|
|
380
|
+
response = self.client.responses.create(
|
|
381
|
+
model=self.config.name,
|
|
382
|
+
input=messages,
|
|
383
|
+
max_output_tokens=max_output_tokens,
|
|
384
|
+
**self.config.generation_args(),
|
|
385
|
+
)
|
|
386
|
+
except openai.OpenAIError as e:
|
|
387
|
+
raise RuntimeError(f'OpenAI vision request failed: {e}') from e
|
|
388
|
+
return self._response_text(response)
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
class AnthropicMessagesClient(BaseModelClient):
|
|
392
|
+
"""Client for Anthropic's Messages API."""
|
|
393
|
+
|
|
394
|
+
def query(self, messages: list[dict[str, Any]], max_output_tokens: int = 10000) -> str:
|
|
395
|
+
"""Send a text request through Anthropic Messages.
|
|
396
|
+
|
|
397
|
+
Parameters
|
|
398
|
+
----------
|
|
399
|
+
messages : list[dict[str, Any]]
|
|
400
|
+
Provider-neutral chat messages.
|
|
401
|
+
max_output_tokens : int, optional
|
|
402
|
+
Maximum number of tokens to generate.
|
|
403
|
+
|
|
404
|
+
Returns
|
|
405
|
+
-------
|
|
406
|
+
str
|
|
407
|
+
Joined text from the Anthropic response.
|
|
408
|
+
|
|
409
|
+
Raises
|
|
410
|
+
------
|
|
411
|
+
ModelCapabilityError
|
|
412
|
+
If the model lacks text capability.
|
|
413
|
+
ValueError
|
|
414
|
+
If no Anthropic API key is configured.
|
|
415
|
+
RuntimeError
|
|
416
|
+
If the provider request fails.
|
|
417
|
+
"""
|
|
418
|
+
self.config.require('text')
|
|
419
|
+
if not self.config.api_key:
|
|
420
|
+
raise ValueError('Anthropic provider requires an API key in the model profile or settings.')
|
|
421
|
+
system = ''
|
|
422
|
+
anthropic_messages = []
|
|
423
|
+
for message in messages:
|
|
424
|
+
if message.get('role') == 'system':
|
|
425
|
+
system += message.get('content', '')
|
|
426
|
+
else:
|
|
427
|
+
anthropic_messages.append({
|
|
428
|
+
'role': message.get('role', 'user'),
|
|
429
|
+
'content': message.get('content', ''),
|
|
430
|
+
})
|
|
431
|
+
return self._request(system, anthropic_messages, max_output_tokens)
|
|
432
|
+
|
|
433
|
+
def query_with_images(self,
|
|
434
|
+
prompt: str,
|
|
435
|
+
image_paths: list[str],
|
|
436
|
+
context: str | None = None,
|
|
437
|
+
max_output_tokens: int = 10000,
|
|
438
|
+
compression_config: CompressionConfig | None = None) -> str:
|
|
439
|
+
"""Send an image request through Anthropic Messages.
|
|
440
|
+
|
|
441
|
+
Parameters
|
|
442
|
+
----------
|
|
443
|
+
prompt : str
|
|
444
|
+
Instructions for image analysis.
|
|
445
|
+
image_paths : list[str]
|
|
446
|
+
Local images to encode in the request.
|
|
447
|
+
context : str, optional
|
|
448
|
+
Additional text context.
|
|
449
|
+
max_output_tokens : int, optional
|
|
450
|
+
Maximum number of tokens to generate.
|
|
451
|
+
compression_config : CompressionConfig | None, optional
|
|
452
|
+
Compression policy for the provider payload.
|
|
453
|
+
|
|
454
|
+
Returns
|
|
455
|
+
-------
|
|
456
|
+
str
|
|
457
|
+
Joined text from the Anthropic response.
|
|
458
|
+
|
|
459
|
+
Raises
|
|
460
|
+
------
|
|
461
|
+
ModelCapabilityError
|
|
462
|
+
If the model lacks vision capability.
|
|
463
|
+
ValueError
|
|
464
|
+
If no Anthropic API key is configured.
|
|
465
|
+
RuntimeError
|
|
466
|
+
If the provider request fails.
|
|
467
|
+
"""
|
|
468
|
+
self.config.require('vision')
|
|
469
|
+
content = [{'type': 'text', 'text': prompt}]
|
|
470
|
+
if context:
|
|
471
|
+
content.append({'type': 'text', 'text': context})
|
|
472
|
+
for image_path in image_paths:
|
|
473
|
+
mime_type = mimetypes.guess_type(image_path)[0] or 'image/png'
|
|
474
|
+
with open(image_path, 'rb') as image_file:
|
|
475
|
+
encoded = base64.b64encode(image_file.read()).decode('ascii')
|
|
476
|
+
content.append({
|
|
477
|
+
'type': 'image',
|
|
478
|
+
'source': {'type': 'base64', 'media_type': mime_type, 'data': encoded},
|
|
479
|
+
})
|
|
480
|
+
messages = [{'role': 'user', 'content': content}]
|
|
481
|
+
messages = maybe_compress_image_messages(
|
|
482
|
+
messages,
|
|
483
|
+
image_paths,
|
|
484
|
+
prompt,
|
|
485
|
+
context,
|
|
486
|
+
self.config,
|
|
487
|
+
compression_config,
|
|
488
|
+
)
|
|
489
|
+
return self._request('', messages, max_output_tokens)
|
|
490
|
+
|
|
491
|
+
def _request(
|
|
492
|
+
self,
|
|
493
|
+
system: str,
|
|
494
|
+
anthropic_messages: list[dict[str, Any]],
|
|
495
|
+
max_output_tokens: int,
|
|
496
|
+
) -> str:
|
|
497
|
+
"""Post a prepared Anthropic Messages request.
|
|
498
|
+
|
|
499
|
+
Parameters
|
|
500
|
+
----------
|
|
501
|
+
system : str
|
|
502
|
+
System instructions for the request.
|
|
503
|
+
anthropic_messages : list[dict[str, Any]]
|
|
504
|
+
Anthropic-formatted conversation messages.
|
|
505
|
+
max_output_tokens : int
|
|
506
|
+
Maximum number of tokens to generate.
|
|
507
|
+
|
|
508
|
+
Returns
|
|
509
|
+
-------
|
|
510
|
+
str
|
|
511
|
+
Joined text blocks from the response.
|
|
512
|
+
|
|
513
|
+
Raises
|
|
514
|
+
------
|
|
515
|
+
ValueError
|
|
516
|
+
If no Anthropic API key is configured.
|
|
517
|
+
RuntimeError
|
|
518
|
+
If the HTTP request fails.
|
|
519
|
+
"""
|
|
520
|
+
if not self.config.api_key:
|
|
521
|
+
raise ValueError('Anthropic provider requires an API key in the model profile or settings.')
|
|
522
|
+
payload = {
|
|
523
|
+
'model': self.config.name,
|
|
524
|
+
'max_tokens': max_output_tokens,
|
|
525
|
+
'messages': anthropic_messages,
|
|
526
|
+
**self.config.generation_args(),
|
|
527
|
+
}
|
|
528
|
+
if system:
|
|
529
|
+
payload['system'] = system
|
|
530
|
+
headers = {
|
|
531
|
+
'x-api-key': self.config.api_key,
|
|
532
|
+
'anthropic-version': '2023-06-01',
|
|
533
|
+
'content-type': 'application/json',
|
|
534
|
+
}
|
|
535
|
+
base_url = (self.config.base_url or 'https://api.anthropic.com').rstrip('/')
|
|
536
|
+
endpoint = f'{base_url}/messages' if base_url.endswith('/v1') else f'{base_url}/v1/messages'
|
|
537
|
+
try:
|
|
538
|
+
response = requests.post(endpoint, headers=headers, json=payload, timeout=120)
|
|
539
|
+
response.raise_for_status()
|
|
540
|
+
except requests.HTTPError as e:
|
|
541
|
+
detail = _anthropic_error_detail(e.response)
|
|
542
|
+
suffix = f': {detail}' if detail else ''
|
|
543
|
+
raise RuntimeError(f'Anthropic request failed: {e}{suffix}') from e
|
|
544
|
+
except requests.RequestException as e:
|
|
545
|
+
raise RuntimeError(f'Anthropic request failed: {e}') from e
|
|
546
|
+
data = response.json()
|
|
547
|
+
chunks = [block.get('text', '') for block in data.get('content', []) if block.get('type') == 'text']
|
|
548
|
+
return ''.join(chunks)
|
|
549
|
+
|
|
550
|
+
|
|
551
|
+
def _anthropic_error_detail(response: requests.Response | None) -> str:
|
|
552
|
+
"""Extract a concise Anthropic error message.
|
|
553
|
+
|
|
554
|
+
Parameters
|
|
555
|
+
----------
|
|
556
|
+
response : requests.Response | None
|
|
557
|
+
Failed HTTP response.
|
|
558
|
+
|
|
559
|
+
Returns
|
|
560
|
+
-------
|
|
561
|
+
str
|
|
562
|
+
Provider error detail truncated to 1,000 characters.
|
|
563
|
+
"""
|
|
564
|
+
if response is None:
|
|
565
|
+
return ''
|
|
566
|
+
try:
|
|
567
|
+
data = response.json()
|
|
568
|
+
except (requests.JSONDecodeError, ValueError):
|
|
569
|
+
data = None
|
|
570
|
+
if isinstance(data, dict):
|
|
571
|
+
error = data.get('error')
|
|
572
|
+
if isinstance(error, dict) and error.get('message'):
|
|
573
|
+
return str(error['message'])[:1000]
|
|
574
|
+
return str(getattr(response, 'text', '') or '').strip()[:1000]
|
|
575
|
+
|
|
576
|
+
|
|
577
|
+
class OpenAICompatibleChatClient(BaseModelClient):
|
|
578
|
+
"""Client for local or third-party OpenAI-compatible chat servers."""
|
|
579
|
+
|
|
580
|
+
def __init__(self, config: ModelConfig) -> None:
|
|
581
|
+
"""Initialize an OpenAI-compatible chat client.
|
|
582
|
+
|
|
583
|
+
Parameters
|
|
584
|
+
----------
|
|
585
|
+
config : ModelConfig
|
|
586
|
+
Model and connection configuration.
|
|
587
|
+
"""
|
|
588
|
+
super().__init__(config)
|
|
589
|
+
kwargs = {'api_key': config.api_key or 'not-needed'}
|
|
590
|
+
if config.base_url:
|
|
591
|
+
kwargs['base_url'] = config.base_url
|
|
592
|
+
self.client = openai.OpenAI(**kwargs)
|
|
593
|
+
|
|
594
|
+
def query(self, messages: list[dict[str, Any]], max_output_tokens: int = 10000) -> str:
|
|
595
|
+
"""Send a text chat completion request.
|
|
596
|
+
|
|
597
|
+
Parameters
|
|
598
|
+
----------
|
|
599
|
+
messages : list[dict[str, Any]]
|
|
600
|
+
Chat completion messages.
|
|
601
|
+
max_output_tokens : int, optional
|
|
602
|
+
Maximum number of tokens to generate.
|
|
603
|
+
|
|
604
|
+
Returns
|
|
605
|
+
-------
|
|
606
|
+
str
|
|
607
|
+
Model response text.
|
|
608
|
+
|
|
609
|
+
Raises
|
|
610
|
+
------
|
|
611
|
+
ModelCapabilityError
|
|
612
|
+
If the model lacks text capability.
|
|
613
|
+
RuntimeError
|
|
614
|
+
If the provider request fails.
|
|
615
|
+
"""
|
|
616
|
+
self.config.require('text')
|
|
617
|
+
return self._chat(messages, max_output_tokens)
|
|
618
|
+
|
|
619
|
+
def query_with_images(self,
|
|
620
|
+
prompt: str,
|
|
621
|
+
image_paths: list[str],
|
|
622
|
+
context: str | None = None,
|
|
623
|
+
max_output_tokens: int = 10000,
|
|
624
|
+
compression_config: CompressionConfig | None = None) -> str:
|
|
625
|
+
"""Send images as OpenAI-compatible chat content.
|
|
626
|
+
|
|
627
|
+
Parameters
|
|
628
|
+
----------
|
|
629
|
+
prompt : str
|
|
630
|
+
Instructions for image analysis.
|
|
631
|
+
image_paths : list[str]
|
|
632
|
+
Local images to encode in the request.
|
|
633
|
+
context : str, optional
|
|
634
|
+
Additional text context.
|
|
635
|
+
max_output_tokens : int, optional
|
|
636
|
+
Maximum number of tokens to generate.
|
|
637
|
+
compression_config : CompressionConfig | None, optional
|
|
638
|
+
Compression policy for the provider payload.
|
|
639
|
+
|
|
640
|
+
Returns
|
|
641
|
+
-------
|
|
642
|
+
str
|
|
643
|
+
Model response text.
|
|
644
|
+
|
|
645
|
+
Raises
|
|
646
|
+
------
|
|
647
|
+
ModelCapabilityError
|
|
648
|
+
If the model lacks vision capability.
|
|
649
|
+
RuntimeError
|
|
650
|
+
If the provider request fails.
|
|
651
|
+
"""
|
|
652
|
+
self.config.require('vision')
|
|
653
|
+
content = [{'type': 'text', 'text': prompt}]
|
|
654
|
+
if context:
|
|
655
|
+
content.append({'type': 'text', 'text': context})
|
|
656
|
+
for image_path in image_paths:
|
|
657
|
+
content.append({'type': 'image_url', 'image_url': {'url': _image_to_data_url(image_path)}})
|
|
658
|
+
messages = [{'role': 'user', 'content': content}]
|
|
659
|
+
messages = maybe_compress_image_messages(
|
|
660
|
+
messages,
|
|
661
|
+
image_paths,
|
|
662
|
+
prompt,
|
|
663
|
+
context,
|
|
664
|
+
self.config,
|
|
665
|
+
compression_config,
|
|
666
|
+
)
|
|
667
|
+
return self._chat(messages, max_output_tokens)
|
|
668
|
+
|
|
669
|
+
def _chat(self, messages: list[dict[str, Any]], max_output_tokens: int) -> str:
|
|
670
|
+
"""Call the chat completions endpoint.
|
|
671
|
+
|
|
672
|
+
Parameters
|
|
673
|
+
----------
|
|
674
|
+
messages : list[dict[str, Any]]
|
|
675
|
+
Provider-formatted chat messages.
|
|
676
|
+
max_output_tokens : int
|
|
677
|
+
Maximum number of tokens to generate.
|
|
678
|
+
|
|
679
|
+
Returns
|
|
680
|
+
-------
|
|
681
|
+
str
|
|
682
|
+
First response message text, or an empty string.
|
|
683
|
+
|
|
684
|
+
Raises
|
|
685
|
+
------
|
|
686
|
+
RuntimeError
|
|
687
|
+
If the provider request fails.
|
|
688
|
+
"""
|
|
689
|
+
try:
|
|
690
|
+
response = self.client.chat.completions.create(
|
|
691
|
+
model=self.config.name,
|
|
692
|
+
messages=messages,
|
|
693
|
+
max_tokens=max_output_tokens,
|
|
694
|
+
**self.config.generation_args(),
|
|
695
|
+
)
|
|
696
|
+
except openai.OpenAIError as e:
|
|
697
|
+
raise RuntimeError(f'Local model request failed: {e}') from e
|
|
698
|
+
return response.choices[0].message.content or ''
|
|
699
|
+
|
|
700
|
+
|
|
701
|
+
def get_model_client(config: ModelConfig | None = None) -> BaseModelClient:
|
|
702
|
+
"""Create the provider client for a model configuration.
|
|
703
|
+
|
|
704
|
+
Parameters
|
|
705
|
+
----------
|
|
706
|
+
config : ModelConfig | None, optional
|
|
707
|
+
Model configuration. The text profile is used by default.
|
|
708
|
+
|
|
709
|
+
Returns
|
|
710
|
+
-------
|
|
711
|
+
BaseModelClient
|
|
712
|
+
Client implementation for the configured provider.
|
|
713
|
+
|
|
714
|
+
Raises
|
|
715
|
+
------
|
|
716
|
+
ValueError
|
|
717
|
+
If the provider is unknown or a local provider lacks a base URL.
|
|
718
|
+
"""
|
|
719
|
+
config = config or ModelConfig.from_profile('text')
|
|
720
|
+
provider = config.provider.lower().replace('_', '-')
|
|
721
|
+
if provider == 'openai':
|
|
722
|
+
return OpenAIResponsesClient(config)
|
|
723
|
+
if provider == 'anthropic':
|
|
724
|
+
return AnthropicMessagesClient(config)
|
|
725
|
+
if provider == 'local':
|
|
726
|
+
if not config.base_url:
|
|
727
|
+
raise ValueError(f'Provider "{config.provider}" requires a base URL.')
|
|
728
|
+
return OpenAICompatibleChatClient(config)
|
|
729
|
+
raise ValueError(f'Unknown model provider: {config.provider}')
|
|
730
|
+
|
|
731
|
+
|
|
732
|
+
def query_text(messages: list[dict[str, Any]],
|
|
733
|
+
config: ModelConfig | None = None,
|
|
734
|
+
max_output_tokens: int = 10000) -> str:
|
|
735
|
+
"""Send a text request through a configured provider.
|
|
736
|
+
|
|
737
|
+
Parameters
|
|
738
|
+
----------
|
|
739
|
+
messages : list[dict[str, Any]]
|
|
740
|
+
Provider-neutral chat messages.
|
|
741
|
+
config : ModelConfig | None, optional
|
|
742
|
+
Model configuration. The text profile is used by default.
|
|
743
|
+
max_output_tokens : int, optional
|
|
744
|
+
Maximum number of tokens to generate.
|
|
745
|
+
|
|
746
|
+
Returns
|
|
747
|
+
-------
|
|
748
|
+
str
|
|
749
|
+
Model response text.
|
|
750
|
+
"""
|
|
751
|
+
return get_model_client(config).query(messages, max_output_tokens=max_output_tokens)
|
|
752
|
+
|
|
753
|
+
|
|
754
|
+
def query_images(prompt: str,
|
|
755
|
+
image_paths: list[str],
|
|
756
|
+
config: ModelConfig | None = None,
|
|
757
|
+
context: str | None = None,
|
|
758
|
+
max_output_tokens: int = 10000,
|
|
759
|
+
compression_config: CompressionConfig | None = None) -> str:
|
|
760
|
+
"""Send an image request through a configured provider.
|
|
761
|
+
|
|
762
|
+
Parameters
|
|
763
|
+
----------
|
|
764
|
+
prompt : str
|
|
765
|
+
Instructions for image analysis.
|
|
766
|
+
image_paths : list[str]
|
|
767
|
+
Local images to include in the request.
|
|
768
|
+
config : ModelConfig | None, optional
|
|
769
|
+
Vision model configuration.
|
|
770
|
+
context : str, optional
|
|
771
|
+
Additional text context.
|
|
772
|
+
max_output_tokens : int, optional
|
|
773
|
+
Maximum number of tokens to generate.
|
|
774
|
+
compression_config : CompressionConfig | None, optional
|
|
775
|
+
Compression policy for the provider payload.
|
|
776
|
+
|
|
777
|
+
Returns
|
|
778
|
+
-------
|
|
779
|
+
str
|
|
780
|
+
Model response text.
|
|
781
|
+
"""
|
|
782
|
+
return get_model_client(config).query_with_images(prompt, image_paths, context=context,
|
|
783
|
+
max_output_tokens=max_output_tokens,
|
|
784
|
+
compression_config=compression_config)
|