ollama-classifier 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.
@@ -0,0 +1,247 @@
1
+ Metadata-Version: 2.3
2
+ Name: ollama-classifier
3
+ Version: 0.1.0
4
+ Summary: A wrapper around Ollama Python SDK for text classification with constrained output and confidence scoring
5
+ Author: Luigi Palumbo, Mengting Yu
6
+ Author-email: Luigi Palumbo <paluigi@gmail.com>, Mengting Yu <mengting.yu@unitus.it>
7
+ Requires-Dist: ollama>=0.4.0
8
+ Requires-Dist: sphinx>=7.0.0 ; extra == 'docs'
9
+ Requires-Dist: sphinx-rtd-theme>=2.0.0 ; extra == 'docs'
10
+ Requires-Dist: myst-parser>=2.0.0 ; extra == 'docs'
11
+ Requires-Python: >=3.11
12
+ Provides-Extra: docs
13
+ Description-Content-Type: text/markdown
14
+
15
+ # ollama-classifier
16
+
17
+ A Python wrapper around the Ollama Python SDK for text classification with constrained output and confidence scoring.
18
+
19
+ ## Features
20
+
21
+ - **Constrained Output**: Uses JSON schema with enum constraints to ensure only valid choices are generated
22
+ - **Confidence Scoring**: Two methods available:
23
+ - **Fast**: Single API call with logprob extraction
24
+ - **Complete**: Multi-call evaluation with softmax for calibrated probabilities
25
+ - **Sync & Async**: Full support for both synchronous and asynchronous operations
26
+ - **Batch Processing**: Classify multiple texts efficiently
27
+ - **Flexible Choices**: Support for simple labels or labels with descriptions
28
+ - **Custom Prompts**: Override the default system prompt for specialized tasks
29
+
30
+ ## Installation
31
+
32
+ ```bash
33
+ pip install ollama-classifier
34
+ ```
35
+
36
+ Or with uv:
37
+
38
+ ```bash
39
+ uv add ollama-classifier
40
+ ```
41
+
42
+ ## Prerequisites
43
+
44
+ - [Ollama](https://ollama.com/download) installed and running
45
+ - A model pulled (e.g., `ollama pull llama3.2`)
46
+
47
+ ## Quick Start
48
+
49
+ ```python
50
+ from ollama import Client
51
+ from ollama_classifier import OllamaClassifier
52
+
53
+ client = Client()
54
+ classifier = OllamaClassifier(client, model="llama3.2")
55
+
56
+ result = classifier.classify(
57
+ text="I love this product!",
58
+ choices=["positive", "negative", "neutral"]
59
+ )
60
+
61
+ print(f"Prediction: {result.prediction}")
62
+ print(f"Confidence: {result.confidence:.2%}")
63
+ print(f"Probabilities: {result.probabilities}")
64
+ ```
65
+
66
+ ## Usage
67
+
68
+ ### Basic Classification
69
+
70
+ ```python
71
+ from ollama import Client
72
+ from ollama_classifier import OllamaClassifier
73
+
74
+ client = Client()
75
+ classifier = OllamaClassifier(client, model="llama3.2")
76
+
77
+ result = classifier.classify(
78
+ text="The goalkeeper made an incredible save!",
79
+ choices=["sports", "politics", "technology", "entertainment"]
80
+ )
81
+ ```
82
+
83
+ ### Classification with Label Descriptions
84
+
85
+ Providing descriptions helps the model understand each category better:
86
+
87
+ ```python
88
+ choices = {
89
+ "positive": "Text expresses happiness, satisfaction, or approval",
90
+ "negative": "Text expresses anger, disappointment, or disapproval",
91
+ "mixed": "Text contains both positive and negative sentiments",
92
+ "neutral": "Text is factual without strong emotional content",
93
+ }
94
+
95
+ result = classifier.classify(
96
+ text="The food was amazing but the service was terrible.",
97
+ choices=choices
98
+ )
99
+ ```
100
+
101
+ ### Custom System Prompt
102
+
103
+ ```python
104
+ result = classifier.classify(
105
+ text="The quarterly earnings exceeded analyst expectations.",
106
+ choices=["bullish", "bearish", "neutral"],
107
+ system_prompt="You are a financial sentiment analyzer. "
108
+ "Classify financial news based on market sentiment."
109
+ )
110
+ ```
111
+
112
+ ### Scoring Methods
113
+
114
+ #### Fast Scoring (Single API Call)
115
+
116
+ ```python
117
+ result = classifier.score_fast(
118
+ text="The movie was fantastic!",
119
+ choices=["positive", "negative", "neutral"]
120
+ )
121
+ ```
122
+
123
+ #### Complete Scoring (Multi-Call with Softmax)
124
+
125
+ More accurate but makes N API calls for N choices:
126
+
127
+ ```python
128
+ result = classifier.score_complete(
129
+ text="The movie was fantastic!",
130
+ choices=["positive", "negative", "neutral"]
131
+ )
132
+ ```
133
+
134
+ ### Generate Only (Fastest)
135
+
136
+ When you only need the prediction without confidence scores:
137
+
138
+ ```python
139
+ prediction = classifier.generate(
140
+ text="The team won the championship!",
141
+ choices=["sports", "finance", "politics"]
142
+ )
143
+ ```
144
+
145
+ ### Batch Classification
146
+
147
+ ```python
148
+ texts = [
149
+ "The goalkeeper made an incredible save!",
150
+ "The central bank raised interest rates.",
151
+ "The new smartphone features a revolutionary camera.",
152
+ ]
153
+
154
+ # Fast batch classification
155
+ results = classifier.batch_classify(
156
+ texts=texts,
157
+ choices=["sports", "finance", "technology"]
158
+ )
159
+
160
+ # Complete batch classification (more accurate)
161
+ results = classifier.batch_classify_complete(
162
+ texts=texts,
163
+ choices=["sports", "finance", "technology"]
164
+ )
165
+
166
+ for text, result in zip(texts, results):
167
+ print(f"{text} -> {result.prediction} ({result.confidence:.2%})")
168
+ ```
169
+
170
+ ### Async Usage
171
+
172
+ ```python
173
+ import asyncio
174
+ from ollama import AsyncClient
175
+ from ollama_classifier import OllamaClassifier
176
+
177
+ async def main():
178
+ client = AsyncClient()
179
+ classifier = OllamaClassifier(client, model="llama3.2")
180
+
181
+ # Single classification
182
+ result = await classifier.aclassify(
183
+ text="The concert was amazing!",
184
+ choices=["positive", "negative", "neutral"]
185
+ )
186
+
187
+ # Batch classification (concurrent)
188
+ results = await classifier.abatch_classify(
189
+ texts=["Text 1", "Text 2", "Text 3"],
190
+ choices=["positive", "negative", "neutral"]
191
+ )
192
+
193
+ asyncio.run(main())
194
+ ```
195
+
196
+ ## API Reference
197
+
198
+ ### ClassificationResult
199
+
200
+ ```python
201
+ @dataclass
202
+ class ClassificationResult:
203
+ prediction: str # The predicted choice label
204
+ confidence: float # Confidence score (0.0 to 1.0)
205
+ probabilities: Dict[str, float] # Probability distribution over all choices
206
+ raw_response: Dict # Raw Ollama response for debugging
207
+ ```
208
+
209
+ ### OllamaClassifier Methods
210
+
211
+ | Method | Async | Description |
212
+ |--------|-------|-------------|
213
+ | `generate(text, choices, system_prompt)` | `agenerate` | Constrained output only (fastest) |
214
+ | `score_fast(text, choices, system_prompt)` | `ascore_fast` | Single-call logprob extraction |
215
+ | `score_complete(text, choices, system_prompt)` | `ascore_complete` | Multi-call evaluation with softmax |
216
+ | `classify(text, choices, system_prompt)` | `aclassify` | Generate + score_fast |
217
+ | `classify_complete(text, choices, system_prompt)` | `aclassify_complete` | Generate + score_complete |
218
+ | `batch_generate(texts, choices, system_prompt)` | `abatch_generate` | Batch constrained output |
219
+ | `batch_score_fast(texts, choices, system_prompt)` | `abatch_score_fast` | Batch fast scoring |
220
+ | `batch_score_complete(texts, choices, system_prompt)` | `abatch_score_complete` | Batch complete scoring |
221
+ | `batch_classify(texts, choices, system_prompt)` | `abatch_classify` | Batch classify (fast) |
222
+ | `batch_classify_complete(texts, choices, system_prompt)` | `abatch_classify_complete` | Batch classify (complete) |
223
+
224
+ ### Parameters
225
+
226
+ - **text** (str): The text to classify
227
+ - **texts** (List[str]): List of texts to classify (batch methods)
228
+ - **choices** (Union[List[str], Dict[str, str]]): Either a list of choice labels, or a dict mapping labels to descriptions
229
+ - **system_prompt** (str | None): Optional custom system prompt
230
+
231
+ ## Choosing a Method
232
+
233
+ | Use Case | Recommended Method |
234
+ |----------|-------------------|
235
+ | Speed is critical, no confidence needed | `generate` |
236
+ | Speed with confidence scores | `classify` / `score_fast` |
237
+ | Accurate confidence scores | `classify_complete` / `score_complete` |
238
+ | Batch processing | `batch_classify` or `batch_classify_complete` |
239
+ | Concurrent processing | Async variants (`aclassify`, etc.) |
240
+
241
+ ## License
242
+
243
+ MIT License
244
+
245
+ ## Development
246
+
247
+ This project just started! Looking forward to suggestions, issues, and pull requests!
@@ -0,0 +1,233 @@
1
+ # ollama-classifier
2
+
3
+ A Python wrapper around the Ollama Python SDK for text classification with constrained output and confidence scoring.
4
+
5
+ ## Features
6
+
7
+ - **Constrained Output**: Uses JSON schema with enum constraints to ensure only valid choices are generated
8
+ - **Confidence Scoring**: Two methods available:
9
+ - **Fast**: Single API call with logprob extraction
10
+ - **Complete**: Multi-call evaluation with softmax for calibrated probabilities
11
+ - **Sync & Async**: Full support for both synchronous and asynchronous operations
12
+ - **Batch Processing**: Classify multiple texts efficiently
13
+ - **Flexible Choices**: Support for simple labels or labels with descriptions
14
+ - **Custom Prompts**: Override the default system prompt for specialized tasks
15
+
16
+ ## Installation
17
+
18
+ ```bash
19
+ pip install ollama-classifier
20
+ ```
21
+
22
+ Or with uv:
23
+
24
+ ```bash
25
+ uv add ollama-classifier
26
+ ```
27
+
28
+ ## Prerequisites
29
+
30
+ - [Ollama](https://ollama.com/download) installed and running
31
+ - A model pulled (e.g., `ollama pull llama3.2`)
32
+
33
+ ## Quick Start
34
+
35
+ ```python
36
+ from ollama import Client
37
+ from ollama_classifier import OllamaClassifier
38
+
39
+ client = Client()
40
+ classifier = OllamaClassifier(client, model="llama3.2")
41
+
42
+ result = classifier.classify(
43
+ text="I love this product!",
44
+ choices=["positive", "negative", "neutral"]
45
+ )
46
+
47
+ print(f"Prediction: {result.prediction}")
48
+ print(f"Confidence: {result.confidence:.2%}")
49
+ print(f"Probabilities: {result.probabilities}")
50
+ ```
51
+
52
+ ## Usage
53
+
54
+ ### Basic Classification
55
+
56
+ ```python
57
+ from ollama import Client
58
+ from ollama_classifier import OllamaClassifier
59
+
60
+ client = Client()
61
+ classifier = OllamaClassifier(client, model="llama3.2")
62
+
63
+ result = classifier.classify(
64
+ text="The goalkeeper made an incredible save!",
65
+ choices=["sports", "politics", "technology", "entertainment"]
66
+ )
67
+ ```
68
+
69
+ ### Classification with Label Descriptions
70
+
71
+ Providing descriptions helps the model understand each category better:
72
+
73
+ ```python
74
+ choices = {
75
+ "positive": "Text expresses happiness, satisfaction, or approval",
76
+ "negative": "Text expresses anger, disappointment, or disapproval",
77
+ "mixed": "Text contains both positive and negative sentiments",
78
+ "neutral": "Text is factual without strong emotional content",
79
+ }
80
+
81
+ result = classifier.classify(
82
+ text="The food was amazing but the service was terrible.",
83
+ choices=choices
84
+ )
85
+ ```
86
+
87
+ ### Custom System Prompt
88
+
89
+ ```python
90
+ result = classifier.classify(
91
+ text="The quarterly earnings exceeded analyst expectations.",
92
+ choices=["bullish", "bearish", "neutral"],
93
+ system_prompt="You are a financial sentiment analyzer. "
94
+ "Classify financial news based on market sentiment."
95
+ )
96
+ ```
97
+
98
+ ### Scoring Methods
99
+
100
+ #### Fast Scoring (Single API Call)
101
+
102
+ ```python
103
+ result = classifier.score_fast(
104
+ text="The movie was fantastic!",
105
+ choices=["positive", "negative", "neutral"]
106
+ )
107
+ ```
108
+
109
+ #### Complete Scoring (Multi-Call with Softmax)
110
+
111
+ More accurate but makes N API calls for N choices:
112
+
113
+ ```python
114
+ result = classifier.score_complete(
115
+ text="The movie was fantastic!",
116
+ choices=["positive", "negative", "neutral"]
117
+ )
118
+ ```
119
+
120
+ ### Generate Only (Fastest)
121
+
122
+ When you only need the prediction without confidence scores:
123
+
124
+ ```python
125
+ prediction = classifier.generate(
126
+ text="The team won the championship!",
127
+ choices=["sports", "finance", "politics"]
128
+ )
129
+ ```
130
+
131
+ ### Batch Classification
132
+
133
+ ```python
134
+ texts = [
135
+ "The goalkeeper made an incredible save!",
136
+ "The central bank raised interest rates.",
137
+ "The new smartphone features a revolutionary camera.",
138
+ ]
139
+
140
+ # Fast batch classification
141
+ results = classifier.batch_classify(
142
+ texts=texts,
143
+ choices=["sports", "finance", "technology"]
144
+ )
145
+
146
+ # Complete batch classification (more accurate)
147
+ results = classifier.batch_classify_complete(
148
+ texts=texts,
149
+ choices=["sports", "finance", "technology"]
150
+ )
151
+
152
+ for text, result in zip(texts, results):
153
+ print(f"{text} -> {result.prediction} ({result.confidence:.2%})")
154
+ ```
155
+
156
+ ### Async Usage
157
+
158
+ ```python
159
+ import asyncio
160
+ from ollama import AsyncClient
161
+ from ollama_classifier import OllamaClassifier
162
+
163
+ async def main():
164
+ client = AsyncClient()
165
+ classifier = OllamaClassifier(client, model="llama3.2")
166
+
167
+ # Single classification
168
+ result = await classifier.aclassify(
169
+ text="The concert was amazing!",
170
+ choices=["positive", "negative", "neutral"]
171
+ )
172
+
173
+ # Batch classification (concurrent)
174
+ results = await classifier.abatch_classify(
175
+ texts=["Text 1", "Text 2", "Text 3"],
176
+ choices=["positive", "negative", "neutral"]
177
+ )
178
+
179
+ asyncio.run(main())
180
+ ```
181
+
182
+ ## API Reference
183
+
184
+ ### ClassificationResult
185
+
186
+ ```python
187
+ @dataclass
188
+ class ClassificationResult:
189
+ prediction: str # The predicted choice label
190
+ confidence: float # Confidence score (0.0 to 1.0)
191
+ probabilities: Dict[str, float] # Probability distribution over all choices
192
+ raw_response: Dict # Raw Ollama response for debugging
193
+ ```
194
+
195
+ ### OllamaClassifier Methods
196
+
197
+ | Method | Async | Description |
198
+ |--------|-------|-------------|
199
+ | `generate(text, choices, system_prompt)` | `agenerate` | Constrained output only (fastest) |
200
+ | `score_fast(text, choices, system_prompt)` | `ascore_fast` | Single-call logprob extraction |
201
+ | `score_complete(text, choices, system_prompt)` | `ascore_complete` | Multi-call evaluation with softmax |
202
+ | `classify(text, choices, system_prompt)` | `aclassify` | Generate + score_fast |
203
+ | `classify_complete(text, choices, system_prompt)` | `aclassify_complete` | Generate + score_complete |
204
+ | `batch_generate(texts, choices, system_prompt)` | `abatch_generate` | Batch constrained output |
205
+ | `batch_score_fast(texts, choices, system_prompt)` | `abatch_score_fast` | Batch fast scoring |
206
+ | `batch_score_complete(texts, choices, system_prompt)` | `abatch_score_complete` | Batch complete scoring |
207
+ | `batch_classify(texts, choices, system_prompt)` | `abatch_classify` | Batch classify (fast) |
208
+ | `batch_classify_complete(texts, choices, system_prompt)` | `abatch_classify_complete` | Batch classify (complete) |
209
+
210
+ ### Parameters
211
+
212
+ - **text** (str): The text to classify
213
+ - **texts** (List[str]): List of texts to classify (batch methods)
214
+ - **choices** (Union[List[str], Dict[str, str]]): Either a list of choice labels, or a dict mapping labels to descriptions
215
+ - **system_prompt** (str | None): Optional custom system prompt
216
+
217
+ ## Choosing a Method
218
+
219
+ | Use Case | Recommended Method |
220
+ |----------|-------------------|
221
+ | Speed is critical, no confidence needed | `generate` |
222
+ | Speed with confidence scores | `classify` / `score_fast` |
223
+ | Accurate confidence scores | `classify_complete` / `score_complete` |
224
+ | Batch processing | `batch_classify` or `batch_classify_complete` |
225
+ | Concurrent processing | Async variants (`aclassify`, etc.) |
226
+
227
+ ## License
228
+
229
+ MIT License
230
+
231
+ ## Development
232
+
233
+ This project just started! Looking forward to suggestions, issues, and pull requests!
@@ -0,0 +1,24 @@
1
+ [project]
2
+ name = "ollama-classifier"
3
+ version = "0.1.0"
4
+ description = "A wrapper around Ollama Python SDK for text classification with constrained output and confidence scoring"
5
+ readme = "README.md"
6
+ authors = [
7
+ { name = "Luigi Palumbo", email = "paluigi@gmail.com" },
8
+ {name = "Mengting Yu", email = "mengting.yu@unitus.it"}
9
+ ]
10
+ requires-python = ">=3.11"
11
+ dependencies = [
12
+ "ollama>=0.4.0",
13
+ ]
14
+
15
+ [project.optional-dependencies]
16
+ docs = [
17
+ "sphinx>=7.0.0",
18
+ "sphinx-rtd-theme>=2.0.0",
19
+ "myst-parser>=2.0.0",
20
+ ]
21
+
22
+ [build-system]
23
+ requires = ["uv_build>=0.9.26,<0.10.0"]
24
+ build-backend = "uv_build"
@@ -0,0 +1,30 @@
1
+ """Ollama Classifier - A wrapper around Ollama Python SDK for text classification.
2
+
3
+ This package provides a classifier for text classification with constrained output
4
+ and confidence scoring using the Ollama Python SDK.
5
+
6
+ Example usage:
7
+ from ollama import Client
8
+ from ollama_classifier import OllamaClassifier, ClassificationResult
9
+
10
+ client = Client()
11
+ classifier = OllamaClassifier(client, model="llama3.2")
12
+
13
+ result = classifier.classify(
14
+ text="I love this product!",
15
+ choices=["positive", "negative", "neutral"]
16
+ )
17
+ print(f"Prediction: {result.prediction}")
18
+ print(f"Confidence: {result.confidence:.2%}")
19
+ """
20
+
21
+ from .types import ClassificationResult, ChoicesType
22
+ from .classifier import OllamaClassifier
23
+
24
+ __all__ = [
25
+ "OllamaClassifier",
26
+ "ClassificationResult",
27
+ "ChoicesType",
28
+ ]
29
+
30
+ __version__ = "0.1.0"