polars-llm 0.1.0__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.
- polars_llm-0.1.0/LICENSE +21 -0
- polars_llm-0.1.0/PKG-INFO +255 -0
- polars_llm-0.1.0/README.md +218 -0
- polars_llm-0.1.0/polars_llm/__init__.py +3 -0
- polars_llm-0.1.0/polars_llm/_runtime.py +463 -0
- polars_llm-0.1.0/polars_llm/llm.py +500 -0
- polars_llm-0.1.0/polars_llm.egg-info/PKG-INFO +255 -0
- polars_llm-0.1.0/polars_llm.egg-info/SOURCES.txt +12 -0
- polars_llm-0.1.0/polars_llm.egg-info/dependency_links.txt +1 -0
- polars_llm-0.1.0/polars_llm.egg-info/requires.txt +17 -0
- polars_llm-0.1.0/polars_llm.egg-info/top_level.txt +1 -0
- polars_llm-0.1.0/pyproject.toml +158 -0
- polars_llm-0.1.0/setup.cfg +4 -0
- polars_llm-0.1.0/tests/test_llm.py +501 -0
polars_llm-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Diego Garcia Lozano
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: polars-llm
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Call LLMs and embedding models from a Polars DataFrame, one row at a time, using native Polars expressions. Powered by LangChain.
|
|
5
|
+
Author-email: Diego Garcia Lozano <diegoglozano96@gmail.com>
|
|
6
|
+
Project-URL: Homepage, https://diegoglozano.github.io/polars-ai/
|
|
7
|
+
Project-URL: Repository, https://github.com/diegoglozano/polars-ai
|
|
8
|
+
Project-URL: Documentation, https://diegoglozano.github.io/polars-ai/
|
|
9
|
+
Keywords: polars,polars-llm,polars-ai,langchain,llm,openai,anthropic,gemini,embeddings,dataframe,etl,python
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Programming Language :: Python
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
19
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
20
|
+
Requires-Python: <4.0,>=3.9
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
License-File: LICENSE
|
|
23
|
+
Requires-Dist: polars>=1.0.0
|
|
24
|
+
Requires-Dist: langchain-core>=0.3.0
|
|
25
|
+
Requires-Dist: nest-asyncio>=1.6.0
|
|
26
|
+
Provides-Extra: openai
|
|
27
|
+
Requires-Dist: langchain-openai>=0.2.0; extra == "openai"
|
|
28
|
+
Provides-Extra: anthropic
|
|
29
|
+
Requires-Dist: langchain-anthropic>=0.2.0; extra == "anthropic"
|
|
30
|
+
Provides-Extra: gemini
|
|
31
|
+
Requires-Dist: langchain-google-genai>=2.0.0; extra == "gemini"
|
|
32
|
+
Provides-Extra: all
|
|
33
|
+
Requires-Dist: langchain-openai>=0.2.0; extra == "all"
|
|
34
|
+
Requires-Dist: langchain-anthropic>=0.2.0; extra == "all"
|
|
35
|
+
Requires-Dist: langchain-google-genai>=2.0.0; extra == "all"
|
|
36
|
+
Dynamic: license-file
|
|
37
|
+
|
|
38
|
+
# polars-llm
|
|
39
|
+
|
|
40
|
+
[](https://pypi.org/project/polars-llm/)
|
|
41
|
+
[](https://pypi.org/project/polars-llm/)
|
|
42
|
+
[](https://github.com/diegoglozano/polars-ai/actions/workflows/main.yml?query=branch%3Amain)
|
|
43
|
+
[](https://codecov.io/gh/diegoglozano/polars-ai)
|
|
44
|
+
[](https://github.com/diegoglozano/polars-ai/blob/main/LICENSE)
|
|
45
|
+
|
|
46
|
+
**Call OpenAI, Anthropic, and Gemini models from a [Polars](https://pola.rs) DataFrame, one row at a time, using native Polars expressions.**
|
|
47
|
+
|
|
48
|
+
`polars-llm` registers an `.llm` namespace on Polars expressions so you can call any [LangChain](https://python.langchain.com/)-supported chat model or embedding model on every row of a DataFrame — synchronously or asynchronously — and pipe the responses straight back into your data pipeline.
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
import polars as pl
|
|
52
|
+
import polars_llm # noqa: F401 — registers the `.llm` namespace
|
|
53
|
+
|
|
54
|
+
(
|
|
55
|
+
pl.DataFrame({"user_prompt": ["Summarise polars in one sentence."]})
|
|
56
|
+
.with_columns(
|
|
57
|
+
pl.col("user_prompt").llm.openai(model="gpt-4o-mini").alias("answer")
|
|
58
|
+
)
|
|
59
|
+
)
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
- **Repository**: <https://github.com/diegoglozano/polars-ai>
|
|
63
|
+
- **Documentation**: <https://diegoglozano.github.io/polars-ai/>
|
|
64
|
+
- **PyPI**: <https://pypi.org/project/polars-llm/>
|
|
65
|
+
|
|
66
|
+
---
|
|
67
|
+
|
|
68
|
+
## Why polars-llm?
|
|
69
|
+
|
|
70
|
+
- **Expression-native** — works inside `with_columns`, `select`, and any other Polars expression context. No Python `for` loops over rows, no notebook glue.
|
|
71
|
+
- **Sync and async** — every provider verb has an `a`-prefixed async sibling that fans out concurrently with `asyncio.gather` and an optional `max_concurrency` cap.
|
|
72
|
+
- **Per-row prompts and system messages** — both the prompt and the system message can be Polars expressions, so you can build them from other columns.
|
|
73
|
+
- **Structured outputs** — pass a Pydantic model as `schema=` to get a struct column back, parsed via LangChain's `with_structured_output`.
|
|
74
|
+
- **Embeddings, too** — `openai_embed` and `gemini_embed` return `List[Float64]` columns ready for vector search.
|
|
75
|
+
- **Powered by [LangChain](https://python.langchain.com/)** — you get the same retries, batching, and observability primitives the rest of the LangChain ecosystem uses, plumbed straight into a DataFrame.
|
|
76
|
+
|
|
77
|
+
Common use cases:
|
|
78
|
+
|
|
79
|
+
- Summarise, classify, translate, or extract structured fields from a column of text.
|
|
80
|
+
- Score rows against a custom rubric using an LLM-as-judge.
|
|
81
|
+
- Build embeddings for a corpus directly from a DataFrame, ready to write to a vector database.
|
|
82
|
+
- Mix LLM calls with the rest of your pipeline (joins, filters, group-bys) without leaving Polars.
|
|
83
|
+
|
|
84
|
+
## Installation
|
|
85
|
+
|
|
86
|
+
`polars-llm` keeps its base install light. Pick the providers you need as extras:
|
|
87
|
+
|
|
88
|
+
```sh
|
|
89
|
+
# Just one provider
|
|
90
|
+
pip install "polars-llm[openai]"
|
|
91
|
+
pip install "polars-llm[anthropic]"
|
|
92
|
+
pip install "polars-llm[gemini]"
|
|
93
|
+
|
|
94
|
+
# Or all of them
|
|
95
|
+
pip install "polars-llm[all]"
|
|
96
|
+
|
|
97
|
+
# uv
|
|
98
|
+
uv add "polars-llm[all]"
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
Requires Python 3.9+ and Polars 1.0+.
|
|
102
|
+
|
|
103
|
+
Authentication follows LangChain conventions — set `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, or `GOOGLE_API_KEY` in your environment before importing.
|
|
104
|
+
|
|
105
|
+
## Quickstart
|
|
106
|
+
|
|
107
|
+
### 1. Chat completion per row
|
|
108
|
+
|
|
109
|
+
```python
|
|
110
|
+
import polars as pl
|
|
111
|
+
import polars_llm # noqa: F401
|
|
112
|
+
|
|
113
|
+
df = (
|
|
114
|
+
pl.DataFrame({"user_prompt": [
|
|
115
|
+
"What is the capital of Spain?",
|
|
116
|
+
"What is the capital of France?",
|
|
117
|
+
]})
|
|
118
|
+
.with_columns(
|
|
119
|
+
pl.col("user_prompt").llm.openai(model="gpt-4o-mini").alias("answer")
|
|
120
|
+
)
|
|
121
|
+
)
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
### 2. System prompt — literal or per-row
|
|
125
|
+
|
|
126
|
+
```python
|
|
127
|
+
# Same system prompt for every row
|
|
128
|
+
pl.col("user_prompt").llm.anthropic(
|
|
129
|
+
model="claude-sonnet-4-6",
|
|
130
|
+
system="Answer in fewer than 10 words.",
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
# Per-row system prompt from another column
|
|
134
|
+
pl.col("user_prompt").llm.gemini(
|
|
135
|
+
model="gemini-2.5-pro",
|
|
136
|
+
system=pl.col("system_prompt"),
|
|
137
|
+
)
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
### 3. Async for throughput
|
|
141
|
+
|
|
142
|
+
The `a`-prefixed verbs run concurrently across the batch, capped at `max_concurrency`:
|
|
143
|
+
|
|
144
|
+
```python
|
|
145
|
+
df.with_columns(
|
|
146
|
+
pl.col("user_prompt").llm.aopenai(
|
|
147
|
+
model="gpt-4o-mini",
|
|
148
|
+
max_concurrency=20,
|
|
149
|
+
).alias("answer")
|
|
150
|
+
)
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
### 4. Structured output with Pydantic
|
|
154
|
+
|
|
155
|
+
```python
|
|
156
|
+
from pydantic import BaseModel
|
|
157
|
+
|
|
158
|
+
class Sentiment(BaseModel):
|
|
159
|
+
label: str # "positive" | "neutral" | "negative"
|
|
160
|
+
confidence: float
|
|
161
|
+
|
|
162
|
+
df.with_columns(
|
|
163
|
+
pl.col("review").llm.openai(
|
|
164
|
+
model="gpt-4o-mini",
|
|
165
|
+
schema=Sentiment,
|
|
166
|
+
).alias("sentiment")
|
|
167
|
+
).unnest("sentiment")
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
### 5. Embeddings
|
|
171
|
+
|
|
172
|
+
```python
|
|
173
|
+
df.with_columns(
|
|
174
|
+
pl.col("text").llm.openai_embed(
|
|
175
|
+
model="text-embedding-3-small",
|
|
176
|
+
).alias("vector")
|
|
177
|
+
)
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
### 6. Retries, caching, metadata
|
|
181
|
+
|
|
182
|
+
```python
|
|
183
|
+
pl.col("user_prompt").llm.aanthropic(
|
|
184
|
+
model="claude-sonnet-4-6",
|
|
185
|
+
retries=3,
|
|
186
|
+
backoff=0.5,
|
|
187
|
+
max_concurrency=10,
|
|
188
|
+
cache=True, # dedupe identical prompts within a batch
|
|
189
|
+
with_metadata=True, # struct {content, elapsed_ms, error}
|
|
190
|
+
)
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
## API reference
|
|
194
|
+
|
|
195
|
+
All methods live under the `.llm` namespace on any Polars expression that resolves to a string column.
|
|
196
|
+
|
|
197
|
+
### Chat verbs
|
|
198
|
+
|
|
199
|
+
| Method | Provider | Mode |
|
|
200
|
+
| -------------------------- | ------------- | ------------ |
|
|
201
|
+
| `openai` / `aopenai` | OpenAI | sync / async |
|
|
202
|
+
| `anthropic` / `aanthropic` | Anthropic | sync / async |
|
|
203
|
+
| `gemini` / `agemini` | Google Gemini | sync / async |
|
|
204
|
+
|
|
205
|
+
### Embedding verbs
|
|
206
|
+
|
|
207
|
+
| Method | Provider | Mode |
|
|
208
|
+
| -------------------------------- | ----------------- | ------------ |
|
|
209
|
+
| `openai_embed` / `aopenai_embed` | OpenAI Embeddings | sync / async |
|
|
210
|
+
| `gemini_embed` / `agemini_embed` | Google Gemini | sync / async |
|
|
211
|
+
|
|
212
|
+
> Anthropic does not currently offer a first-party embeddings API.
|
|
213
|
+
|
|
214
|
+
### Common arguments
|
|
215
|
+
|
|
216
|
+
All verbs are keyword-only and accept:
|
|
217
|
+
|
|
218
|
+
- **`model`** _(str)_ — model name forwarded to LangChain (e.g. `"gpt-4o-mini"`, `"claude-sonnet-4-6"`, `"gemini-2.5-pro"`).
|
|
219
|
+
- **`system`** _(chat only)_ — literal string or `pl.Expr` for a per-row system prompt.
|
|
220
|
+
- **`schema`** _(chat only)_ — a Pydantic model class. Returns a struct column with the schema fields, via `with_structured_output`.
|
|
221
|
+
- **`client`** — a pre-configured LangChain chat or embeddings instance (skips the in-tree constructor and is handy for advanced configuration like custom base URLs).
|
|
222
|
+
- **`retries`** _(int, default 0)_ — retry on any exception raised by the provider call.
|
|
223
|
+
- **`backoff`** _(float, default 0.0)_ — exponential backoff base (seconds).
|
|
224
|
+
- **`max_concurrency`** _(async only, int)_ — cap on in-flight requests via `asyncio.Semaphore`.
|
|
225
|
+
- **`cache`** _(bool, default False)_ — memoise identical inputs within a batch.
|
|
226
|
+
- **`with_metadata`** _(bool, default False)_ — return a struct column with timing and error metadata instead of just the content / vector.
|
|
227
|
+
- **`on_error`** _("null" | "raise", default "null")_ — when `with_metadata=False`, what to do on errors. `"null"` replaces failures with `None` and emits a warning; `"raise"` re-raises immediately.
|
|
228
|
+
- **`**model_kwargs`** — any additional keyword arguments forwarded to the underlying LangChain class (e.g. `temperature=`, `max_tokens=`, `timeout=`).
|
|
229
|
+
|
|
230
|
+
### Return types
|
|
231
|
+
|
|
232
|
+
| Mode | Default dtype | With `with_metadata=True` |
|
|
233
|
+
| -------------------- | ----------------------------------------- | ----------------------------------------------------------------------------- |
|
|
234
|
+
| Chat (no `schema`) | `Utf8` | `Struct{content: Utf8, elapsed_ms: Float64, error: Utf8}` |
|
|
235
|
+
| Chat (with `schema`) | `Struct{...}` matching the Pydantic model | Same struct; content JSON-serialised under `content` |
|
|
236
|
+
| Embeddings | `List[Float64]` | `Struct{vector: List[Float64], dim: Int64, elapsed_ms: Float64, error: Utf8}` |
|
|
237
|
+
|
|
238
|
+
## Tips and patterns
|
|
239
|
+
|
|
240
|
+
- **Build prompts from columns** with `pl.format("Translate to {}: {}", pl.col("language"), pl.col("text"))`.
|
|
241
|
+
- **Bring your own client** to share a single `ChatOpenAI` (with custom `base_url`, `organization`, etc.) across many calls — pass it as `client=`.
|
|
242
|
+
- **Watch the warning** — when a request fails and is silently nulled, polars-llm emits a `UserWarning` so you don't ship a column of nulls by accident. Pass `with_metadata=True` to inspect per-row errors instead.
|
|
243
|
+
- **Combine with lazy frames** — every verb is an expression, so it composes inside `LazyFrame.with_columns(...)`.
|
|
244
|
+
|
|
245
|
+
## Contributing
|
|
246
|
+
|
|
247
|
+
Contributions are welcome — see [CONTRIBUTING.md](./CONTRIBUTING.md). Please open an issue before starting on larger changes.
|
|
248
|
+
|
|
249
|
+
## License
|
|
250
|
+
|
|
251
|
+
[MIT](./LICENSE) © Diego Garcia Lozano
|
|
252
|
+
|
|
253
|
+
---
|
|
254
|
+
|
|
255
|
+
Inspired by and patterned after [polars-api](https://github.com/diegoglozano/polars-api).
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
# polars-llm
|
|
2
|
+
|
|
3
|
+
[](https://pypi.org/project/polars-llm/)
|
|
4
|
+
[](https://pypi.org/project/polars-llm/)
|
|
5
|
+
[](https://github.com/diegoglozano/polars-ai/actions/workflows/main.yml?query=branch%3Amain)
|
|
6
|
+
[](https://codecov.io/gh/diegoglozano/polars-ai)
|
|
7
|
+
[](https://github.com/diegoglozano/polars-ai/blob/main/LICENSE)
|
|
8
|
+
|
|
9
|
+
**Call OpenAI, Anthropic, and Gemini models from a [Polars](https://pola.rs) DataFrame, one row at a time, using native Polars expressions.**
|
|
10
|
+
|
|
11
|
+
`polars-llm` registers an `.llm` namespace on Polars expressions so you can call any [LangChain](https://python.langchain.com/)-supported chat model or embedding model on every row of a DataFrame — synchronously or asynchronously — and pipe the responses straight back into your data pipeline.
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
import polars as pl
|
|
15
|
+
import polars_llm # noqa: F401 — registers the `.llm` namespace
|
|
16
|
+
|
|
17
|
+
(
|
|
18
|
+
pl.DataFrame({"user_prompt": ["Summarise polars in one sentence."]})
|
|
19
|
+
.with_columns(
|
|
20
|
+
pl.col("user_prompt").llm.openai(model="gpt-4o-mini").alias("answer")
|
|
21
|
+
)
|
|
22
|
+
)
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
- **Repository**: <https://github.com/diegoglozano/polars-ai>
|
|
26
|
+
- **Documentation**: <https://diegoglozano.github.io/polars-ai/>
|
|
27
|
+
- **PyPI**: <https://pypi.org/project/polars-llm/>
|
|
28
|
+
|
|
29
|
+
---
|
|
30
|
+
|
|
31
|
+
## Why polars-llm?
|
|
32
|
+
|
|
33
|
+
- **Expression-native** — works inside `with_columns`, `select`, and any other Polars expression context. No Python `for` loops over rows, no notebook glue.
|
|
34
|
+
- **Sync and async** — every provider verb has an `a`-prefixed async sibling that fans out concurrently with `asyncio.gather` and an optional `max_concurrency` cap.
|
|
35
|
+
- **Per-row prompts and system messages** — both the prompt and the system message can be Polars expressions, so you can build them from other columns.
|
|
36
|
+
- **Structured outputs** — pass a Pydantic model as `schema=` to get a struct column back, parsed via LangChain's `with_structured_output`.
|
|
37
|
+
- **Embeddings, too** — `openai_embed` and `gemini_embed` return `List[Float64]` columns ready for vector search.
|
|
38
|
+
- **Powered by [LangChain](https://python.langchain.com/)** — you get the same retries, batching, and observability primitives the rest of the LangChain ecosystem uses, plumbed straight into a DataFrame.
|
|
39
|
+
|
|
40
|
+
Common use cases:
|
|
41
|
+
|
|
42
|
+
- Summarise, classify, translate, or extract structured fields from a column of text.
|
|
43
|
+
- Score rows against a custom rubric using an LLM-as-judge.
|
|
44
|
+
- Build embeddings for a corpus directly from a DataFrame, ready to write to a vector database.
|
|
45
|
+
- Mix LLM calls with the rest of your pipeline (joins, filters, group-bys) without leaving Polars.
|
|
46
|
+
|
|
47
|
+
## Installation
|
|
48
|
+
|
|
49
|
+
`polars-llm` keeps its base install light. Pick the providers you need as extras:
|
|
50
|
+
|
|
51
|
+
```sh
|
|
52
|
+
# Just one provider
|
|
53
|
+
pip install "polars-llm[openai]"
|
|
54
|
+
pip install "polars-llm[anthropic]"
|
|
55
|
+
pip install "polars-llm[gemini]"
|
|
56
|
+
|
|
57
|
+
# Or all of them
|
|
58
|
+
pip install "polars-llm[all]"
|
|
59
|
+
|
|
60
|
+
# uv
|
|
61
|
+
uv add "polars-llm[all]"
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
Requires Python 3.9+ and Polars 1.0+.
|
|
65
|
+
|
|
66
|
+
Authentication follows LangChain conventions — set `OPENAI_API_KEY`, `ANTHROPIC_API_KEY`, or `GOOGLE_API_KEY` in your environment before importing.
|
|
67
|
+
|
|
68
|
+
## Quickstart
|
|
69
|
+
|
|
70
|
+
### 1. Chat completion per row
|
|
71
|
+
|
|
72
|
+
```python
|
|
73
|
+
import polars as pl
|
|
74
|
+
import polars_llm # noqa: F401
|
|
75
|
+
|
|
76
|
+
df = (
|
|
77
|
+
pl.DataFrame({"user_prompt": [
|
|
78
|
+
"What is the capital of Spain?",
|
|
79
|
+
"What is the capital of France?",
|
|
80
|
+
]})
|
|
81
|
+
.with_columns(
|
|
82
|
+
pl.col("user_prompt").llm.openai(model="gpt-4o-mini").alias("answer")
|
|
83
|
+
)
|
|
84
|
+
)
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
### 2. System prompt — literal or per-row
|
|
88
|
+
|
|
89
|
+
```python
|
|
90
|
+
# Same system prompt for every row
|
|
91
|
+
pl.col("user_prompt").llm.anthropic(
|
|
92
|
+
model="claude-sonnet-4-6",
|
|
93
|
+
system="Answer in fewer than 10 words.",
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
# Per-row system prompt from another column
|
|
97
|
+
pl.col("user_prompt").llm.gemini(
|
|
98
|
+
model="gemini-2.5-pro",
|
|
99
|
+
system=pl.col("system_prompt"),
|
|
100
|
+
)
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
### 3. Async for throughput
|
|
104
|
+
|
|
105
|
+
The `a`-prefixed verbs run concurrently across the batch, capped at `max_concurrency`:
|
|
106
|
+
|
|
107
|
+
```python
|
|
108
|
+
df.with_columns(
|
|
109
|
+
pl.col("user_prompt").llm.aopenai(
|
|
110
|
+
model="gpt-4o-mini",
|
|
111
|
+
max_concurrency=20,
|
|
112
|
+
).alias("answer")
|
|
113
|
+
)
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
### 4. Structured output with Pydantic
|
|
117
|
+
|
|
118
|
+
```python
|
|
119
|
+
from pydantic import BaseModel
|
|
120
|
+
|
|
121
|
+
class Sentiment(BaseModel):
|
|
122
|
+
label: str # "positive" | "neutral" | "negative"
|
|
123
|
+
confidence: float
|
|
124
|
+
|
|
125
|
+
df.with_columns(
|
|
126
|
+
pl.col("review").llm.openai(
|
|
127
|
+
model="gpt-4o-mini",
|
|
128
|
+
schema=Sentiment,
|
|
129
|
+
).alias("sentiment")
|
|
130
|
+
).unnest("sentiment")
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
### 5. Embeddings
|
|
134
|
+
|
|
135
|
+
```python
|
|
136
|
+
df.with_columns(
|
|
137
|
+
pl.col("text").llm.openai_embed(
|
|
138
|
+
model="text-embedding-3-small",
|
|
139
|
+
).alias("vector")
|
|
140
|
+
)
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
### 6. Retries, caching, metadata
|
|
144
|
+
|
|
145
|
+
```python
|
|
146
|
+
pl.col("user_prompt").llm.aanthropic(
|
|
147
|
+
model="claude-sonnet-4-6",
|
|
148
|
+
retries=3,
|
|
149
|
+
backoff=0.5,
|
|
150
|
+
max_concurrency=10,
|
|
151
|
+
cache=True, # dedupe identical prompts within a batch
|
|
152
|
+
with_metadata=True, # struct {content, elapsed_ms, error}
|
|
153
|
+
)
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
## API reference
|
|
157
|
+
|
|
158
|
+
All methods live under the `.llm` namespace on any Polars expression that resolves to a string column.
|
|
159
|
+
|
|
160
|
+
### Chat verbs
|
|
161
|
+
|
|
162
|
+
| Method | Provider | Mode |
|
|
163
|
+
| -------------------------- | ------------- | ------------ |
|
|
164
|
+
| `openai` / `aopenai` | OpenAI | sync / async |
|
|
165
|
+
| `anthropic` / `aanthropic` | Anthropic | sync / async |
|
|
166
|
+
| `gemini` / `agemini` | Google Gemini | sync / async |
|
|
167
|
+
|
|
168
|
+
### Embedding verbs
|
|
169
|
+
|
|
170
|
+
| Method | Provider | Mode |
|
|
171
|
+
| -------------------------------- | ----------------- | ------------ |
|
|
172
|
+
| `openai_embed` / `aopenai_embed` | OpenAI Embeddings | sync / async |
|
|
173
|
+
| `gemini_embed` / `agemini_embed` | Google Gemini | sync / async |
|
|
174
|
+
|
|
175
|
+
> Anthropic does not currently offer a first-party embeddings API.
|
|
176
|
+
|
|
177
|
+
### Common arguments
|
|
178
|
+
|
|
179
|
+
All verbs are keyword-only and accept:
|
|
180
|
+
|
|
181
|
+
- **`model`** _(str)_ — model name forwarded to LangChain (e.g. `"gpt-4o-mini"`, `"claude-sonnet-4-6"`, `"gemini-2.5-pro"`).
|
|
182
|
+
- **`system`** _(chat only)_ — literal string or `pl.Expr` for a per-row system prompt.
|
|
183
|
+
- **`schema`** _(chat only)_ — a Pydantic model class. Returns a struct column with the schema fields, via `with_structured_output`.
|
|
184
|
+
- **`client`** — a pre-configured LangChain chat or embeddings instance (skips the in-tree constructor and is handy for advanced configuration like custom base URLs).
|
|
185
|
+
- **`retries`** _(int, default 0)_ — retry on any exception raised by the provider call.
|
|
186
|
+
- **`backoff`** _(float, default 0.0)_ — exponential backoff base (seconds).
|
|
187
|
+
- **`max_concurrency`** _(async only, int)_ — cap on in-flight requests via `asyncio.Semaphore`.
|
|
188
|
+
- **`cache`** _(bool, default False)_ — memoise identical inputs within a batch.
|
|
189
|
+
- **`with_metadata`** _(bool, default False)_ — return a struct column with timing and error metadata instead of just the content / vector.
|
|
190
|
+
- **`on_error`** _("null" | "raise", default "null")_ — when `with_metadata=False`, what to do on errors. `"null"` replaces failures with `None` and emits a warning; `"raise"` re-raises immediately.
|
|
191
|
+
- **`**model_kwargs`** — any additional keyword arguments forwarded to the underlying LangChain class (e.g. `temperature=`, `max_tokens=`, `timeout=`).
|
|
192
|
+
|
|
193
|
+
### Return types
|
|
194
|
+
|
|
195
|
+
| Mode | Default dtype | With `with_metadata=True` |
|
|
196
|
+
| -------------------- | ----------------------------------------- | ----------------------------------------------------------------------------- |
|
|
197
|
+
| Chat (no `schema`) | `Utf8` | `Struct{content: Utf8, elapsed_ms: Float64, error: Utf8}` |
|
|
198
|
+
| Chat (with `schema`) | `Struct{...}` matching the Pydantic model | Same struct; content JSON-serialised under `content` |
|
|
199
|
+
| Embeddings | `List[Float64]` | `Struct{vector: List[Float64], dim: Int64, elapsed_ms: Float64, error: Utf8}` |
|
|
200
|
+
|
|
201
|
+
## Tips and patterns
|
|
202
|
+
|
|
203
|
+
- **Build prompts from columns** with `pl.format("Translate to {}: {}", pl.col("language"), pl.col("text"))`.
|
|
204
|
+
- **Bring your own client** to share a single `ChatOpenAI` (with custom `base_url`, `organization`, etc.) across many calls — pass it as `client=`.
|
|
205
|
+
- **Watch the warning** — when a request fails and is silently nulled, polars-llm emits a `UserWarning` so you don't ship a column of nulls by accident. Pass `with_metadata=True` to inspect per-row errors instead.
|
|
206
|
+
- **Combine with lazy frames** — every verb is an expression, so it composes inside `LazyFrame.with_columns(...)`.
|
|
207
|
+
|
|
208
|
+
## Contributing
|
|
209
|
+
|
|
210
|
+
Contributions are welcome — see [CONTRIBUTING.md](./CONTRIBUTING.md). Please open an issue before starting on larger changes.
|
|
211
|
+
|
|
212
|
+
## License
|
|
213
|
+
|
|
214
|
+
[MIT](./LICENSE) © Diego Garcia Lozano
|
|
215
|
+
|
|
216
|
+
---
|
|
217
|
+
|
|
218
|
+
Inspired by and patterned after [polars-api](https://github.com/diegoglozano/polars-api).
|