prompture 0.0.29.dev8__py3-none-any.whl → 0.0.35__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 (67) hide show
  1. prompture/__init__.py +146 -23
  2. prompture/_version.py +34 -0
  3. prompture/aio/__init__.py +74 -0
  4. prompture/async_conversation.py +607 -0
  5. prompture/async_core.py +803 -0
  6. prompture/async_driver.py +169 -0
  7. prompture/cache.py +469 -0
  8. prompture/callbacks.py +55 -0
  9. prompture/cli.py +63 -4
  10. prompture/conversation.py +631 -0
  11. prompture/core.py +876 -263
  12. prompture/cost_mixin.py +51 -0
  13. prompture/discovery.py +164 -0
  14. prompture/driver.py +168 -5
  15. prompture/drivers/__init__.py +173 -69
  16. prompture/drivers/airllm_driver.py +109 -0
  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 +251 -34
  32. prompture/drivers/google_driver.py +107 -38
  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 +157 -23
  39. prompture/drivers/openai_driver.py +178 -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/scaffold/__init__.py +1 -0
  47. prompture/scaffold/generator.py +84 -0
  48. prompture/scaffold/templates/Dockerfile.j2 +12 -0
  49. prompture/scaffold/templates/README.md.j2 +41 -0
  50. prompture/scaffold/templates/config.py.j2 +21 -0
  51. prompture/scaffold/templates/env.example.j2 +8 -0
  52. prompture/scaffold/templates/main.py.j2 +86 -0
  53. prompture/scaffold/templates/models.py.j2 +40 -0
  54. prompture/scaffold/templates/requirements.txt.j2 +5 -0
  55. prompture/server.py +183 -0
  56. prompture/session.py +117 -0
  57. prompture/settings.py +18 -1
  58. prompture/tools.py +219 -267
  59. prompture/tools_schema.py +254 -0
  60. prompture/validator.py +3 -3
  61. {prompture-0.0.29.dev8.dist-info → prompture-0.0.35.dist-info}/METADATA +117 -21
  62. prompture-0.0.35.dist-info/RECORD +66 -0
  63. {prompture-0.0.29.dev8.dist-info → prompture-0.0.35.dist-info}/WHEEL +1 -1
  64. prompture-0.0.29.dev8.dist-info/RECORD +0 -27
  65. {prompture-0.0.29.dev8.dist-info → prompture-0.0.35.dist-info}/entry_points.txt +0 -0
  66. {prompture-0.0.29.dev8.dist-info → prompture-0.0.35.dist-info}/licenses/LICENSE +0 -0
  67. {prompture-0.0.29.dev8.dist-info → prompture-0.0.35.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,61 @@
1
+ """Async Hugging Face driver using httpx."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from typing import Any
7
+
8
+ import httpx
9
+
10
+ from ..async_driver import AsyncDriver
11
+
12
+
13
+ class AsyncHuggingFaceDriver(AsyncDriver):
14
+ MODEL_PRICING = {"default": {"prompt": 0.0, "completion": 0.0}}
15
+
16
+ def __init__(self, endpoint: str | None = None, token: str | None = None, model: str = "bert-base-uncased"):
17
+ self.endpoint = endpoint or os.getenv("HF_ENDPOINT")
18
+ self.token = token or os.getenv("HF_TOKEN")
19
+ self.model = model
20
+
21
+ if not self.endpoint:
22
+ raise ValueError("Hugging Face endpoint is not configured. Set HF_ENDPOINT or pass explicitly.")
23
+ if not self.token:
24
+ raise ValueError("Hugging Face token is not configured. Set HF_TOKEN or pass explicitly.")
25
+
26
+ self.headers = {"Authorization": f"Bearer {self.token}"}
27
+
28
+ async def generate(self, prompt: str, options: dict[str, Any]) -> dict[str, Any]:
29
+ payload = {
30
+ "inputs": prompt,
31
+ "parameters": options,
32
+ }
33
+
34
+ async with httpx.AsyncClient() as client:
35
+ try:
36
+ r = await client.post(
37
+ self.endpoint, headers=self.headers, json=payload, timeout=options.get("timeout", 60)
38
+ )
39
+ r.raise_for_status()
40
+ response_data = r.json()
41
+ except Exception as e:
42
+ raise RuntimeError(f"AsyncHuggingFaceDriver request failed: {e}") from e
43
+
44
+ text = None
45
+ if isinstance(response_data, list) and response_data and "generated_text" in response_data[0]:
46
+ text = response_data[0]["generated_text"]
47
+ elif isinstance(response_data, dict) and "generated_text" in response_data:
48
+ text = response_data["generated_text"]
49
+ else:
50
+ text = str(response_data)
51
+
52
+ meta = {
53
+ "prompt_tokens": 0,
54
+ "completion_tokens": 0,
55
+ "total_tokens": 0,
56
+ "cost": 0.0,
57
+ "raw_response": response_data,
58
+ "model_name": options.get("model", self.model),
59
+ }
60
+
61
+ return {"text": text, "meta": meta}
@@ -0,0 +1,79 @@
1
+ """Async LM Studio driver using httpx."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import os
7
+ from typing import Any
8
+
9
+ import httpx
10
+
11
+ from ..async_driver import AsyncDriver
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ class AsyncLMStudioDriver(AsyncDriver):
17
+ supports_json_mode = True
18
+
19
+ MODEL_PRICING = {"default": {"prompt": 0.0, "completion": 0.0}}
20
+
21
+ def __init__(self, endpoint: str | None = None, model: str = "deepseek/deepseek-r1-0528-qwen3-8b"):
22
+ self.endpoint = endpoint or os.getenv("LMSTUDIO_ENDPOINT", "http://127.0.0.1:1234/v1/chat/completions")
23
+ self.model = model
24
+ self.options: dict[str, Any] = {}
25
+
26
+ supports_messages = True
27
+
28
+ async def generate(self, prompt: str, options: dict[str, Any] | None = None) -> dict[str, Any]:
29
+ messages = [{"role": "user", "content": prompt}]
30
+ return await self._do_generate(messages, options)
31
+
32
+ async def generate_messages(self, messages: list[dict[str, str]], options: dict[str, Any]) -> dict[str, Any]:
33
+ return await self._do_generate(messages, options)
34
+
35
+ async def _do_generate(
36
+ self, messages: list[dict[str, str]], options: dict[str, Any] | None = None
37
+ ) -> dict[str, Any]:
38
+ merged_options = self.options.copy()
39
+ if options:
40
+ merged_options.update(options)
41
+
42
+ payload = {
43
+ "model": merged_options.get("model", self.model),
44
+ "messages": messages,
45
+ "temperature": merged_options.get("temperature", 0.7),
46
+ }
47
+
48
+ # Native JSON mode support
49
+ if merged_options.get("json_mode"):
50
+ payload["response_format"] = {"type": "json_object"}
51
+
52
+ async with httpx.AsyncClient() as client:
53
+ try:
54
+ r = await client.post(self.endpoint, json=payload, timeout=120)
55
+ r.raise_for_status()
56
+ response_data = r.json()
57
+ except Exception as e:
58
+ raise RuntimeError(f"AsyncLMStudioDriver request failed: {e}") from e
59
+
60
+ if "choices" not in response_data or not response_data["choices"]:
61
+ raise ValueError(f"Unexpected response format: {response_data}")
62
+
63
+ text = response_data["choices"][0]["message"]["content"]
64
+
65
+ usage = response_data.get("usage", {})
66
+ prompt_tokens = usage.get("prompt_tokens", 0)
67
+ completion_tokens = usage.get("completion_tokens", 0)
68
+ total_tokens = usage.get("total_tokens", prompt_tokens + completion_tokens)
69
+
70
+ meta = {
71
+ "prompt_tokens": prompt_tokens,
72
+ "completion_tokens": completion_tokens,
73
+ "total_tokens": total_tokens,
74
+ "cost": 0.0,
75
+ "raw_response": response_data,
76
+ "model_name": merged_options.get("model", self.model),
77
+ }
78
+
79
+ return {"text": text, "meta": meta}
@@ -0,0 +1,44 @@
1
+ """Async LocalHTTP driver using httpx."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from typing import Any
7
+
8
+ import httpx
9
+
10
+ from ..async_driver import AsyncDriver
11
+
12
+
13
+ class AsyncLocalHTTPDriver(AsyncDriver):
14
+ MODEL_PRICING = {"default": {"prompt": 0.0, "completion": 0.0}}
15
+
16
+ def __init__(self, endpoint: str | None = None, model: str = "local-model"):
17
+ self.endpoint = endpoint or os.getenv("LOCAL_HTTP_ENDPOINT", "http://localhost:8000/generate")
18
+ self.model = model
19
+
20
+ async def generate(self, prompt: str, options: dict[str, Any]) -> dict[str, Any]:
21
+ payload = {"prompt": prompt, "options": options}
22
+
23
+ async with httpx.AsyncClient() as client:
24
+ try:
25
+ r = await client.post(self.endpoint, json=payload, timeout=options.get("timeout", 30))
26
+ r.raise_for_status()
27
+ response_data = r.json()
28
+ except Exception as e:
29
+ raise RuntimeError(f"AsyncLocalHTTPDriver request failed: {e}") from e
30
+
31
+ if "text" in response_data and "meta" in response_data:
32
+ return response_data
33
+
34
+ meta = {
35
+ "prompt_tokens": response_data.get("prompt_tokens", 0),
36
+ "completion_tokens": response_data.get("completion_tokens", 0),
37
+ "total_tokens": response_data.get("total_tokens", 0),
38
+ "cost": 0.0,
39
+ "raw_response": response_data,
40
+ "model_name": options.get("model", self.model),
41
+ }
42
+
43
+ text = response_data.get("text") or response_data.get("response") or str(response_data)
44
+ return {"text": text, "meta": meta}
@@ -0,0 +1,125 @@
1
+ """Async Ollama driver using httpx."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import os
7
+ from typing import Any
8
+
9
+ import httpx
10
+
11
+ from ..async_driver import AsyncDriver
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+
16
+ class AsyncOllamaDriver(AsyncDriver):
17
+ supports_json_mode = True
18
+
19
+ MODEL_PRICING = {"default": {"prompt": 0.0, "completion": 0.0}}
20
+
21
+ def __init__(self, endpoint: str | None = None, model: str = "llama3"):
22
+ self.endpoint = endpoint or os.getenv("OLLAMA_ENDPOINT", "http://localhost:11434/api/generate")
23
+ self.model = model
24
+ self.options: dict[str, Any] = {}
25
+
26
+ supports_messages = True
27
+
28
+ async def generate(self, prompt: str, options: dict[str, Any] | None = None) -> dict[str, Any]:
29
+ merged_options = self.options.copy()
30
+ if options:
31
+ merged_options.update(options)
32
+
33
+ payload = {
34
+ "prompt": prompt,
35
+ "model": merged_options.get("model", self.model),
36
+ "stream": False,
37
+ }
38
+
39
+ # Native JSON mode support
40
+ if merged_options.get("json_mode"):
41
+ payload["format"] = "json"
42
+
43
+ if "temperature" in merged_options:
44
+ payload["temperature"] = merged_options["temperature"]
45
+ if "top_p" in merged_options:
46
+ payload["top_p"] = merged_options["top_p"]
47
+ if "top_k" in merged_options:
48
+ payload["top_k"] = merged_options["top_k"]
49
+
50
+ async with httpx.AsyncClient() as client:
51
+ try:
52
+ r = await client.post(self.endpoint, json=payload, timeout=120)
53
+ r.raise_for_status()
54
+ response_data = r.json()
55
+ except httpx.HTTPStatusError as e:
56
+ raise RuntimeError(f"Ollama request failed: {e}") from e
57
+ except Exception as e:
58
+ raise RuntimeError(f"Ollama request failed: {e}") from e
59
+
60
+ prompt_tokens = response_data.get("prompt_eval_count", 0)
61
+ completion_tokens = response_data.get("eval_count", 0)
62
+ total_tokens = prompt_tokens + completion_tokens
63
+
64
+ meta = {
65
+ "prompt_tokens": prompt_tokens,
66
+ "completion_tokens": completion_tokens,
67
+ "total_tokens": total_tokens,
68
+ "cost": 0.0,
69
+ "raw_response": response_data,
70
+ "model_name": merged_options.get("model", self.model),
71
+ }
72
+
73
+ return {"text": response_data.get("response", ""), "meta": meta}
74
+
75
+ async def generate_messages(self, messages: list[dict[str, str]], options: dict[str, Any]) -> dict[str, Any]:
76
+ """Use Ollama's /api/chat endpoint for multi-turn conversations."""
77
+ merged_options = self.options.copy()
78
+ if options:
79
+ merged_options.update(options)
80
+
81
+ # Derive the chat endpoint from the generate endpoint
82
+ chat_endpoint = self.endpoint.replace("/api/generate", "/api/chat")
83
+
84
+ payload: dict[str, Any] = {
85
+ "model": merged_options.get("model", self.model),
86
+ "messages": messages,
87
+ "stream": False,
88
+ }
89
+
90
+ if merged_options.get("json_mode"):
91
+ payload["format"] = "json"
92
+
93
+ if "temperature" in merged_options:
94
+ payload["temperature"] = merged_options["temperature"]
95
+ if "top_p" in merged_options:
96
+ payload["top_p"] = merged_options["top_p"]
97
+ if "top_k" in merged_options:
98
+ payload["top_k"] = merged_options["top_k"]
99
+
100
+ async with httpx.AsyncClient() as client:
101
+ try:
102
+ r = await client.post(chat_endpoint, json=payload, timeout=120)
103
+ r.raise_for_status()
104
+ response_data = r.json()
105
+ except httpx.HTTPStatusError as e:
106
+ raise RuntimeError(f"Ollama chat request failed: {e}") from e
107
+ except Exception as e:
108
+ raise RuntimeError(f"Ollama chat request failed: {e}") from e
109
+
110
+ prompt_tokens = response_data.get("prompt_eval_count", 0)
111
+ completion_tokens = response_data.get("eval_count", 0)
112
+ total_tokens = prompt_tokens + completion_tokens
113
+
114
+ meta = {
115
+ "prompt_tokens": prompt_tokens,
116
+ "completion_tokens": completion_tokens,
117
+ "total_tokens": total_tokens,
118
+ "cost": 0.0,
119
+ "raw_response": response_data,
120
+ "model_name": merged_options.get("model", self.model),
121
+ }
122
+
123
+ message = response_data.get("message", {})
124
+ text = message.get("content", "")
125
+ return {"text": text, "meta": meta}
@@ -0,0 +1,96 @@
1
+ """Async OpenAI driver. Requires the ``openai`` package (>=1.0.0)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from typing import Any
7
+
8
+ try:
9
+ from openai import AsyncOpenAI
10
+ except Exception:
11
+ AsyncOpenAI = None
12
+
13
+ from ..async_driver import AsyncDriver
14
+ from ..cost_mixin import CostMixin
15
+ from .openai_driver import OpenAIDriver
16
+
17
+
18
+ class AsyncOpenAIDriver(CostMixin, AsyncDriver):
19
+ supports_json_mode = True
20
+ supports_json_schema = True
21
+
22
+ MODEL_PRICING = OpenAIDriver.MODEL_PRICING
23
+
24
+ def __init__(self, api_key: str | None = None, model: str = "gpt-4o-mini"):
25
+ self.api_key = api_key or os.getenv("OPENAI_API_KEY")
26
+ self.model = model
27
+ if AsyncOpenAI:
28
+ self.client = AsyncOpenAI(api_key=self.api_key)
29
+ else:
30
+ self.client = None
31
+
32
+ supports_messages = True
33
+
34
+ async def generate(self, prompt: str, options: dict[str, Any]) -> dict[str, Any]:
35
+ messages = [{"role": "user", "content": prompt}]
36
+ return await self._do_generate(messages, options)
37
+
38
+ async def generate_messages(self, messages: list[dict[str, str]], options: dict[str, Any]) -> dict[str, Any]:
39
+ return await self._do_generate(messages, options)
40
+
41
+ async def _do_generate(self, messages: list[dict[str, str]], options: dict[str, Any]) -> dict[str, Any]:
42
+ if self.client is None:
43
+ raise RuntimeError("openai package (>=1.0.0) is not installed")
44
+
45
+ model = options.get("model", self.model)
46
+
47
+ model_info = self.MODEL_PRICING.get(model, {})
48
+ tokens_param = model_info.get("tokens_param", "max_tokens")
49
+ supports_temperature = model_info.get("supports_temperature", True)
50
+
51
+ opts = {"temperature": 1.0, "max_tokens": 512, **options}
52
+
53
+ kwargs = {
54
+ "model": model,
55
+ "messages": messages,
56
+ }
57
+ kwargs[tokens_param] = opts.get("max_tokens", 512)
58
+
59
+ if supports_temperature and "temperature" in opts:
60
+ kwargs["temperature"] = opts["temperature"]
61
+
62
+ # Native JSON mode support
63
+ if options.get("json_mode"):
64
+ json_schema = options.get("json_schema")
65
+ if json_schema:
66
+ kwargs["response_format"] = {
67
+ "type": "json_schema",
68
+ "json_schema": {
69
+ "name": "extraction",
70
+ "strict": True,
71
+ "schema": json_schema,
72
+ },
73
+ }
74
+ else:
75
+ kwargs["response_format"] = {"type": "json_object"}
76
+
77
+ resp = await self.client.chat.completions.create(**kwargs)
78
+
79
+ usage = getattr(resp, "usage", None)
80
+ prompt_tokens = getattr(usage, "prompt_tokens", 0)
81
+ completion_tokens = getattr(usage, "completion_tokens", 0)
82
+ total_tokens = getattr(usage, "total_tokens", 0)
83
+
84
+ total_cost = self._calculate_cost("openai", model, prompt_tokens, completion_tokens)
85
+
86
+ meta = {
87
+ "prompt_tokens": prompt_tokens,
88
+ "completion_tokens": completion_tokens,
89
+ "total_tokens": total_tokens,
90
+ "cost": total_cost,
91
+ "raw_response": resp.model_dump(),
92
+ "model_name": model,
93
+ }
94
+
95
+ text = resp.choices[0].message.content
96
+ return {"text": text, "meta": meta}
@@ -0,0 +1,96 @@
1
+ """Async OpenRouter driver using httpx."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from typing import Any
7
+
8
+ import httpx
9
+
10
+ from ..async_driver import AsyncDriver
11
+ from ..cost_mixin import CostMixin
12
+ from .openrouter_driver import OpenRouterDriver
13
+
14
+
15
+ class AsyncOpenRouterDriver(CostMixin, AsyncDriver):
16
+ supports_json_mode = True
17
+
18
+ MODEL_PRICING = OpenRouterDriver.MODEL_PRICING
19
+
20
+ def __init__(self, api_key: str | None = None, model: str = "openai/gpt-3.5-turbo"):
21
+ self.api_key = api_key or os.getenv("OPENROUTER_API_KEY")
22
+ if not self.api_key:
23
+ raise ValueError("OpenRouter API key not found. Set OPENROUTER_API_KEY env var.")
24
+ self.model = model
25
+ self.base_url = "https://openrouter.ai/api/v1"
26
+ self.headers = {
27
+ "Authorization": f"Bearer {self.api_key}",
28
+ "HTTP-Referer": "https://github.com/jhd3197/prompture",
29
+ "Content-Type": "application/json",
30
+ }
31
+
32
+ supports_messages = True
33
+
34
+ async def generate(self, prompt: str, options: dict[str, Any]) -> dict[str, Any]:
35
+ messages = [{"role": "user", "content": prompt}]
36
+ return await self._do_generate(messages, options)
37
+
38
+ async def generate_messages(self, messages: list[dict[str, str]], options: dict[str, Any]) -> dict[str, Any]:
39
+ return await self._do_generate(messages, options)
40
+
41
+ async def _do_generate(self, messages: list[dict[str, str]], options: dict[str, Any]) -> dict[str, Any]:
42
+ model = options.get("model", self.model)
43
+
44
+ model_info = self.MODEL_PRICING.get(model, {})
45
+ tokens_param = model_info.get("tokens_param", "max_tokens")
46
+ supports_temperature = model_info.get("supports_temperature", True)
47
+
48
+ opts = {"temperature": 1.0, "max_tokens": 512, **options}
49
+
50
+ data = {
51
+ "model": model,
52
+ "messages": messages,
53
+ }
54
+ data[tokens_param] = opts.get("max_tokens", 512)
55
+
56
+ if supports_temperature and "temperature" in opts:
57
+ data["temperature"] = opts["temperature"]
58
+
59
+ # Native JSON mode support
60
+ if options.get("json_mode"):
61
+ data["response_format"] = {"type": "json_object"}
62
+
63
+ async with httpx.AsyncClient() as client:
64
+ try:
65
+ response = await client.post(
66
+ f"{self.base_url}/chat/completions",
67
+ headers=self.headers,
68
+ json=data,
69
+ timeout=120,
70
+ )
71
+ response.raise_for_status()
72
+ resp = response.json()
73
+ except httpx.HTTPStatusError as e:
74
+ error_msg = f"OpenRouter API request failed: {e!s}"
75
+ raise RuntimeError(error_msg) from e
76
+ except Exception as e:
77
+ raise RuntimeError(f"OpenRouter API request failed: {e!s}") from e
78
+
79
+ usage = resp.get("usage", {})
80
+ prompt_tokens = usage.get("prompt_tokens", 0)
81
+ completion_tokens = usage.get("completion_tokens", 0)
82
+ total_tokens = usage.get("total_tokens", 0)
83
+
84
+ total_cost = self._calculate_cost("openrouter", model, prompt_tokens, completion_tokens)
85
+
86
+ meta = {
87
+ "prompt_tokens": prompt_tokens,
88
+ "completion_tokens": completion_tokens,
89
+ "total_tokens": total_tokens,
90
+ "cost": total_cost,
91
+ "raw_response": resp,
92
+ "model_name": model,
93
+ }
94
+
95
+ text = resp["choices"][0]["message"]["content"]
96
+ return {"text": text, "meta": meta}
@@ -0,0 +1,129 @@
1
+ """Async driver registry — mirrors the sync DRIVER_REGISTRY.
2
+
3
+ This module provides async driver registration and factory functions.
4
+ Custom async drivers can be registered via the ``register_async_driver()``
5
+ function or discovered via entry points.
6
+
7
+ Entry Point Discovery:
8
+ Add to your pyproject.toml:
9
+
10
+ [project.entry-points."prompture.async_drivers"]
11
+ my_provider = "my_package.drivers:my_async_driver_factory"
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from ..settings import settings
17
+ from .async_airllm_driver import AsyncAirLLMDriver
18
+ from .async_azure_driver import AsyncAzureDriver
19
+ from .async_claude_driver import AsyncClaudeDriver
20
+ from .async_google_driver import AsyncGoogleDriver
21
+ from .async_grok_driver import AsyncGrokDriver
22
+ from .async_groq_driver import AsyncGroqDriver
23
+ from .async_lmstudio_driver import AsyncLMStudioDriver
24
+ from .async_local_http_driver import AsyncLocalHTTPDriver
25
+ from .async_ollama_driver import AsyncOllamaDriver
26
+ from .async_openai_driver import AsyncOpenAIDriver
27
+ from .async_openrouter_driver import AsyncOpenRouterDriver
28
+ from .registry import (
29
+ _get_async_registry,
30
+ get_async_driver_factory,
31
+ register_async_driver,
32
+ )
33
+
34
+ # Register built-in async drivers
35
+ register_async_driver(
36
+ "openai",
37
+ lambda model=None: AsyncOpenAIDriver(api_key=settings.openai_api_key, model=model or settings.openai_model),
38
+ overwrite=True,
39
+ )
40
+ register_async_driver(
41
+ "ollama",
42
+ lambda model=None: AsyncOllamaDriver(endpoint=settings.ollama_endpoint, model=model or settings.ollama_model),
43
+ overwrite=True,
44
+ )
45
+ register_async_driver(
46
+ "claude",
47
+ lambda model=None: AsyncClaudeDriver(api_key=settings.claude_api_key, model=model or settings.claude_model),
48
+ overwrite=True,
49
+ )
50
+ register_async_driver(
51
+ "lmstudio",
52
+ lambda model=None: AsyncLMStudioDriver(endpoint=settings.lmstudio_endpoint, model=model or settings.lmstudio_model),
53
+ overwrite=True,
54
+ )
55
+ register_async_driver(
56
+ "azure",
57
+ lambda model=None: AsyncAzureDriver(
58
+ api_key=settings.azure_api_key, endpoint=settings.azure_api_endpoint, deployment_id=settings.azure_deployment_id
59
+ ),
60
+ overwrite=True,
61
+ )
62
+ register_async_driver(
63
+ "local_http",
64
+ lambda model=None: AsyncLocalHTTPDriver(endpoint=settings.local_http_endpoint, model=model),
65
+ overwrite=True,
66
+ )
67
+ register_async_driver(
68
+ "google",
69
+ lambda model=None: AsyncGoogleDriver(api_key=settings.google_api_key, model=model or settings.google_model),
70
+ overwrite=True,
71
+ )
72
+ register_async_driver(
73
+ "groq",
74
+ lambda model=None: AsyncGroqDriver(api_key=settings.groq_api_key, model=model or settings.groq_model),
75
+ overwrite=True,
76
+ )
77
+ register_async_driver(
78
+ "openrouter",
79
+ lambda model=None: AsyncOpenRouterDriver(
80
+ api_key=settings.openrouter_api_key, model=model or settings.openrouter_model
81
+ ),
82
+ overwrite=True,
83
+ )
84
+ register_async_driver(
85
+ "grok",
86
+ lambda model=None: AsyncGrokDriver(api_key=settings.grok_api_key, model=model or settings.grok_model),
87
+ overwrite=True,
88
+ )
89
+ register_async_driver(
90
+ "airllm",
91
+ lambda model=None: AsyncAirLLMDriver(
92
+ model=model or settings.airllm_model,
93
+ compression=settings.airllm_compression,
94
+ ),
95
+ overwrite=True,
96
+ )
97
+
98
+ # Backwards compatibility: expose registry dict
99
+ ASYNC_DRIVER_REGISTRY = _get_async_registry()
100
+
101
+
102
+ def get_async_driver(provider_name: str | None = None):
103
+ """Factory to get an async driver instance based on the provider name.
104
+
105
+ Uses default model from settings if not overridden.
106
+ """
107
+ provider = (provider_name or settings.ai_provider or "ollama").strip().lower()
108
+ factory = get_async_driver_factory(provider)
109
+ return factory()
110
+
111
+
112
+ def get_async_driver_for_model(model_str: str):
113
+ """Factory to get an async driver instance based on a full model string.
114
+
115
+ Format: ``provider/model_id``
116
+ Example: ``"openai/gpt-4-turbo-preview"``
117
+ """
118
+ if not isinstance(model_str, str):
119
+ raise ValueError("Model string must be a string, got {type(model_str)}")
120
+
121
+ if not model_str:
122
+ raise ValueError("Model string cannot be empty")
123
+
124
+ parts = model_str.split("/", 1)
125
+ provider = parts[0].lower()
126
+ model_id = parts[1] if len(parts) > 1 else None
127
+
128
+ factory = get_async_driver_factory(provider)
129
+ return factory(model_id)