habermas-machine 0.1.1.dev0__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.
- habermas_machine/__init__.py +27 -0
- habermas_machine/_version.py +24 -0
- habermas_machine/llm_client/__init__.py +16 -0
- habermas_machine/llm_client/aistudio_client.py +193 -0
- habermas_machine/llm_client/anthropic_client.py +195 -0
- habermas_machine/llm_client/base_client.py +98 -0
- habermas_machine/llm_client/mock_client.py +59 -0
- habermas_machine/llm_client/togetherai_client.py +172 -0
- habermas_machine/llm_client/utils.py +42 -0
- habermas_machine/machine.py +831 -0
- habermas_machine/models.py +132 -0
- habermas_machine/prompts.py +476 -0
- habermas_machine/prompts_i18n.py +480 -0
- habermas_machine/reward_model/__init__.py +16 -0
- habermas_machine/reward_model/base_model.py +83 -0
- habermas_machine/reward_model/cot_ranking_model.py +117 -0
- habermas_machine/reward_model/finetuned_reward_model.py +109 -0
- habermas_machine/reward_model/length_based_model.py +67 -0
- habermas_machine/reward_model/mock_ranking_model.py +60 -0
- habermas_machine/reward_model/utils.py +414 -0
- habermas_machine/social_choice/__init__.py +16 -0
- habermas_machine/social_choice/approval_method.py +177 -0
- habermas_machine/social_choice/base_method.py +228 -0
- habermas_machine/social_choice/maximal_lotteries.py +211 -0
- habermas_machine/social_choice/mock_method.py +50 -0
- habermas_machine/social_choice/schulze_method.py +223 -0
- habermas_machine/social_choice/utils.py +112 -0
- habermas_machine/statement_model/__init__.py +16 -0
- habermas_machine/statement_model/base_model.py +100 -0
- habermas_machine/statement_model/cot_model.py +266 -0
- habermas_machine/statement_model/mock_statement_model.py +72 -0
- habermas_machine/statement_model/two_step_diverse_model.py +232 -0
- habermas_machine/types.py +70 -0
- habermas_machine/utils.py +66 -0
- habermas_machine-0.1.1.dev0.dist-info/METADATA +96 -0
- habermas_machine-0.1.1.dev0.dist-info/RECORD +41 -0
- habermas_machine-0.1.1.dev0.dist-info/WHEEL +5 -0
- habermas_machine-0.1.1.dev0.dist-info/licenses/LICENSE +161 -0
- habermas_machine-0.1.1.dev0.dist-info/scm_file_list.json +60 -0
- habermas_machine-0.1.1.dev0.dist-info/scm_version.json +8 -0
- habermas_machine-0.1.1.dev0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# Copyright 2025 Google LLC
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
# ==============================================================================
|
|
15
|
+
|
|
16
|
+
"""Habermas Machine package metadata."""
|
|
17
|
+
|
|
18
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
try:
|
|
22
|
+
__version__ = version("habermas-machine")
|
|
23
|
+
except PackageNotFoundError:
|
|
24
|
+
__version__ = "0.0.0"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
__all__ = ["__version__"]
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# file generated by vcs-versioning
|
|
2
|
+
# don't change, don't track in version control
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
__all__ = [
|
|
6
|
+
"__version__",
|
|
7
|
+
"__version_tuple__",
|
|
8
|
+
"version",
|
|
9
|
+
"version_tuple",
|
|
10
|
+
"__commit_id__",
|
|
11
|
+
"commit_id",
|
|
12
|
+
]
|
|
13
|
+
|
|
14
|
+
version: str
|
|
15
|
+
__version__: str
|
|
16
|
+
__version_tuple__: tuple[int | str, ...]
|
|
17
|
+
version_tuple: tuple[int | str, ...]
|
|
18
|
+
commit_id: str | None
|
|
19
|
+
__commit_id__: str | None
|
|
20
|
+
|
|
21
|
+
__version__ = version = '0.1.1.dev0'
|
|
22
|
+
__version_tuple__ = version_tuple = (0, 1, 1, 'dev0')
|
|
23
|
+
|
|
24
|
+
__commit_id__ = commit_id = None
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
# Copyright 2025 Google LLC
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
# ==============================================================================
|
|
15
|
+
|
|
16
|
+
"""LLM clients for a prompted Habermas Machine."""
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
# Copyright 2025 Google LLC
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
# ==============================================================================
|
|
15
|
+
|
|
16
|
+
"""Language Model that uses GDM AI Studio API."""
|
|
17
|
+
|
|
18
|
+
from collections.abc import Collection, Mapping, Sequence
|
|
19
|
+
import json
|
|
20
|
+
import os
|
|
21
|
+
import tempfile
|
|
22
|
+
import time
|
|
23
|
+
from datetime import datetime
|
|
24
|
+
|
|
25
|
+
import google.generativeai as genai
|
|
26
|
+
from google.generativeai import types
|
|
27
|
+
from typing_extensions import override
|
|
28
|
+
from dotenv import load_dotenv
|
|
29
|
+
|
|
30
|
+
from habermas_machine.llm_client import base_client
|
|
31
|
+
from habermas_machine.llm_client import utils
|
|
32
|
+
|
|
33
|
+
DEFAULT_SAFETY_SETTINGS = [
|
|
34
|
+
types.SafetySettingDict(
|
|
35
|
+
category=types.HarmCategory.HARM_CATEGORY_HARASSMENT,
|
|
36
|
+
threshold=types.HarmBlockThreshold.BLOCK_ONLY_HIGH,
|
|
37
|
+
),
|
|
38
|
+
types.SafetySettingDict(
|
|
39
|
+
category=types.HarmCategory.HARM_CATEGORY_HATE_SPEECH,
|
|
40
|
+
threshold=types.HarmBlockThreshold.BLOCK_ONLY_HIGH,
|
|
41
|
+
),
|
|
42
|
+
types.SafetySettingDict(
|
|
43
|
+
category=types.HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT,
|
|
44
|
+
threshold=types.HarmBlockThreshold.BLOCK_ONLY_HIGH,
|
|
45
|
+
),
|
|
46
|
+
types.SafetySettingDict(
|
|
47
|
+
category=types.HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,
|
|
48
|
+
threshold=types.HarmBlockThreshold.BLOCK_ONLY_HIGH,
|
|
49
|
+
),
|
|
50
|
+
]
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class AIStudioClient(base_client.LLMClient):
|
|
54
|
+
"""Language Model that uses AI Studio API."""
|
|
55
|
+
|
|
56
|
+
def __init__(
|
|
57
|
+
self,
|
|
58
|
+
model_name: str,
|
|
59
|
+
*,
|
|
60
|
+
safety_settings: Sequence[Mapping[str, str]] = DEFAULT_SAFETY_SETTINGS,
|
|
61
|
+
tmp_dir: str | None = None,
|
|
62
|
+
) -> None:
|
|
63
|
+
"""Initializes the instance.
|
|
64
|
+
|
|
65
|
+
Args:
|
|
66
|
+
model_name: which language model to use. For more details, see
|
|
67
|
+
https://aistudio.google.com/.
|
|
68
|
+
safety_settings: Gemini safety settings. For more details, see
|
|
69
|
+
https://ai.google.dev/gemini-api/docs/safety.
|
|
70
|
+
tmp_dir: directory for temporary batch input files. Defaults to the
|
|
71
|
+
system temp directory.
|
|
72
|
+
"""
|
|
73
|
+
load_dotenv()
|
|
74
|
+
self._api_key = os.environ['GEMINI_API_KEY']
|
|
75
|
+
self._model_name = model_name
|
|
76
|
+
self._safety_settings = safety_settings
|
|
77
|
+
self._client = genai.Client(api_key=self._api_key)
|
|
78
|
+
self._tmp_dir = tmp_dir or tempfile.gettempdir()
|
|
79
|
+
|
|
80
|
+
@override
|
|
81
|
+
def sample_text(
|
|
82
|
+
self,
|
|
83
|
+
prompt: str,
|
|
84
|
+
*,
|
|
85
|
+
max_tokens: int = base_client.DEFAULT_MAX_TOKENS,
|
|
86
|
+
terminators: Collection[str] = base_client.DEFAULT_TERMINATORS,
|
|
87
|
+
temperature: float = base_client.DEFAULT_TEMPERATURE,
|
|
88
|
+
timeout: float = base_client.DEFAULT_TIMEOUT_SECONDS,
|
|
89
|
+
seed: int | None = None,
|
|
90
|
+
) -> str:
|
|
91
|
+
del timeout
|
|
92
|
+
response = self._client.models.generate_content(
|
|
93
|
+
model=self._model_name,
|
|
94
|
+
contents=[prompt.strip()], # Remove leading and trailing whitespace
|
|
95
|
+
config=types.GenerateContentConfig(
|
|
96
|
+
thinking_config=types.ThinkingConfig(thinking_budget=0), # Disables thinking
|
|
97
|
+
temperature=temperature,
|
|
98
|
+
stop_sequences=terminators,
|
|
99
|
+
seed=seed,
|
|
100
|
+
maxOutputTokens=max_tokens,
|
|
101
|
+
safety_settings=self._safety_settings,
|
|
102
|
+
),
|
|
103
|
+
)
|
|
104
|
+
try:
|
|
105
|
+
response = response.text
|
|
106
|
+
except ValueError as e:
|
|
107
|
+
print('An error occurred: ', e)
|
|
108
|
+
print(f'prompt: {prompt}')
|
|
109
|
+
print(f'sample: {response}')
|
|
110
|
+
return utils.truncate(response, delimiters=terminators)
|
|
111
|
+
|
|
112
|
+
@override
|
|
113
|
+
def batch_sample_text(
|
|
114
|
+
self,
|
|
115
|
+
prompts: dict[str, str], # custom_id -> prompt
|
|
116
|
+
*,
|
|
117
|
+
max_tokens: int = base_client.DEFAULT_MAX_TOKENS,
|
|
118
|
+
terminators: Collection[str] = base_client.DEFAULT_TERMINATORS,
|
|
119
|
+
temperature: float = base_client.DEFAULT_TEMPERATURE,
|
|
120
|
+
timeout: float = base_client.DEFAULT_TIMEOUT_SECONDS,
|
|
121
|
+
seed: int | None = None,
|
|
122
|
+
) -> dict[str, str]:
|
|
123
|
+
"""
|
|
124
|
+
Batch version of sample_text. Returns a dict of custom_id -> response.
|
|
125
|
+
"""
|
|
126
|
+
# TODO: check if custom id is working, verify and process output. have not tested yet
|
|
127
|
+
|
|
128
|
+
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
|
|
129
|
+
filename = os.path.join(self._tmp_dir, f"aistudio_batch_input_{ts}.jsonl")
|
|
130
|
+
with open(filename, "w") as f:
|
|
131
|
+
for custom_id, prompt in prompts.items():
|
|
132
|
+
req = {
|
|
133
|
+
"key": custom_id,
|
|
134
|
+
"request": {
|
|
135
|
+
"contents": [
|
|
136
|
+
{"parts": [{"text": prompt.strip()}]}
|
|
137
|
+
],
|
|
138
|
+
"config": {
|
|
139
|
+
"safety_settings": [s._asdict() if hasattr(s, "_asdict") else dict(s) for s in safety_settings],
|
|
140
|
+
"thinking_config": {
|
|
141
|
+
"thinking_budget": 0
|
|
142
|
+
},
|
|
143
|
+
"temperature": temperature,
|
|
144
|
+
"stop_sequences": terminators,
|
|
145
|
+
"seed": seed,
|
|
146
|
+
"maxOutputTokens": max_tokens
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
f.write(json.dumps(req) + "\n")
|
|
151
|
+
|
|
152
|
+
# Upload the file to the File API
|
|
153
|
+
uploaded_file = client.files.upload(
|
|
154
|
+
file=filename,
|
|
155
|
+
config=types.UploadFileConfig(display_name='my-batch-requests', mime_type='jsonl')
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
batch_job = client.batches.create(
|
|
159
|
+
model= self._model_name,
|
|
160
|
+
src=uploaded_file.name,
|
|
161
|
+
config={
|
|
162
|
+
'display_name': "file-upload-job-1",
|
|
163
|
+
},
|
|
164
|
+
)
|
|
165
|
+
|
|
166
|
+
job_name = batch_job.name
|
|
167
|
+
batch_job = client.batches.get(name=job_name)
|
|
168
|
+
|
|
169
|
+
# Wait for the batch job to complete
|
|
170
|
+
completed_states = set([
|
|
171
|
+
'JOB_STATE_SUCCEEDED',
|
|
172
|
+
'JOB_STATE_FAILED',
|
|
173
|
+
'JOB_STATE_CANCELLED',
|
|
174
|
+
])
|
|
175
|
+
batch_job = client.batches.get(name=job_name) # Initial get
|
|
176
|
+
while batch_job.state.name not in completed_states:
|
|
177
|
+
time.sleep(30) # Wait for 30 seconds before polling again
|
|
178
|
+
batch_job = client.batches.get(name=job_name)
|
|
179
|
+
|
|
180
|
+
if batch_job.state.name == 'JOB_STATE_SUCCEEDED':
|
|
181
|
+
if batch_job.dest and batch_job.dest.file_name:
|
|
182
|
+
# Results are in a file
|
|
183
|
+
result_file_name = batch_job.dest.file_name
|
|
184
|
+
file_content = client.files.download(file=result_file_name)
|
|
185
|
+
# Process file_content (bytes) as needed
|
|
186
|
+
return file_content.decode('utf-8')
|
|
187
|
+
else:
|
|
188
|
+
raise ValueError("No results found (neither file nor inline).")
|
|
189
|
+
else:
|
|
190
|
+
raise ValueError(f"Job did not succeed. Final state: {batch_job.state.name} ")
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
# Copyright 2025 Google LLC
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
# ==============================================================================
|
|
15
|
+
|
|
16
|
+
from collections.abc import Collection, Mapping, Sequence
|
|
17
|
+
import os
|
|
18
|
+
import time
|
|
19
|
+
|
|
20
|
+
import anthropic
|
|
21
|
+
from anthropic.types.message_create_params import MessageCreateParamsNonStreaming
|
|
22
|
+
from anthropic.types.messages.batch_create_params import Request
|
|
23
|
+
import httpx
|
|
24
|
+
from typing_extensions import override
|
|
25
|
+
from dotenv import load_dotenv
|
|
26
|
+
|
|
27
|
+
from habermas_machine.llm_client import base_client
|
|
28
|
+
from habermas_machine.llm_client import utils
|
|
29
|
+
|
|
30
|
+
class AnthropicClient(base_client.LLMClient):
|
|
31
|
+
"""Language Model that uses Anthropic API."""
|
|
32
|
+
|
|
33
|
+
def __init__(
|
|
34
|
+
self,
|
|
35
|
+
model_name: str,
|
|
36
|
+
*,
|
|
37
|
+
safety_settings: Sequence[Mapping[str, str]] = [],
|
|
38
|
+
) -> None:
|
|
39
|
+
"""Initializes the instance.
|
|
40
|
+
|
|
41
|
+
Args:
|
|
42
|
+
model_name: which language model to use. For more details, see
|
|
43
|
+
https://docs.anthropic.com/.
|
|
44
|
+
"""
|
|
45
|
+
del safety_settings # Anthropic does not support safety settings.
|
|
46
|
+
|
|
47
|
+
load_dotenv()
|
|
48
|
+
|
|
49
|
+
self._api_key = os.environ['ANTHROPIC_API_KEY']
|
|
50
|
+
self._model_name = model_name
|
|
51
|
+
# Widen httpx connection pool so ThreadPoolExecutor parallelism in
|
|
52
|
+
# HabermasMachine.mediate() isn't capped by the default ~20 connection limit.
|
|
53
|
+
self._client = anthropic.Anthropic(
|
|
54
|
+
api_key=self._api_key,
|
|
55
|
+
http_client=httpx.Client(
|
|
56
|
+
limits=httpx.Limits(max_connections=128, max_keepalive_connections=128),
|
|
57
|
+
),
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
@override
|
|
61
|
+
def sample_text(
|
|
62
|
+
self,
|
|
63
|
+
prompt: str,
|
|
64
|
+
*,
|
|
65
|
+
max_tokens: int = base_client.DEFAULT_MAX_TOKENS,
|
|
66
|
+
terminators: Collection[str] = base_client.DEFAULT_TERMINATORS,
|
|
67
|
+
temperature: float = base_client.DEFAULT_TEMPERATURE,
|
|
68
|
+
timeout: float = base_client.DEFAULT_TIMEOUT_SECONDS,
|
|
69
|
+
seed: int | None = None,
|
|
70
|
+
) -> str:
|
|
71
|
+
del timeout
|
|
72
|
+
del seed # Anthropic does not support seeds.
|
|
73
|
+
try:
|
|
74
|
+
sample = self._client.messages.create(
|
|
75
|
+
model = self._model_name,
|
|
76
|
+
max_tokens = max_tokens,
|
|
77
|
+
stop_sequences = terminators,
|
|
78
|
+
# temperature = temperature,
|
|
79
|
+
stream=False,
|
|
80
|
+
messages=[{
|
|
81
|
+
"role": "user",
|
|
82
|
+
"content": prompt
|
|
83
|
+
}]
|
|
84
|
+
)
|
|
85
|
+
response = sample.content[0].text
|
|
86
|
+
except Exception as e:
|
|
87
|
+
print(f"Error in sample_text: {e}")
|
|
88
|
+
print(f"Model: {self._model_name}")
|
|
89
|
+
print(f"Prompt: {prompt}")
|
|
90
|
+
return ""
|
|
91
|
+
return utils.truncate(response, delimiters=terminators)
|
|
92
|
+
|
|
93
|
+
def sample_many(
|
|
94
|
+
self,
|
|
95
|
+
prompts: dict[str, str], # custom_id -> prompt
|
|
96
|
+
*,
|
|
97
|
+
max_tokens: int = base_client.DEFAULT_MAX_TOKENS,
|
|
98
|
+
terminators: Collection[str] = base_client.DEFAULT_TERMINATORS,
|
|
99
|
+
temperature: float = base_client.DEFAULT_TEMPERATURE,
|
|
100
|
+
timeout: float = base_client.DEFAULT_TIMEOUT_SECONDS,
|
|
101
|
+
seed: int | None = None,
|
|
102
|
+
batch_id: str | None = None,
|
|
103
|
+
) -> dict[str, str]:
|
|
104
|
+
"""Same functionality as batch sample but using multiple single requests.
|
|
105
|
+
Use when batch API is taking literally forever.
|
|
106
|
+
"""
|
|
107
|
+
responses = {}
|
|
108
|
+
total = len(prompts)
|
|
109
|
+
for i, (custom_id, prompt) in enumerate(prompts.items(), start=1):
|
|
110
|
+
response = self.sample_text(
|
|
111
|
+
prompt,
|
|
112
|
+
max_tokens=max_tokens,
|
|
113
|
+
terminators=terminators,
|
|
114
|
+
temperature=temperature,
|
|
115
|
+
timeout=timeout,
|
|
116
|
+
seed=seed,
|
|
117
|
+
)
|
|
118
|
+
responses[custom_id] = response
|
|
119
|
+
if i % 20 == 0:
|
|
120
|
+
ts = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
|
|
121
|
+
print(f"[{ts}] Processed {i}/{total} prompts.")
|
|
122
|
+
return responses
|
|
123
|
+
|
|
124
|
+
@override
|
|
125
|
+
def batch_sample_text(
|
|
126
|
+
self,
|
|
127
|
+
prompts: dict[str, str], # custom_id -> prompt
|
|
128
|
+
*,
|
|
129
|
+
max_tokens: int = base_client.DEFAULT_MAX_TOKENS,
|
|
130
|
+
terminators: Collection[str] = base_client.DEFAULT_TERMINATORS,
|
|
131
|
+
temperature: float = base_client.DEFAULT_TEMPERATURE,
|
|
132
|
+
timeout: float = base_client.DEFAULT_TIMEOUT_SECONDS,
|
|
133
|
+
seed: int | None = None,
|
|
134
|
+
batch_id: str | None = None,
|
|
135
|
+
use_batch_api: bool = True,
|
|
136
|
+
) -> dict[str, str]:
|
|
137
|
+
"""
|
|
138
|
+
Batch version of sample_text. Returns a dict of custom_id -> response.
|
|
139
|
+
"""
|
|
140
|
+
|
|
141
|
+
if not use_batch_api:
|
|
142
|
+
print(f"Using sample_many instead of batch API with {len(prompts)} prompts.")
|
|
143
|
+
return self.sample_many(
|
|
144
|
+
prompts,
|
|
145
|
+
max_tokens=max_tokens,
|
|
146
|
+
terminators=terminators,
|
|
147
|
+
temperature=temperature,
|
|
148
|
+
timeout=timeout,
|
|
149
|
+
seed=seed,
|
|
150
|
+
batch_id=batch_id,
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
print(f"Starting batch_sample_text with {len(prompts)} prompts.")
|
|
154
|
+
print(batch_id)
|
|
155
|
+
if batch_id is None:
|
|
156
|
+
requests = [
|
|
157
|
+
Request(
|
|
158
|
+
custom_id=custom_id,
|
|
159
|
+
params=MessageCreateParamsNonStreaming(
|
|
160
|
+
model=self._model_name,
|
|
161
|
+
max_tokens=max_tokens,
|
|
162
|
+
temperature=temperature,
|
|
163
|
+
stop_sequences=terminators,
|
|
164
|
+
messages=[{
|
|
165
|
+
"role": "user",
|
|
166
|
+
"content": prompt,
|
|
167
|
+
}]
|
|
168
|
+
)
|
|
169
|
+
) for custom_id, prompt in prompts.items()
|
|
170
|
+
]
|
|
171
|
+
batch = self._client.messages.batches.create(requests=requests)
|
|
172
|
+
# Wait for batch to finish
|
|
173
|
+
while True:
|
|
174
|
+
batch_status = self._client.messages.batches.retrieve(batch.id)
|
|
175
|
+
if getattr(batch_status, "processing_status", None) == "ended":
|
|
176
|
+
break
|
|
177
|
+
time.sleep(1)
|
|
178
|
+
batch_id = batch.id
|
|
179
|
+
results = self._client.messages.batches.results(batch_id)
|
|
180
|
+
# Map results by custom_id
|
|
181
|
+
result_map = {str(r.custom_id): r for r in results}
|
|
182
|
+
responses = {}
|
|
183
|
+
for custom_id, prompt in prompts.items():
|
|
184
|
+
r = result_map.get(custom_id)
|
|
185
|
+
if r is not None:
|
|
186
|
+
try:
|
|
187
|
+
text = r.result.message.content[0].text
|
|
188
|
+
except Exception as e:
|
|
189
|
+
print(f"Error in batch response for custom_id {custom_id}: {e}")
|
|
190
|
+
text = None
|
|
191
|
+
responses[custom_id] = utils.truncate(text, delimiters=terminators)
|
|
192
|
+
else:
|
|
193
|
+
print(f"Missing response for custom_id {custom_id}")
|
|
194
|
+
responses[custom_id] = None
|
|
195
|
+
return responses
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
# Copyright 2025 Google LLC
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
# ==============================================================================
|
|
15
|
+
|
|
16
|
+
"""Base class for LLM clients."""
|
|
17
|
+
|
|
18
|
+
import abc
|
|
19
|
+
from collections.abc import Collection
|
|
20
|
+
|
|
21
|
+
DEFAULT_TEMPERATURE = 0.8
|
|
22
|
+
DEFAULT_TERMINATORS = ()
|
|
23
|
+
DEFAULT_TIMEOUT_SECONDS = 60
|
|
24
|
+
# Safety-net cap on response length. The CoT statement / ranking prompts emit
|
|
25
|
+
# `</answer>` as a stop sequence well before this, so this only kicks in if a
|
|
26
|
+
# response runs away. Sized to comfortably fit 5 diverse statements in one
|
|
27
|
+
# call (the largest known single output).
|
|
28
|
+
DEFAULT_MAX_TOKENS = 3000
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class LLMClient(abc.ABC):
|
|
32
|
+
"""Language model client base class."""
|
|
33
|
+
|
|
34
|
+
@abc.abstractmethod
|
|
35
|
+
def sample_text(
|
|
36
|
+
self,
|
|
37
|
+
prompt: str,
|
|
38
|
+
*,
|
|
39
|
+
max_tokens: int = DEFAULT_MAX_TOKENS,
|
|
40
|
+
terminators: Collection[str] = DEFAULT_TERMINATORS,
|
|
41
|
+
temperature: float = DEFAULT_TEMPERATURE,
|
|
42
|
+
timeout: float = DEFAULT_TIMEOUT_SECONDS,
|
|
43
|
+
seed: int | None = None,
|
|
44
|
+
) -> str:
|
|
45
|
+
"""Samples text from the model.
|
|
46
|
+
|
|
47
|
+
Args:
|
|
48
|
+
prompt: The input text that the model conditions on.
|
|
49
|
+
max_tokens: The maximum number of tokens in the response.
|
|
50
|
+
terminators: The response will be terminated before any of these
|
|
51
|
+
characters.
|
|
52
|
+
temperature: Model temperature.
|
|
53
|
+
timeout: Timeout for the request.
|
|
54
|
+
seed: Optional seed for the sampling. If None a random seed will be used.
|
|
55
|
+
|
|
56
|
+
Returns:
|
|
57
|
+
The sampled response (i.e. does not include the prompt).
|
|
58
|
+
|
|
59
|
+
Raises:
|
|
60
|
+
TimeoutError: if the operation times out.
|
|
61
|
+
"""
|
|
62
|
+
raise NotImplementedError('sample_text method is not implemented.')
|
|
63
|
+
|
|
64
|
+
@abc.abstractmethod
|
|
65
|
+
def batch_sample_text(
|
|
66
|
+
self,
|
|
67
|
+
prompts: dict[str, str], # custom_id -> prompt
|
|
68
|
+
*,
|
|
69
|
+
max_tokens: int = DEFAULT_MAX_TOKENS,
|
|
70
|
+
terminators: Collection[str] = DEFAULT_TERMINATORS,
|
|
71
|
+
temperature: float = DEFAULT_TEMPERATURE,
|
|
72
|
+
timeout: float = DEFAULT_TIMEOUT_SECONDS,
|
|
73
|
+
seed: int | None = None,
|
|
74
|
+
) -> dict[str, str]:
|
|
75
|
+
"""Batch version of sample_text.
|
|
76
|
+
|
|
77
|
+
Args:
|
|
78
|
+
prompts: A dictionary mapping custom_id to prompt strings.
|
|
79
|
+
max_tokens: The maximum number of tokens in each response.
|
|
80
|
+
terminators: The response will be truncated before any of these strings.
|
|
81
|
+
temperature: Sampling temperature for the model.
|
|
82
|
+
timeout: Timeout for the request in seconds.
|
|
83
|
+
seed: Optional seed for sampling. If None, a random seed will be used.
|
|
84
|
+
|
|
85
|
+
Returns:
|
|
86
|
+
A dictionary mapping custom_id to the model's response string.
|
|
87
|
+
|
|
88
|
+
Raises:
|
|
89
|
+
TimeoutError: If the operation times out.
|
|
90
|
+
NotImplementedError: If the method is not implemented by a subclass.
|
|
91
|
+
"""
|
|
92
|
+
raise NotImplementedError('batch_sample_text method is not implemented.')
|
|
93
|
+
|
|
94
|
+
@property
|
|
95
|
+
def model_name(self):
|
|
96
|
+
"""Public property to access the model name, if implemented by subclass."""
|
|
97
|
+
# Subclasses should set self._model_name
|
|
98
|
+
return getattr(self, '_model_name', None)
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
# Copyright 2025 Google LLC
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
# ==============================================================================
|
|
15
|
+
|
|
16
|
+
"""Mock LLM client that returns a fixed response."""
|
|
17
|
+
|
|
18
|
+
from collections.abc import Collection
|
|
19
|
+
|
|
20
|
+
from typing_extensions import override
|
|
21
|
+
|
|
22
|
+
from habermas_machine.llm_client import base_client
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class MockClient(base_client.LLMClient):
|
|
26
|
+
"""Mock client that returns a fixed response."""
|
|
27
|
+
|
|
28
|
+
def __init__(self, model_name:str, response: str = 'Mock response.'):
|
|
29
|
+
self._response = response
|
|
30
|
+
self._model_name = model_name
|
|
31
|
+
|
|
32
|
+
@override
|
|
33
|
+
def sample_text(
|
|
34
|
+
self,
|
|
35
|
+
prompt: str,
|
|
36
|
+
*,
|
|
37
|
+
max_tokens: int = base_client.DEFAULT_MAX_TOKENS,
|
|
38
|
+
terminators: Collection[str] = base_client.DEFAULT_TERMINATORS,
|
|
39
|
+
temperature: float = base_client.DEFAULT_TEMPERATURE,
|
|
40
|
+
timeout: float = base_client.DEFAULT_TIMEOUT_SECONDS,
|
|
41
|
+
seed: int | None = None,
|
|
42
|
+
) -> str:
|
|
43
|
+
del prompt, max_tokens, terminators, temperature, timeout, seed
|
|
44
|
+
return self._response
|
|
45
|
+
|
|
46
|
+
@override
|
|
47
|
+
def batch_sample_text(
|
|
48
|
+
self,
|
|
49
|
+
prompts: dict[str, str], # custom_id -> prompt
|
|
50
|
+
*,
|
|
51
|
+
max_tokens: int = base_client.DEFAULT_MAX_TOKENS,
|
|
52
|
+
terminators: Collection[str] = base_client.DEFAULT_TERMINATORS,
|
|
53
|
+
temperature: float = base_client.DEFAULT_TEMPERATURE,
|
|
54
|
+
timeout: float = base_client.DEFAULT_TIMEOUT_SECONDS,
|
|
55
|
+
seed: int | None = None,
|
|
56
|
+
use_batch_api: bool = True,
|
|
57
|
+
) -> dict[str, str]:
|
|
58
|
+
del max_tokens, terminators, temperature, timeout, seed
|
|
59
|
+
return {custom_id: self._response for custom_id in prompts}
|