text2cypher 3.0.1__tar.gz → 3.0.2__tar.gz

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 (52) hide show
  1. {text2cypher-3.0.1 → text2cypher-3.0.2}/PKG-INFO +6 -4
  2. {text2cypher-3.0.1 → text2cypher-3.0.2}/README.md +2 -2
  3. {text2cypher-3.0.1 → text2cypher-3.0.2}/pyproject.toml +6 -2
  4. {text2cypher-3.0.1 → text2cypher-3.0.2}/pyproject.toml.orig +8 -2
  5. {text2cypher-3.0.1 → text2cypher-3.0.2}/src/text2cypher/_generation/schema_filter.py +18 -14
  6. {text2cypher-3.0.1 → text2cypher-3.0.2}/src/text2cypher/_pipeline.py +14 -9
  7. text2cypher-3.0.2/src/text2cypher/llm/_adapt.py +73 -0
  8. text2cypher-3.0.2/src/text2cypher/llm/_messages.py +251 -0
  9. text2cypher-3.0.1/src/text2cypher/llm/_adapt.py +0 -47
  10. {text2cypher-3.0.1 → text2cypher-3.0.2}/LICENSE +0 -0
  11. {text2cypher-3.0.1 → text2cypher-3.0.2}/THIRD_PARTY_NOTICES +0 -0
  12. {text2cypher-3.0.1 → text2cypher-3.0.2}/src/text2cypher/__init__.py +0 -0
  13. {text2cypher-3.0.1 → text2cypher-3.0.2}/src/text2cypher/_config.py +0 -0
  14. {text2cypher-3.0.1 → text2cypher-3.0.2}/src/text2cypher/_errors.py +0 -0
  15. {text2cypher-3.0.1 → text2cypher-3.0.2}/src/text2cypher/_generation/__init__.py +0 -0
  16. {text2cypher-3.0.1 → text2cypher-3.0.2}/src/text2cypher/_generation/conversation.py +0 -0
  17. {text2cypher-3.0.1 → text2cypher-3.0.2}/src/text2cypher/_generation/extract.py +0 -0
  18. {text2cypher-3.0.1 → text2cypher-3.0.2}/src/text2cypher/_generation/generate.py +0 -0
  19. {text2cypher-3.0.1 → text2cypher-3.0.2}/src/text2cypher/_generation/header.py +0 -0
  20. {text2cypher-3.0.1 → text2cypher-3.0.2}/src/text2cypher/_generation/problems.py +0 -0
  21. {text2cypher-3.0.1 → text2cypher-3.0.2}/src/text2cypher/_generation/prompts.py +0 -0
  22. {text2cypher-3.0.1 → text2cypher-3.0.2}/src/text2cypher/_generation/read_skill.py +0 -0
  23. {text2cypher-3.0.1 → text2cypher-3.0.2}/src/text2cypher/_generation/typos.py +0 -0
  24. {text2cypher-3.0.1 → text2cypher-3.0.2}/src/text2cypher/_graph/__init__.py +0 -0
  25. {text2cypher-3.0.1 → text2cypher-3.0.2}/src/text2cypher/_graph/examples.py +0 -0
  26. {text2cypher-3.0.1 → text2cypher-3.0.2}/src/text2cypher/_graph/execution.py +0 -0
  27. {text2cypher-3.0.1 → text2cypher-3.0.2}/src/text2cypher/_graph/schema_source.py +0 -0
  28. {text2cypher-3.0.1 → text2cypher-3.0.2}/src/text2cypher/_results/__init__.py +0 -0
  29. {text2cypher-3.0.1 → text2cypher-3.0.2}/src/text2cypher/_results/results.py +0 -0
  30. {text2cypher-3.0.1 → text2cypher-3.0.2}/src/text2cypher/_results/values.py +0 -0
  31. {text2cypher-3.0.1 → text2cypher-3.0.2}/src/text2cypher/_skills/__init__.py +0 -0
  32. {text2cypher-3.0.1 → text2cypher-3.0.2}/src/text2cypher/_skills/functions/SKILL.md +0 -0
  33. {text2cypher-3.0.1 → text2cypher-3.0.2}/src/text2cypher/_skills/graph-algorithms/SKILL.md +0 -0
  34. {text2cypher-3.0.1 → text2cypher-3.0.2}/src/text2cypher/_skills/path-finding/SKILL.md +0 -0
  35. {text2cypher-3.0.1 → text2cypher-3.0.2}/src/text2cypher/_validation/__init__.py +0 -0
  36. {text2cypher-3.0.1 → text2cypher-3.0.2}/src/text2cypher/_validation/issues.py +0 -0
  37. {text2cypher-3.0.1 → text2cypher-3.0.2}/src/text2cypher/_validation/validator.py +0 -0
  38. {text2cypher-3.0.1 → text2cypher-3.0.2}/src/text2cypher/_workflow.py +0 -0
  39. {text2cypher-3.0.1 → text2cypher-3.0.2}/src/text2cypher/llm/__init__.py +0 -0
  40. {text2cypher-3.0.1 → text2cypher-3.0.2}/src/text2cypher/llm/_base.py +0 -0
  41. {text2cypher-3.0.1 → text2cypher-3.0.2}/src/text2cypher/llm/_chat_completions.py +0 -0
  42. {text2cypher-3.0.1 → text2cypher-3.0.2}/src/text2cypher/llm/_fake.py +0 -0
  43. {text2cypher-3.0.1 → text2cypher-3.0.2}/src/text2cypher/llm/_options.py +0 -0
  44. {text2cypher-3.0.1 → text2cypher-3.0.2}/src/text2cypher/py.typed +0 -0
  45. {text2cypher-3.0.1 → text2cypher-3.0.2}/src/text2cypher/schema/__init__.py +0 -0
  46. {text2cypher-3.0.1 → text2cypher-3.0.2}/src/text2cypher/schema/_dictionary.py +0 -0
  47. {text2cypher-3.0.1 → text2cypher-3.0.2}/src/text2cypher/schema/_filter.py +0 -0
  48. {text2cypher-3.0.1 → text2cypher-3.0.2}/src/text2cypher/schema/_from_snapshot.py +0 -0
  49. {text2cypher-3.0.1 → text2cypher-3.0.2}/src/text2cypher/schema/_model.py +0 -0
  50. {text2cypher-3.0.1 → text2cypher-3.0.2}/src/text2cypher/schema/_render.py +0 -0
  51. {text2cypher-3.0.1 → text2cypher-3.0.2}/src/text2cypher/schema/_stopwords.py +0 -0
  52. {text2cypher-3.0.1 → text2cypher-3.0.2}/src/text2cypher/skills.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: text2cypher
3
- Version: 3.0.1
3
+ Version: 3.0.2
4
4
  Summary: text2cypher: Generate validated Cypher queries from natural language text with LLMs
5
5
  Keywords: cypher,text2cypher,falkordb,llm,knowledge-graph,openCypher,graphdb
6
6
  Author: Kwaku Yeboah-Antwi
@@ -18,17 +18,19 @@ Classifier: Programming Language :: Python :: 3.13
18
18
  Classifier: Programming Language :: Python :: 3.14
19
19
  Classifier: Topic :: Database
20
20
  Classifier: Typing :: Typed
21
- Requires-Dist: cypher-guardrail>=1.6.0
21
+ Requires-Dist: cypher-guardrail>=1.7.0
22
22
  Requires-Dist: falkordb[hiredis]>=1.8.0
23
23
  Requires-Dist: openai>=3.31.0
24
24
  Requires-Dist: redis>=8.1.0
25
25
  Requires-Dist: snowballstemmer>=3.1.1
26
+ Requires-Dist: anthropic>=2.0.0 ; extra == 'anthropic'
26
27
  Requires-Python: >=3.12
27
28
  Project-URL: Homepage, https://github.com/Killeroid/text2cypher
28
29
  Project-URL: Documentation, https://text2cypher.readthedocs.io/en/stable/
29
30
  Project-URL: Changelog, https://github.com/Killeroid/text2cypher/blob/main/CHANGELOG.md
30
31
  Project-URL: Issues, https://github.com/Killeroid/text2cypher/issues
31
32
  Project-URL: Repository, https://github.com/Killeroid/text2cypher
33
+ Provides-Extra: anthropic
32
34
  Description-Content-Type: text/markdown
33
35
 
34
36
  # text2cypher
@@ -54,7 +56,7 @@ text2cypher asks an LLM to write the query, checks it against the real graph wit
54
56
  * **Skills** (optional): short guides to graph algorithms, path finding and the functions FalkorDB has, which the LLM reads with a tool only when a question needs them. Measured: they help a smaller model, and a stronger one gains little.
55
57
  * **Typos fixed without the LLM** (optional): a misspelled label, relationship type or property that is a likely typo of exactly one name in your graph is replaced and the query validated again, at no cost in LLM calls.
56
58
  * **Optional execution**: run the query read-only, with a timeout, and get the rows; a query that FalkorDB fails at run time is sent back to the LLM like any other problem.
57
- * **Bring your own LLM**: a small protocol, `chat` (the conversation as turns) or just `complete`, and the OpenAI SDK's own client accepted as it is, with the settings of how a model is asked (temperature, reasoning effort and others) as one dictionary. Async throughout.
59
+ * **Bring your own LLM**: a small protocol, `chat` (the conversation as turns) or just `complete`, and the OpenAI SDK's own client (or Anthropic's, with `text2cypher[anthropic]`) accepted as it is, with the settings of how a model is asked (temperature, reasoning effort and others) as one dictionary. Async throughout.
58
60
 
59
61
  ## Installation
60
62
 
@@ -64,7 +66,7 @@ Python 3.12 or later.
64
66
  uv add text2cypher # or: pip install text2cypher
65
67
  ```
66
68
 
67
- You need a FalkorDB graph that has data, reachable with the async client (`falkordb.asyncio`), and a model. The included client uses OpenAI's API and reads `OPENAI_API_KEY`.
69
+ You need a FalkorDB graph that has data, reachable with the async client (`falkordb.asyncio`), and a model. The included client uses OpenAI's API and reads `OPENAI_API_KEY`; Claude works the same way with `text2cypher[anthropic]` (see [LLM clients](https://text2cypher.readthedocs.io/en/latest/llm.html#claude-anthropic)).
68
70
 
69
71
  ## Quickstart
70
72
 
@@ -21,7 +21,7 @@ text2cypher asks an LLM to write the query, checks it against the real graph wit
21
21
  * **Skills** (optional): short guides to graph algorithms, path finding and the functions FalkorDB has, which the LLM reads with a tool only when a question needs them. Measured: they help a smaller model, and a stronger one gains little.
22
22
  * **Typos fixed without the LLM** (optional): a misspelled label, relationship type or property that is a likely typo of exactly one name in your graph is replaced and the query validated again, at no cost in LLM calls.
23
23
  * **Optional execution**: run the query read-only, with a timeout, and get the rows; a query that FalkorDB fails at run time is sent back to the LLM like any other problem.
24
- * **Bring your own LLM**: a small protocol, `chat` (the conversation as turns) or just `complete`, and the OpenAI SDK's own client accepted as it is, with the settings of how a model is asked (temperature, reasoning effort and others) as one dictionary. Async throughout.
24
+ * **Bring your own LLM**: a small protocol, `chat` (the conversation as turns) or just `complete`, and the OpenAI SDK's own client (or Anthropic's, with `text2cypher[anthropic]`) accepted as it is, with the settings of how a model is asked (temperature, reasoning effort and others) as one dictionary. Async throughout.
25
25
 
26
26
  ## Installation
27
27
 
@@ -31,7 +31,7 @@ Python 3.12 or later.
31
31
  uv add text2cypher # or: pip install text2cypher
32
32
  ```
33
33
 
34
- You need a FalkorDB graph that has data, reachable with the async client (`falkordb.asyncio`), and a model. The included client uses OpenAI's API and reads `OPENAI_API_KEY`.
34
+ You need a FalkorDB graph that has data, reachable with the async client (`falkordb.asyncio`), and a model. The included client uses OpenAI's API and reads `OPENAI_API_KEY`; Claude works the same way with `text2cypher[anthropic]` (see [LLM clients](https://text2cypher.readthedocs.io/en/latest/llm.html#claude-anthropic)).
35
35
 
36
36
  ## Quickstart
37
37
 
@@ -1,11 +1,11 @@
1
1
  [project]
2
2
  name = "text2cypher"
3
- version = "3.0.1"
3
+ version = "3.0.2"
4
4
  description = "text2cypher: Generate validated Cypher queries from natural language text with LLMs"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.12"
7
7
  dependencies = [
8
- "cypher-guardrail>=1.6.0",
8
+ "cypher-guardrail>=1.7.0",
9
9
  "falkordb[hiredis]>=1.8.0",
10
10
  "openai>=3.31.0",
11
11
  "redis>=8.1.0",
@@ -49,6 +49,9 @@ Changelog = "https://github.com/Killeroid/text2cypher/blob/main/CHANGELOG.md"
49
49
  Issues = "https://github.com/Killeroid/text2cypher/issues"
50
50
  Repository = "https://github.com/Killeroid/text2cypher"
51
51
 
52
+ [project.optional-dependencies]
53
+ anthropic = ["anthropic>=2.0.0"]
54
+
52
55
  [build-system]
53
56
  requires = ["uv_build>=0.13.1,<0.14.0"]
54
57
  build-backend = "uv_build"
@@ -135,6 +138,7 @@ python = ".venv"
135
138
 
136
139
  [dependency-groups]
137
140
  dev = [
141
+ "anthropic>=2.0.0",
138
142
  "anyio>=4.15.1",
139
143
  "coverage>=7.16.2",
140
144
  "falkordblite; python_version >= '3.12'",
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "text2cypher"
3
- version = "3.0.1"
3
+ version = "3.0.2"
4
4
  description = "text2cypher: Generate validated Cypher queries from natural language text with LLMs"
5
5
  readme = "README.md"
6
6
  authors = [
@@ -8,7 +8,7 @@ authors = [
8
8
  ]
9
9
  requires-python = ">=3.12"
10
10
  dependencies = [
11
- "cypher-guardrail>=1.6.0",
11
+ "cypher-guardrail>=1.7.0",
12
12
  "falkordb[hiredis]>=1.8.0",
13
13
  "openai>=3.31.0",
14
14
  "redis>=8.1.0",
@@ -40,6 +40,7 @@ module-name = "text2cypher"
40
40
 
41
41
  [dependency-groups]
42
42
  dev = [
43
+ "anthropic>=2.0.0",
43
44
  "anyio>=4.15.1",
44
45
  "coverage>=7.16.2",
45
46
  "falkordblite; python_version >= '3.12'",
@@ -116,3 +117,8 @@ Documentation = "https://text2cypher.readthedocs.io/en/stable/"
116
117
  Changelog = "https://github.com/Killeroid/text2cypher/blob/main/CHANGELOG.md"
117
118
  Issues = "https://github.com/Killeroid/text2cypher/issues"
118
119
  Repository = "https://github.com/Killeroid/text2cypher"
120
+
121
+ [project.optional-dependencies]
122
+ anthropic = [
123
+ "anthropic>=2.0.0",
124
+ ]
@@ -17,7 +17,7 @@ from text2cypher.llm import (
17
17
  ModelOptions,
18
18
  Usage,
19
19
  )
20
- from text2cypher.llm._adapt import as_client
20
+ from text2cypher.llm._adapt import as_client, is_async_anthropic
21
21
  from text2cypher.llm._options import checked_options
22
22
  from text2cypher.schema import (
23
23
  GraphSchema,
@@ -28,7 +28,10 @@ from text2cypher.schema._model import quote_identifier
28
28
  from text2cypher.schema._render import as_markdown, data_dictionary_section
29
29
 
30
30
  if TYPE_CHECKING:
31
+ from anthropic import AsyncAnthropic
32
+
31
33
  from text2cypher.llm._chat_completions import ChatCompletionsAdapter
34
+ from text2cypher.llm._messages import MessagesAdapter
32
35
 
33
36
  _SYSTEM = """\
34
37
  # Role
@@ -122,30 +125,30 @@ class LLMSchemaFilter:
122
125
 
123
126
  Attributes:
124
127
  llm: The client to ask, perhaps a cheaper one than the main model. It may be an
125
- ``openai.AsyncOpenAI`` if ``model`` says which model. ``None`` takes the client
128
+ ``openai.AsyncOpenAI`` or ``anthropic.AsyncAnthropic`` if ``model`` says which model. ``None`` takes the client
126
129
  of the ``Text2Cypher`` it is given to.
127
130
  min_entities: Labels plus relationship types below which no model is asked; ``0``
128
131
  always asks.
129
- model: With an ``AsyncOpenAI`` as ``llm``, the model to ask. With ``llm=None``, a
130
- model to ask on the main client instead of the main model: the same SDK client
131
- and settings, for example a cheaper model (it needs an OpenAI client as the main
132
- one).
132
+ model: With an ``AsyncOpenAI`` or ``AsyncAnthropic`` as ``llm``, the model to ask. With
133
+ ``llm=None``, a model to ask on the main client instead of the main model: the same
134
+ SDK client and settings, for example a cheaper model (it needs a client made from an
135
+ OpenAI or Anthropic SDK client as the main one).
133
136
  model_options: How to ask ``model``; see ``ModelOptions``. The model starts with no
134
137
  ``temperature`` (the server's own, which every model accepts, so the choice is not
135
138
  repeatable: ``{"temperature": 0}`` makes it so), no ``reasoning_effort`` and no
136
139
  ``extra``, whatever the main client has, because they depend on the model. With
137
140
  ``llm=None`` it keeps the main client's connection settings (``timeout``,
138
- ``max_retries``, ``system_role`` and ``tools``); with an ``AsyncOpenAI`` as ``llm``,
139
- any other setting left out takes the default of the adapter for an ``AsyncOpenAI``. It needs
140
- ``model``, and it is an error with a client of the filter's own that is not an
141
- ``AsyncOpenAI``.
141
+ ``max_retries``, ``system_role`` and ``tools``); with an ``AsyncOpenAI`` or
142
+ ``AsyncAnthropic`` as ``llm``, any other setting left out takes the default of its
143
+ adapter. It needs ``model``, and it is an error with a client of the filter's own
144
+ that is neither.
142
145
  property_descriptions: With a data dictionary on the schema, whether the model is
143
146
  shown what the properties mean as well as the labels and relationship types
144
147
  (always shown). ``False`` keeps the prompt short; ``True`` helps a question that
145
148
  names a thing only by what a property holds.
146
149
  """
147
150
 
148
- llm: AsyncChatClient | AsyncLLMClient | AsyncOpenAI | None = None
151
+ llm: "AsyncChatClient | AsyncLLMClient | AsyncOpenAI | AsyncAnthropic | None" = None
149
152
  min_entities: int = field(default=20, kw_only=True)
150
153
  model: str | None = field(default=None, kw_only=True)
151
154
  model_options: ModelOptions | None = field(
@@ -162,7 +165,7 @@ class LLMSchemaFilter:
162
165
  checked_options(self.model_options)
163
166
  if self.llm is not None:
164
167
  options = self.model_options
165
- if isinstance(self.llm, AsyncOpenAI):
168
+ if isinstance(self.llm, AsyncOpenAI) or is_async_anthropic(self.llm):
166
169
  options = cast("ModelOptions", {**_MODEL_START, **(options or {})})
167
170
  object.__setattr__(self, "llm", as_client(self.llm, self.model, options))
168
171
 
@@ -182,11 +185,12 @@ class LLMSchemaFilter:
182
185
  if not hasattr(llm, "with_model"):
183
186
  raise ValueError(
184
187
  "LLMSchemaFilter(model=...) asks the main client with another model, "
185
- "which needs an OpenAI client as the main one: give the filter its own llm"
188
+ "which needs a client made from an OpenAI or Anthropic SDK client as the main "
189
+ "one: give the filter its own llm"
186
190
  )
187
191
  return replace(
188
192
  self,
189
- llm=cast("ChatCompletionsAdapter", llm).with_model(
193
+ llm=cast("ChatCompletionsAdapter | MessagesAdapter", llm).with_model(
190
194
  self.model, {**_MODEL_START, **(self.model_options or {})}
191
195
  ),
192
196
  model=None,
@@ -2,9 +2,9 @@
2
2
 
3
3
  from collections.abc import Awaitable, Callable, Sequence
4
4
  from dataclasses import replace
5
+ from typing import TYPE_CHECKING
5
6
 
6
7
  from falkordb.asyncio import FalkorDB
7
- from openai import AsyncOpenAI
8
8
 
9
9
  from text2cypher._config import Config
10
10
  from text2cypher._generation import AsyncSchemaFilter, LLMSchemaFilter
@@ -18,6 +18,10 @@ from text2cypher.llm._adapt import as_client
18
18
  from text2cypher.llm._base import supports_tools
19
19
  from text2cypher.schema import DataDictionary, SchemaFilter, filter_schema
20
20
 
21
+ if TYPE_CHECKING:
22
+ from anthropic import AsyncAnthropic
23
+ from openai import AsyncOpenAI
24
+
21
25
 
22
26
  class Text2Cypher:
23
27
  """Turns a question into a query that passes validation against a FalkorDB graph.
@@ -25,15 +29,16 @@ class Text2Cypher:
25
29
  Args:
26
30
  client: A ``falkordb.asyncio`` client. It is bound to one event loop, so use
27
31
  one ``Text2Cypher`` per loop.
28
- llm: The model that writes and corrects the queries: an ``openai.AsyncOpenAI`` (with
29
- ``model``), or a client of your own. A client with ``chat``
32
+ llm: The model that writes and corrects the queries: an ``openai.AsyncOpenAI`` or an
33
+ ``anthropic.AsyncAnthropic`` (with ``model``), or a client of your own. A client with ``chat``
30
34
  is given each correction as the turns of a conversation; one with only
31
35
  ``complete``, as one message.
32
- model: The model to ask, when ``llm`` is an ``openai.AsyncOpenAI``, which has none
33
- of its own. Any other kind of ``llm`` chooses its own model, and ``model`` with
34
- one is an error.
35
- model_options: How to ask ``model``, for an ``openai.AsyncOpenAI``: the
36
- ``temperature``, ``reasoning_effort``, ``timeout`` and other settings of
36
+ model: The model to ask, when ``llm`` is an ``openai.AsyncOpenAI`` or an
37
+ ``anthropic.AsyncAnthropic``, which have none of their own. Any other kind of
38
+ ``llm`` chooses its own model, and ``model`` with one is an error.
39
+ model_options: How to ask ``model``, for an ``openai.AsyncOpenAI`` or an
40
+ ``anthropic.AsyncAnthropic``: the ``temperature`` (not for Anthropic, whose models
41
+ take none), ``reasoning_effort``, ``timeout`` and other settings of
37
42
  ``ModelOptions``; a setting left out takes the default. Any
38
43
  other kind of ``llm`` has its own settings, and ``model_options`` with one is an
39
44
  error.
@@ -64,7 +69,7 @@ class Text2Cypher:
64
69
  def __init__(
65
70
  self,
66
71
  client: FalkorDB,
67
- llm: AsyncChatClient | AsyncLLMClient | AsyncOpenAI,
72
+ llm: "AsyncChatClient | AsyncLLMClient | AsyncOpenAI | AsyncAnthropic",
68
73
  *,
69
74
  model: str | None = None,
70
75
  model_options: ModelOptions | None = None,
@@ -0,0 +1,73 @@
1
+ """Accept the SDK's own client wherever an LLM is accepted."""
2
+
3
+ import sys
4
+ from typing import TYPE_CHECKING, cast
5
+
6
+ from openai import AsyncOpenAI, OpenAI
7
+
8
+ from text2cypher.llm._base import AsyncChatClient, AsyncLLMClient
9
+ from text2cypher.llm._chat_completions import ChatCompletionsAdapter
10
+ from text2cypher.llm._options import ModelOptions
11
+
12
+ if TYPE_CHECKING:
13
+ from anthropic import AsyncAnthropic
14
+
15
+ type LLM = AsyncChatClient | AsyncLLMClient | AsyncOpenAI | AsyncAnthropic
16
+
17
+
18
+ def is_async_anthropic(llm: object) -> bool:
19
+ """Whether ``llm`` is an ``anthropic.AsyncAnthropic``, without importing ``anthropic``:
20
+ one that exists has already imported it, and an install without it has none."""
21
+ module = sys.modules.get("anthropic")
22
+ return module is not None and isinstance(llm, module.AsyncAnthropic)
23
+
24
+
25
+ def as_client(
26
+ llm: LLM,
27
+ model: str | None = None,
28
+ model_options: ModelOptions | None = None,
29
+ ) -> AsyncChatClient | AsyncLLMClient:
30
+ """``llm`` as a client the library can ask.
31
+
32
+ An ``openai.AsyncOpenAI`` (also ``AsyncAzureOpenAI``, and one made for a compatible
33
+ server with ``base_url``) becomes a ``ChatCompletionsAdapter`` for ``model``, with
34
+ ``model_options`` or else that class's defaults; an ``anthropic.AsyncAnthropic``
35
+ becomes a ``MessagesAdapter`` the same way. Any other client is returned as it is.
36
+
37
+ Raises:
38
+ ValueError: If an ``AsyncOpenAI`` or ``AsyncAnthropic`` is given with no ``model``
39
+ (it has none of its own), or ``model`` or ``model_options`` is given with a
40
+ client that is not one.
41
+ TypeError: If ``llm`` is the synchronous ``openai.OpenAI``: the library is async.
42
+ """
43
+ if isinstance(llm, AsyncOpenAI):
44
+ if model is None:
45
+ raise ValueError(
46
+ "An openai.AsyncOpenAI has no model of its own: pass model='...'"
47
+ )
48
+ return ChatCompletionsAdapter(model, client=llm, model_options=model_options)
49
+ if is_async_anthropic(llm):
50
+ from text2cypher.llm._messages import MessagesAdapter
51
+
52
+ if model is None:
53
+ raise ValueError(
54
+ "An anthropic.AsyncAnthropic has no model of its own: pass model='...'"
55
+ )
56
+ return MessagesAdapter(
57
+ model, client=cast("AsyncAnthropic", llm), model_options=model_options
58
+ )
59
+ if isinstance(llm, OpenAI):
60
+ raise TypeError(
61
+ "text2cypher is async: pass an openai.AsyncOpenAI, not an openai.OpenAI"
62
+ )
63
+ if model is not None:
64
+ raise ValueError(
65
+ "model= is for an openai.AsyncOpenAI or anthropic.AsyncAnthropic; any other "
66
+ "client chooses its own model"
67
+ )
68
+ if model_options is not None:
69
+ raise ValueError(
70
+ "model_options is for an openai.AsyncOpenAI or anthropic.AsyncAnthropic; "
71
+ "any other client has its own settings, which it is given when it is made"
72
+ )
73
+ return cast("AsyncChatClient | AsyncLLMClient", llm)
@@ -0,0 +1,251 @@
1
+ """The adapter that gives the library's chat protocol over the Anthropic SDK's Messages API."""
2
+
3
+ import copy
4
+ from collections import OrderedDict
5
+ from collections.abc import Sequence
6
+ from typing import Any, Literal
7
+
8
+ from anthropic import NOT_GIVEN, AsyncAnthropic, omit
9
+ from anthropic.types import Message as AnthropicMessage
10
+
11
+ from text2cypher.llm._base import Completion, Message, Tool, ToolCall, Usage
12
+ from text2cypher.llm._options import DEFAULTS, ModelOptions, checked_options
13
+
14
+ # The model's thinking counts toward it, so it is not small: the API requires a value
15
+ _MAX_TOKENS = 16000
16
+ # What the API takes from the client, so ``extra`` may not set it (``max_tokens`` it may)
17
+ _RESERVED = frozenset({"system", "top_p", "top_k"})
18
+ # How many replies that asked for tools are remembered (see ``_remember``)
19
+ _REMEMBERED = 256
20
+
21
+ _FINISH_REASONS = {
22
+ "end_turn": "stop",
23
+ "stop_sequence": "stop",
24
+ "max_tokens": "length",
25
+ "model_context_window_exceeded": "length",
26
+ "tool_use": "tool_calls",
27
+ "refusal": "refusal",
28
+ }
29
+
30
+
31
+ class MessagesAdapter:
32
+ """Asks a model through the SDK's Messages API: a system prompt and the turns of the conversation.
33
+
34
+ It is what an ``anthropic.AsyncAnthropic`` given to ``Text2Cypher`` or ``LLMSchemaFilter``
35
+ (with ``model=``) becomes; it is not part of the public API.
36
+
37
+ The models take no ``temperature``, ``top_p`` or ``top_k`` (the API refuses any value, or
38
+ any but the default, depending on its version), so none is ever sent and a ``temperature``
39
+ in ``model_options`` is an error: a reply cannot be made repeatable.
40
+
41
+ Thinking is on by default and cannot be turned off on every model. A reply that asks for
42
+ tools has thinking blocks, which the API requires back unchanged with the tool results, so
43
+ the adapter keeps the content blocks of such a reply and sends them back. A reply that
44
+ asks for nothing is sent back as its text alone, which the API allows.
45
+
46
+ Args:
47
+ model: The model to ask. There is no default: the right one depends on the
48
+ account and on the schema being prompted.
49
+ client: The ``AsyncAnthropic`` to use. By default one is made from the environment.
50
+ model_options: How to ask it: ``reasoning_effort`` (sent as ``output_config.effort``),
51
+ ``timeout``, ``max_retries``, ``tools`` and ``extra`` of ``ModelOptions``;
52
+ ``extra`` may set ``max_tokens`` (default 16000). ``system_role`` has no effect: the
53
+ system prompt is always its own field.
54
+ """
55
+
56
+ def __init__(
57
+ self,
58
+ model: str,
59
+ *,
60
+ client: AsyncAnthropic | None = None,
61
+ model_options: ModelOptions | None = None,
62
+ ) -> None:
63
+ self._model = model
64
+ self._sdk = client or AsyncAnthropic()
65
+ self._options: ModelOptions = _checked(
66
+ {**DEFAULTS, "temperature": None, **checked_options(model_options)}
67
+ )
68
+ # The blocks of replies that asked for tools, by the id of their first tool call
69
+ self._remembered: OrderedDict[str, list[Any]] = OrderedDict()
70
+ self._apply()
71
+
72
+ def _apply(self) -> None:
73
+ options = self._options
74
+ timeout, retries = options["timeout"], options["max_retries"]
75
+ # The copy shares the connection pool of the client it is made from
76
+ self._client = self._sdk.with_options(
77
+ timeout=NOT_GIVEN if timeout is None else timeout,
78
+ max_retries=NOT_GIVEN if retries is None else retries,
79
+ )
80
+ self.supports_tools = options["tools"]
81
+
82
+ def with_model(
83
+ self, model: str, model_options: ModelOptions | None = None
84
+ ) -> "MessagesAdapter":
85
+ """A client that asks ``model`` instead, with the same SDK client and every setting
86
+ but the ones in ``model_options``, for example a cheaper model for a part of the work.
87
+
88
+ A model that thinks differently may need other settings: a key you leave out is
89
+ kept, and ``None`` takes a setting away (``{"reasoning_effort": None}``).
90
+
91
+ Raises:
92
+ ValueError: If ``model_options`` has an unknown key, a ``temperature``, or an
93
+ ``extra`` that sets a field the client sets itself.
94
+ """
95
+ other = copy.copy(self)
96
+ other._model = model
97
+ other._options = _checked({**self._options, **checked_options(model_options)})
98
+ # Thinking blocks belong to the model that wrote them
99
+ other._remembered = OrderedDict()
100
+ other._apply()
101
+ return other
102
+
103
+ async def complete(self, system: str, user: str) -> Completion:
104
+ """Ask the model with one user message; see ``chat``."""
105
+ return await self.chat(system, [Message("user", user)])
106
+
107
+ async def chat(
108
+ self,
109
+ system: str,
110
+ messages: Sequence[Message],
111
+ tools: Sequence[Tool] | None = None,
112
+ *,
113
+ tool_choice: Literal["auto", "none"] = "auto",
114
+ ) -> Completion:
115
+ """Ask the model, and return its reply, the tool calls it made, and the tokens used.
116
+
117
+ ``tools`` are offered with their parameters as the input schema. The answers to a
118
+ reply's tool calls are sent as the results of one user message.
119
+ """
120
+ extra = dict(self._options["extra"] or {})
121
+ max_tokens = extra.pop("max_tokens", _MAX_TOKENS)
122
+ effort = self._options["reasoning_effort"]
123
+ offered: Any = [_tool_param(tool) for tool in tools or ()] or omit
124
+ choice: Any = {"type": tool_choice} if tools else omit
125
+ output: Any = {"effort": effort} if effort is not None else omit
126
+ response = await self._client.messages.create(
127
+ model=self._model,
128
+ max_tokens=max_tokens,
129
+ system=system,
130
+ messages=self._messages(messages),
131
+ tools=offered,
132
+ tool_choice=choice,
133
+ output_config=output,
134
+ extra_body=extra or None,
135
+ )
136
+ return self._completion(response)
137
+
138
+ def _completion(self, response: AnthropicMessage) -> Completion:
139
+ text = "".join(block.text for block in response.content if block.type == "text")
140
+ calls = tuple(
141
+ ToolCall(block.id, block.name, _input(block.input))
142
+ for block in response.content
143
+ if block.type == "tool_use"
144
+ )
145
+ if calls:
146
+ self._remember(calls[0].id, list(response.content))
147
+ used = response.usage
148
+ reason = response.stop_reason
149
+ return Completion(
150
+ text=text,
151
+ usage=Usage(
152
+ used.input_tokens
153
+ + (used.cache_creation_input_tokens or 0)
154
+ + (used.cache_read_input_tokens or 0),
155
+ used.output_tokens,
156
+ ),
157
+ tool_calls=calls,
158
+ finish_reason=None
159
+ if reason is None
160
+ else _FINISH_REASONS.get(reason, reason),
161
+ )
162
+
163
+ def _remember(self, call_id: str, blocks: list[Any]) -> None:
164
+ """Keep a reply's blocks, thinking included, for when its tool calls come back.
165
+
166
+ A run of the library asks a handful of times, so the oldest are forgotten.
167
+ """
168
+ self._remembered[call_id] = blocks
169
+ while len(self._remembered) > _REMEMBERED:
170
+ self._remembered.popitem(last=False)
171
+
172
+ def _messages(self, turns: Sequence[Message]) -> list[Any]:
173
+ params: list[Any] = []
174
+ for turn in turns:
175
+ if turn.role == "tool":
176
+ block = {
177
+ "type": "tool_result",
178
+ "tool_use_id": turn.tool_call_id or "",
179
+ "content": turn.content,
180
+ }
181
+ # Every answer to one reply's calls goes in the one user message
182
+ if (
183
+ params
184
+ and params[-1]["role"] == "user"
185
+ and _only_results(params[-1])
186
+ ):
187
+ params[-1]["content"].append(block)
188
+ else:
189
+ params.append({"role": "user", "content": [block]})
190
+ elif turn.role == "assistant" and turn.tool_calls:
191
+ kept = self._remembered.get(turn.tool_calls[0].id)
192
+ params.append(
193
+ {
194
+ "role": "assistant",
195
+ "content": kept
196
+ if kept is not None
197
+ else _blocks(turn.content, turn.tool_calls),
198
+ }
199
+ )
200
+ else:
201
+ params.append({"role": turn.role, "content": turn.content})
202
+ return params
203
+
204
+
205
+ def _checked(options: ModelOptions) -> ModelOptions:
206
+ if options.get("temperature") is not None:
207
+ raise ValueError(
208
+ "temperature cannot be set for an anthropic.AsyncAnthropic: the models take no "
209
+ "temperature (the API refuses it), so a reply cannot be made repeatable"
210
+ )
211
+ taken = _RESERVED.intersection(options.get("extra") or ())
212
+ if taken:
213
+ raise ValueError(
214
+ f"extra cannot set {', '.join(sorted(taken))}: the client sets it, "
215
+ "or the models take none"
216
+ )
217
+ return options
218
+
219
+
220
+ def _only_results(params: dict[str, Any]) -> bool:
221
+ content = params["content"]
222
+ return isinstance(content, list) and all(
223
+ block["type"] == "tool_result" for block in content
224
+ )
225
+
226
+
227
+ def _blocks(text: str, calls: Sequence[ToolCall]) -> list[dict[str, Any]]:
228
+ """The blocks of a reply that asked for tools, when what it said is not remembered."""
229
+ blocks: list[dict[str, Any]] = [{"type": "text", "text": text}] if text else []
230
+ blocks.extend(
231
+ {
232
+ "type": "tool_use",
233
+ "id": call.id,
234
+ "name": call.name,
235
+ "input": dict(call.arguments),
236
+ }
237
+ for call in calls
238
+ )
239
+ return blocks
240
+
241
+
242
+ def _tool_param(tool: Tool) -> dict[str, Any]:
243
+ return {
244
+ "name": tool.name,
245
+ "description": tool.description,
246
+ "input_schema": dict(tool.parameters),
247
+ }
248
+
249
+
250
+ def _input(value: object) -> dict[str, Any]:
251
+ return dict(value) if isinstance(value, dict) else {}
@@ -1,47 +0,0 @@
1
- """Accept the SDK's own client wherever an LLM is accepted."""
2
-
3
- from openai import AsyncOpenAI, OpenAI
4
-
5
- from text2cypher.llm._base import AsyncChatClient, AsyncLLMClient
6
- from text2cypher.llm._chat_completions import ChatCompletionsAdapter
7
- from text2cypher.llm._options import ModelOptions
8
-
9
- type LLM = AsyncChatClient | AsyncLLMClient | AsyncOpenAI
10
-
11
-
12
- def as_client(
13
- llm: LLM,
14
- model: str | None = None,
15
- model_options: ModelOptions | None = None,
16
- ) -> AsyncChatClient | AsyncLLMClient:
17
- """``llm`` as a client the library can ask.
18
-
19
- An ``openai.AsyncOpenAI`` (also ``AsyncAzureOpenAI``, and one made for a compatible
20
- server with ``base_url``) becomes a ``ChatCompletionsAdapter`` for ``model``, with
21
- ``model_options`` or else that class's defaults. Any other client is returned as it is.
22
-
23
- Raises:
24
- ValueError: If an ``AsyncOpenAI`` is given with no ``model`` (it has none of its
25
- own), or ``model`` or ``model_options`` is given with a client that is not one.
26
- TypeError: If ``llm`` is the synchronous ``openai.OpenAI``: the library is async.
27
- """
28
- if isinstance(llm, AsyncOpenAI):
29
- if model is None:
30
- raise ValueError(
31
- "An openai.AsyncOpenAI has no model of its own: pass model='...'"
32
- )
33
- return ChatCompletionsAdapter(model, client=llm, model_options=model_options)
34
- if isinstance(llm, OpenAI):
35
- raise TypeError(
36
- "text2cypher is async: pass an openai.AsyncOpenAI, not an openai.OpenAI"
37
- )
38
- if model is not None:
39
- raise ValueError(
40
- "model= is for an openai.AsyncOpenAI; any other client chooses its own model"
41
- )
42
- if model_options is not None:
43
- raise ValueError(
44
- "model_options is for an openai.AsyncOpenAI; any other client has its own "
45
- "settings, which it is given when it is made"
46
- )
47
- return llm
File without changes