prompture 0.0.33.dev1__py3-none-any.whl → 0.0.34__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.
Files changed (56) hide show
  1. prompture/__init__.py +133 -49
  2. prompture/_version.py +34 -0
  3. prompture/aio/__init__.py +74 -0
  4. prompture/async_conversation.py +484 -0
  5. prompture/async_core.py +803 -0
  6. prompture/async_driver.py +131 -0
  7. prompture/cache.py +469 -0
  8. prompture/callbacks.py +50 -0
  9. prompture/cli.py +7 -3
  10. prompture/conversation.py +504 -0
  11. prompture/core.py +475 -352
  12. prompture/cost_mixin.py +51 -0
  13. prompture/discovery.py +50 -35
  14. prompture/driver.py +125 -5
  15. prompture/drivers/__init__.py +171 -73
  16. prompture/drivers/airllm_driver.py +13 -20
  17. prompture/drivers/async_airllm_driver.py +26 -0
  18. prompture/drivers/async_azure_driver.py +117 -0
  19. prompture/drivers/async_claude_driver.py +107 -0
  20. prompture/drivers/async_google_driver.py +132 -0
  21. prompture/drivers/async_grok_driver.py +91 -0
  22. prompture/drivers/async_groq_driver.py +84 -0
  23. prompture/drivers/async_hugging_driver.py +61 -0
  24. prompture/drivers/async_lmstudio_driver.py +79 -0
  25. prompture/drivers/async_local_http_driver.py +44 -0
  26. prompture/drivers/async_ollama_driver.py +125 -0
  27. prompture/drivers/async_openai_driver.py +96 -0
  28. prompture/drivers/async_openrouter_driver.py +96 -0
  29. prompture/drivers/async_registry.py +129 -0
  30. prompture/drivers/azure_driver.py +36 -9
  31. prompture/drivers/claude_driver.py +86 -34
  32. prompture/drivers/google_driver.py +87 -51
  33. prompture/drivers/grok_driver.py +29 -32
  34. prompture/drivers/groq_driver.py +27 -26
  35. prompture/drivers/hugging_driver.py +6 -6
  36. prompture/drivers/lmstudio_driver.py +26 -13
  37. prompture/drivers/local_http_driver.py +6 -6
  38. prompture/drivers/ollama_driver.py +90 -23
  39. prompture/drivers/openai_driver.py +36 -9
  40. prompture/drivers/openrouter_driver.py +31 -25
  41. prompture/drivers/registry.py +306 -0
  42. prompture/field_definitions.py +106 -96
  43. prompture/logging.py +80 -0
  44. prompture/model_rates.py +217 -0
  45. prompture/runner.py +49 -47
  46. prompture/session.py +117 -0
  47. prompture/settings.py +14 -1
  48. prompture/tools.py +172 -265
  49. prompture/validator.py +3 -3
  50. {prompture-0.0.33.dev1.dist-info → prompture-0.0.34.dist-info}/METADATA +18 -20
  51. prompture-0.0.34.dist-info/RECORD +55 -0
  52. prompture-0.0.33.dev1.dist-info/RECORD +0 -29
  53. {prompture-0.0.33.dev1.dist-info → prompture-0.0.34.dist-info}/WHEEL +0 -0
  54. {prompture-0.0.33.dev1.dist-info → prompture-0.0.34.dist-info}/entry_points.txt +0 -0
  55. {prompture-0.0.33.dev1.dist-info → prompture-0.0.34.dist-info}/licenses/LICENSE +0 -0
  56. {prompture-0.0.33.dev1.dist-info → prompture-0.0.34.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,504 @@
1
+ """Stateful multi-turn conversation support for Prompture."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import logging
7
+ from datetime import date, datetime
8
+ from decimal import Decimal
9
+ from typing import Any, Literal, Union
10
+
11
+ from pydantic import BaseModel
12
+
13
+ from .callbacks import DriverCallbacks
14
+ from .driver import Driver
15
+ from .drivers import get_driver_for_model
16
+ from .field_definitions import get_registry_snapshot
17
+ from .tools import (
18
+ clean_json_text,
19
+ convert_value,
20
+ get_field_default,
21
+ )
22
+
23
+ logger = logging.getLogger("prompture.conversation")
24
+
25
+
26
+ class Conversation:
27
+ """Stateful multi-turn conversation with an LLM.
28
+
29
+ Maintains a message history across calls so the model can reference
30
+ previous turns. Works with any Prompture driver.
31
+
32
+ Example::
33
+
34
+ conv = Conversation("openai/gpt-4", system_prompt="You are a data extractor")
35
+ r1 = conv.ask_for_json("Extract names from: John, age 30", name_schema)
36
+ r2 = conv.ask_for_json("Now extract ages", age_schema) # sees turn 1
37
+ """
38
+
39
+ def __init__(
40
+ self,
41
+ model_name: str | None = None,
42
+ *,
43
+ driver: Driver | None = None,
44
+ system_prompt: str | None = None,
45
+ options: dict[str, Any] | None = None,
46
+ callbacks: DriverCallbacks | None = None,
47
+ ) -> None:
48
+ if model_name is None and driver is None:
49
+ raise ValueError("Either model_name or driver must be provided")
50
+
51
+ if driver is not None:
52
+ self._driver = driver
53
+ else:
54
+ self._driver = get_driver_for_model(model_name)
55
+
56
+ if callbacks is not None:
57
+ self._driver.callbacks = callbacks
58
+
59
+ self._model_name = model_name or ""
60
+ self._system_prompt = system_prompt
61
+ self._options = dict(options) if options else {}
62
+ self._messages: list[dict[str, str]] = []
63
+ self._usage = {
64
+ "prompt_tokens": 0,
65
+ "completion_tokens": 0,
66
+ "total_tokens": 0,
67
+ "cost": 0.0,
68
+ "turns": 0,
69
+ }
70
+
71
+ # ------------------------------------------------------------------
72
+ # Public helpers
73
+ # ------------------------------------------------------------------
74
+
75
+ @property
76
+ def messages(self) -> list[dict[str, str]]:
77
+ """Read-only view of the conversation history."""
78
+ return list(self._messages)
79
+
80
+ @property
81
+ def usage(self) -> dict[str, Any]:
82
+ """Accumulated token/cost totals across all turns."""
83
+ return dict(self._usage)
84
+
85
+ def clear(self) -> None:
86
+ """Reset message history (keeps system_prompt and driver)."""
87
+ self._messages.clear()
88
+
89
+ def add_context(self, role: str, content: str) -> None:
90
+ """Seed the history with a user or assistant message."""
91
+ if role not in ("user", "assistant"):
92
+ raise ValueError("role must be 'user' or 'assistant'")
93
+ self._messages.append({"role": role, "content": content})
94
+
95
+ def usage_summary(self) -> str:
96
+ """Human-readable summary of accumulated usage."""
97
+ u = self._usage
98
+ return f"Conversation: {u['total_tokens']:,} tokens across {u['turns']} turn(s) costing ${u['cost']:.4f}"
99
+
100
+ # ------------------------------------------------------------------
101
+ # Core methods
102
+ # ------------------------------------------------------------------
103
+
104
+ def _build_messages(self, user_content: str) -> list[dict[str, str]]:
105
+ """Build the full messages array for an API call."""
106
+ msgs: list[dict[str, str]] = []
107
+ if self._system_prompt:
108
+ msgs.append({"role": "system", "content": self._system_prompt})
109
+ msgs.extend(self._messages)
110
+ msgs.append({"role": "user", "content": user_content})
111
+ return msgs
112
+
113
+ def _accumulate_usage(self, meta: dict[str, Any]) -> None:
114
+ self._usage["prompt_tokens"] += meta.get("prompt_tokens", 0)
115
+ self._usage["completion_tokens"] += meta.get("completion_tokens", 0)
116
+ self._usage["total_tokens"] += meta.get("total_tokens", 0)
117
+ self._usage["cost"] += meta.get("cost", 0.0)
118
+ self._usage["turns"] += 1
119
+
120
+ def ask(
121
+ self,
122
+ content: str,
123
+ options: dict[str, Any] | None = None,
124
+ ) -> str:
125
+ """Send a message and get a raw text response.
126
+
127
+ Appends the user message and assistant response to history.
128
+ """
129
+ merged = {**self._options, **(options or {})}
130
+ messages = self._build_messages(content)
131
+ resp = self._driver.generate_messages_with_hooks(messages, merged)
132
+
133
+ text = resp.get("text", "")
134
+ meta = resp.get("meta", {})
135
+
136
+ # Record in history
137
+ self._messages.append({"role": "user", "content": content})
138
+ self._messages.append({"role": "assistant", "content": text})
139
+ self._accumulate_usage(meta)
140
+
141
+ return text
142
+
143
+ def ask_for_json(
144
+ self,
145
+ content: str,
146
+ json_schema: dict[str, Any],
147
+ *,
148
+ ai_cleanup: bool = True,
149
+ options: dict[str, Any] | None = None,
150
+ output_format: Literal["json", "toon"] = "json",
151
+ json_mode: Literal["auto", "on", "off"] = "auto",
152
+ ) -> dict[str, Any]:
153
+ """Send a message with schema enforcement and get structured JSON back.
154
+
155
+ The schema instructions are appended to the prompt but only the
156
+ original *content* is stored in conversation history to keep
157
+ context clean for subsequent turns.
158
+ """
159
+
160
+ merged = {**self._options, **(options or {})}
161
+
162
+ # Build the full prompt with schema instructions inline (handled by ask_for_json)
163
+ # We use a special approach: call ask_for_json with the driver but pass messages context
164
+ schema_string = json.dumps(json_schema, indent=2)
165
+
166
+ # Determine JSON mode
167
+ use_json_mode = False
168
+ if json_mode == "on":
169
+ use_json_mode = True
170
+ elif json_mode == "auto":
171
+ use_json_mode = getattr(self._driver, "supports_json_mode", False)
172
+
173
+ if use_json_mode:
174
+ merged = {**merged, "json_mode": True}
175
+ if getattr(self._driver, "supports_json_schema", False):
176
+ merged["json_schema"] = json_schema
177
+
178
+ # Build instruction based on JSON mode
179
+ if use_json_mode and getattr(self._driver, "supports_json_schema", False):
180
+ instruct = "Extract data matching the requested schema.\nIf a value is unknown use null."
181
+ elif use_json_mode:
182
+ instruct = (
183
+ "Return a JSON object that validates against this schema:\n"
184
+ f"{schema_string}\n\n"
185
+ "If a value is unknown use null."
186
+ )
187
+ else:
188
+ instruct = (
189
+ "Return only a single JSON object (no markdown, no extra text) that validates against this JSON schema:\n"
190
+ f"{schema_string}\n\n"
191
+ "If a value is unknown use null. Use double quotes for keys and strings."
192
+ )
193
+
194
+ full_user_content = f"{content}\n\n{instruct}"
195
+
196
+ messages = self._build_messages(full_user_content)
197
+ resp = self._driver.generate_messages_with_hooks(messages, merged)
198
+
199
+ text = resp.get("text", "")
200
+ meta = resp.get("meta", {})
201
+
202
+ # Store original content (without schema boilerplate) for cleaner context
203
+ self._messages.append({"role": "user", "content": content})
204
+
205
+ # Parse JSON
206
+ cleaned = clean_json_text(text)
207
+ try:
208
+ json_obj = json.loads(cleaned)
209
+ except json.JSONDecodeError:
210
+ if ai_cleanup:
211
+ from .core import clean_json_text_with_ai
212
+
213
+ cleaned = clean_json_text_with_ai(self._driver, cleaned, self._model_name, merged)
214
+ json_obj = json.loads(cleaned)
215
+ else:
216
+ raise
217
+
218
+ # Store assistant response in history
219
+ self._messages.append({"role": "assistant", "content": cleaned})
220
+ self._accumulate_usage(meta)
221
+
222
+ model_name = self._model_name
223
+ if "/" in model_name:
224
+ model_name = model_name.split("/", 1)[1]
225
+
226
+ usage = {
227
+ **meta,
228
+ "raw_response": resp,
229
+ "model_name": model_name or getattr(self._driver, "model", ""),
230
+ }
231
+
232
+ result: dict[str, Any] = {
233
+ "json_string": cleaned,
234
+ "json_object": json_obj,
235
+ "usage": usage,
236
+ "output_format": output_format,
237
+ }
238
+
239
+ if output_format == "toon":
240
+ try:
241
+ import toon
242
+
243
+ result["toon_string"] = toon.encode(json_obj)
244
+ except ImportError:
245
+ raise RuntimeError("TOON requested but 'python-toon' is not installed.") from None
246
+
247
+ return result
248
+
249
+ def extract_with_model(
250
+ self,
251
+ model_cls: type[BaseModel],
252
+ text: str,
253
+ *,
254
+ instruction_template: str = "Extract information from the following text:",
255
+ ai_cleanup: bool = True,
256
+ output_format: Literal["json", "toon"] = "json",
257
+ options: dict[str, Any] | None = None,
258
+ json_mode: Literal["auto", "on", "off"] = "auto",
259
+ ) -> dict[str, Any]:
260
+ """Extract structured information into a Pydantic model with conversation context."""
261
+ from .core import normalize_field_value
262
+
263
+ schema = model_cls.model_json_schema()
264
+ content_prompt = f"{instruction_template} {text}"
265
+
266
+ result = self.ask_for_json(
267
+ content=content_prompt,
268
+ json_schema=schema,
269
+ ai_cleanup=ai_cleanup,
270
+ options=options,
271
+ output_format=output_format,
272
+ json_mode=json_mode,
273
+ )
274
+
275
+ # Normalize field values
276
+ json_object = result["json_object"]
277
+ schema_properties = schema.get("properties", {})
278
+
279
+ for field_name, field_info in model_cls.model_fields.items():
280
+ if field_name in json_object and field_name in schema_properties:
281
+ field_def = {
282
+ "nullable": not schema_properties[field_name].get("type")
283
+ or "null"
284
+ in (
285
+ schema_properties[field_name].get("anyOf", [])
286
+ if isinstance(schema_properties[field_name].get("anyOf"), list)
287
+ else []
288
+ ),
289
+ "default": field_info.default
290
+ if hasattr(field_info, "default") and field_info.default is not ...
291
+ else None,
292
+ }
293
+ json_object[field_name] = normalize_field_value(
294
+ json_object[field_name], field_info.annotation, field_def
295
+ )
296
+
297
+ model_instance = model_cls(**json_object)
298
+
299
+ result_dict = {
300
+ "json_string": result["json_string"],
301
+ "json_object": result["json_object"],
302
+ "usage": result["usage"],
303
+ }
304
+ result_dict["model"] = model_instance
305
+
306
+ return type(
307
+ "ExtractResult",
308
+ (dict,),
309
+ {
310
+ "__getattr__": lambda self, key: self.get(key),
311
+ "__call__": lambda self: self["model"],
312
+ },
313
+ )(result_dict)
314
+
315
+ # ------------------------------------------------------------------
316
+ # Internal: stepwise with shared context
317
+ # ------------------------------------------------------------------
318
+
319
+ def _stepwise_extract(
320
+ self,
321
+ model_cls: type[BaseModel],
322
+ text: str,
323
+ instruction_template: str,
324
+ ai_cleanup: bool,
325
+ fields: list[str] | None,
326
+ field_definitions: dict[str, Any] | None,
327
+ json_mode: Literal["auto", "on", "off"],
328
+ ) -> dict[str, Union[str, dict[str, Any]]]:
329
+ """Stepwise extraction using conversation context between fields."""
330
+ if field_definitions is None:
331
+ field_definitions = get_registry_snapshot()
332
+
333
+ data: dict[str, Any] = {}
334
+ validation_errors: list[str] = []
335
+ field_results: dict[str, Any] = {}
336
+
337
+ accumulated_usage = {
338
+ "prompt_tokens": 0,
339
+ "completion_tokens": 0,
340
+ "total_tokens": 0,
341
+ "cost": 0.0,
342
+ "model_name": self._model_name,
343
+ "field_usages": {},
344
+ }
345
+
346
+ valid_fields = set(model_cls.model_fields.keys())
347
+ if fields is not None:
348
+ invalid_fields = set(fields) - valid_fields
349
+ if invalid_fields:
350
+ raise KeyError(f"Fields not found in model: {', '.join(invalid_fields)}")
351
+ field_items = [(name, model_cls.model_fields[name]) for name in fields]
352
+ else:
353
+ field_items = list(model_cls.model_fields.items())
354
+
355
+ # Seed conversation with the source text
356
+ self.add_context("user", f"I need to extract information from this text:\n\n{text}")
357
+ self.add_context(
358
+ "assistant", "I'll help you extract the information from that text. What would you like to extract?"
359
+ )
360
+
361
+ for field_name, field_info in field_items:
362
+ logger.debug("[stepwise-conv] Extracting field: %s", field_name)
363
+
364
+ field_schema = {
365
+ "value": {
366
+ "type": "integer" if field_info.annotation is int else "string",
367
+ "description": field_info.description or f"Value for {field_name}",
368
+ }
369
+ }
370
+
371
+ try:
372
+ prompt = instruction_template.format(field_name=field_name)
373
+ result = self.ask_for_json(
374
+ content=f"{prompt} {text}",
375
+ json_schema=field_schema,
376
+ ai_cleanup=ai_cleanup,
377
+ json_mode=json_mode,
378
+ )
379
+
380
+ field_usage = result.get("usage", {})
381
+ accumulated_usage["prompt_tokens"] += field_usage.get("prompt_tokens", 0)
382
+ accumulated_usage["completion_tokens"] += field_usage.get("completion_tokens", 0)
383
+ accumulated_usage["total_tokens"] += field_usage.get("total_tokens", 0)
384
+ accumulated_usage["cost"] += field_usage.get("cost", 0.0)
385
+ accumulated_usage["field_usages"][field_name] = field_usage
386
+
387
+ extracted_value = result["json_object"]["value"]
388
+ if isinstance(extracted_value, dict) and "value" in extracted_value:
389
+ raw_value = extracted_value["value"]
390
+ else:
391
+ raw_value = extracted_value
392
+
393
+ # Normalize
394
+ from .core import normalize_field_value
395
+
396
+ field_def = {}
397
+ if field_definitions and field_name in field_definitions:
398
+ field_def = field_definitions[field_name] if isinstance(field_definitions[field_name], dict) else {}
399
+
400
+ nullable = field_def.get("nullable", True)
401
+ default_value = field_def.get("default")
402
+ if (
403
+ default_value is None
404
+ and hasattr(field_info, "default")
405
+ and field_info.default is not ...
406
+ and str(field_info.default) != "PydanticUndefined"
407
+ ):
408
+ default_value = field_info.default
409
+
410
+ normalize_def = {"nullable": nullable, "default": default_value}
411
+ raw_value = normalize_field_value(raw_value, field_info.annotation, normalize_def)
412
+
413
+ try:
414
+ converted_value = convert_value(raw_value, field_info.annotation, allow_shorthand=True)
415
+ data[field_name] = converted_value
416
+ field_results[field_name] = {"status": "success", "used_default": False}
417
+ except ValueError as e:
418
+ error_msg = f"Type conversion failed for {field_name}: {e!s}"
419
+ has_default = _has_default(field_name, field_info, field_definitions)
420
+ if not has_default:
421
+ validation_errors.append(error_msg)
422
+ default_value = get_field_default(field_name, field_info, field_definitions)
423
+ data[field_name] = default_value
424
+ field_results[field_name] = {
425
+ "status": "conversion_failed",
426
+ "error": error_msg,
427
+ "used_default": True,
428
+ }
429
+
430
+ except Exception as e:
431
+ error_msg = f"Extraction failed for {field_name}: {e!s}"
432
+ has_default = _has_default(field_name, field_info, field_definitions)
433
+ if not has_default:
434
+ validation_errors.append(error_msg)
435
+ default_value = get_field_default(field_name, field_info, field_definitions)
436
+ data[field_name] = default_value
437
+ field_results[field_name] = {"status": "extraction_failed", "error": error_msg, "used_default": True}
438
+ accumulated_usage["field_usages"][field_name] = {
439
+ "error": str(e),
440
+ "status": "failed",
441
+ "used_default": True,
442
+ "default_value": default_value,
443
+ }
444
+
445
+ if validation_errors:
446
+ accumulated_usage["validation_errors"] = validation_errors
447
+
448
+ try:
449
+ model_instance = model_cls(**data)
450
+ model_dict = model_instance.model_dump()
451
+
452
+ class ExtendedJSONEncoder(json.JSONEncoder):
453
+ def default(self, obj):
454
+ if isinstance(obj, (datetime, date)):
455
+ return obj.isoformat()
456
+ if isinstance(obj, Decimal):
457
+ return str(obj)
458
+ return super().default(obj)
459
+
460
+ json_string = json.dumps(model_dict, cls=ExtendedJSONEncoder)
461
+
462
+ result = {
463
+ "json_string": json_string,
464
+ "json_object": json.loads(json_string),
465
+ "usage": accumulated_usage,
466
+ "field_results": field_results,
467
+ }
468
+ result["model"] = model_instance
469
+ return type(
470
+ "ExtractResult",
471
+ (dict,),
472
+ {"__getattr__": lambda self, key: self.get(key), "__call__": lambda self: self["model"]},
473
+ )(result)
474
+ except Exception as e:
475
+ error_msg = f"Model validation error: {e!s}"
476
+ if "validation_errors" not in accumulated_usage:
477
+ accumulated_usage["validation_errors"] = []
478
+ accumulated_usage["validation_errors"].append(error_msg)
479
+
480
+ error_result = {
481
+ "json_string": "{}",
482
+ "json_object": {},
483
+ "usage": accumulated_usage,
484
+ "field_results": field_results,
485
+ "error": error_msg,
486
+ }
487
+ return type(
488
+ "ExtractResult",
489
+ (dict,),
490
+ {"__getattr__": lambda self, key: self.get(key), "__call__": lambda self: None},
491
+ )(error_result)
492
+
493
+
494
+ def _has_default(field_name: str, field_info: Any, field_definitions: dict[str, Any] | None) -> bool:
495
+ """Check whether a Pydantic field has a usable default value."""
496
+ if field_definitions and field_name in field_definitions:
497
+ fd = field_definitions[field_name]
498
+ if isinstance(fd, dict) and "default" in fd:
499
+ return True
500
+ if hasattr(field_info, "default"):
501
+ val = field_info.default
502
+ if val is not ... and str(val) != "PydanticUndefined":
503
+ return True
504
+ return False