langfun 0.1.2.dev202501090804__py3-none-any.whl → 0.1.2.dev202501100804__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.
- langfun/core/llms/__init__.py +3 -0
- langfun/core/llms/deepseek.py +8 -152
- langfun/core/llms/deepseek_test.py +12 -389
- langfun/core/llms/groq.py +12 -99
- langfun/core/llms/groq_test.py +31 -137
- langfun/core/llms/llama_cpp.py +17 -54
- langfun/core/llms/llama_cpp_test.py +2 -34
- langfun/core/llms/openai.py +9 -147
- langfun/core/llms/openai_compatible.py +179 -0
- langfun/core/llms/openai_compatible_test.py +480 -0
- langfun/core/llms/openai_test.py +13 -423
- langfun/core/modalities/mime.py +8 -0
- langfun/core/modalities/mime_test.py +19 -4
- langfun/core/modality_test.py +0 -1
- {langfun-0.1.2.dev202501090804.dist-info → langfun-0.1.2.dev202501100804.dist-info}/METADATA +1 -1
- {langfun-0.1.2.dev202501090804.dist-info → langfun-0.1.2.dev202501100804.dist-info}/RECORD +19 -17
- {langfun-0.1.2.dev202501090804.dist-info → langfun-0.1.2.dev202501100804.dist-info}/LICENSE +0 -0
- {langfun-0.1.2.dev202501090804.dist-info → langfun-0.1.2.dev202501100804.dist-info}/WHEEL +0 -0
- {langfun-0.1.2.dev202501090804.dist-info → langfun-0.1.2.dev202501100804.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,179 @@
|
|
1
|
+
# Copyright 2025 The Langfun Authors
|
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
|
+
"""Base for OpenAI compatible models (including OpenAI)."""
|
15
|
+
|
16
|
+
from typing import Annotated, Any
|
17
|
+
|
18
|
+
import langfun.core as lf
|
19
|
+
from langfun.core import modalities as lf_modalities
|
20
|
+
from langfun.core.llms import rest
|
21
|
+
import pyglove as pg
|
22
|
+
|
23
|
+
|
24
|
+
@lf.use_init_args(['api_endpoint', 'model'])
|
25
|
+
class OpenAICompatible(rest.REST):
|
26
|
+
"""Base for OpenAI compatible models."""
|
27
|
+
|
28
|
+
model: Annotated[
|
29
|
+
str, 'The name of the model to use.',
|
30
|
+
] = ''
|
31
|
+
|
32
|
+
multimodal: Annotated[
|
33
|
+
bool, 'Whether this model has multimodal support.'
|
34
|
+
] = False
|
35
|
+
|
36
|
+
@property
|
37
|
+
def headers(self) -> dict[str, Any]:
|
38
|
+
return {
|
39
|
+
'Content-Type': 'application/json'
|
40
|
+
}
|
41
|
+
|
42
|
+
def _request_args(
|
43
|
+
self, options: lf.LMSamplingOptions) -> dict[str, Any]:
|
44
|
+
"""Returns a dict as request arguments."""
|
45
|
+
# Reference:
|
46
|
+
# https://platform.openai.com/docs/api-reference/completions/create
|
47
|
+
# NOTE(daiyip): options.top_k is not applicable.
|
48
|
+
args = dict(
|
49
|
+
n=options.n,
|
50
|
+
top_logprobs=options.top_logprobs,
|
51
|
+
)
|
52
|
+
if self.model:
|
53
|
+
args['model'] = self.model
|
54
|
+
if options.logprobs:
|
55
|
+
args['logprobs'] = options.logprobs
|
56
|
+
if options.temperature is not None:
|
57
|
+
args['temperature'] = options.temperature
|
58
|
+
if options.max_tokens is not None:
|
59
|
+
args['max_completion_tokens'] = options.max_tokens
|
60
|
+
if options.top_p is not None:
|
61
|
+
args['top_p'] = options.top_p
|
62
|
+
if options.stop:
|
63
|
+
args['stop'] = options.stop
|
64
|
+
if options.random_seed is not None:
|
65
|
+
args['seed'] = options.random_seed
|
66
|
+
return args
|
67
|
+
|
68
|
+
def _content_from_message(self, message: lf.Message) -> list[dict[str, Any]]:
|
69
|
+
"""Returns a OpenAI content object from a Langfun message."""
|
70
|
+
content = []
|
71
|
+
for chunk in message.chunk():
|
72
|
+
if isinstance(chunk, str):
|
73
|
+
item = dict(type='text', text=chunk)
|
74
|
+
elif isinstance(chunk, lf_modalities.Image) and self.multimodal:
|
75
|
+
item = dict(type='image_url', image_url=dict(url=chunk.embeddable_uri))
|
76
|
+
else:
|
77
|
+
raise ValueError(f'Unsupported modality: {chunk!r}.')
|
78
|
+
content.append(item)
|
79
|
+
return content
|
80
|
+
|
81
|
+
def request(
|
82
|
+
self,
|
83
|
+
prompt: lf.Message,
|
84
|
+
sampling_options: lf.LMSamplingOptions
|
85
|
+
) -> dict[str, Any]:
|
86
|
+
"""Returns the JSON input for a message."""
|
87
|
+
request_args = self._request_args(sampling_options)
|
88
|
+
|
89
|
+
# Users could use `metadata_json_schema` to pass additional
|
90
|
+
# request arguments.
|
91
|
+
json_schema = prompt.metadata.get('json_schema')
|
92
|
+
if json_schema is not None:
|
93
|
+
if not isinstance(json_schema, dict):
|
94
|
+
raise ValueError(
|
95
|
+
f'`json_schema` must be a dict, got {json_schema!r}.'
|
96
|
+
)
|
97
|
+
if 'title' not in json_schema:
|
98
|
+
raise ValueError(
|
99
|
+
f'The root of `json_schema` must have a `title` field, '
|
100
|
+
f'got {json_schema!r}.'
|
101
|
+
)
|
102
|
+
request_args.update(
|
103
|
+
response_format=dict(
|
104
|
+
type='json_schema',
|
105
|
+
json_schema=dict(
|
106
|
+
schema=json_schema,
|
107
|
+
name=json_schema['title'],
|
108
|
+
strict=True,
|
109
|
+
)
|
110
|
+
)
|
111
|
+
)
|
112
|
+
prompt.metadata.formatted_text = (
|
113
|
+
prompt.text
|
114
|
+
+ '\n\n [RESPONSE FORMAT (not part of prompt)]\n'
|
115
|
+
+ pg.to_json_str(request_args['response_format'], json_indent=2)
|
116
|
+
)
|
117
|
+
|
118
|
+
# Prepare messages.
|
119
|
+
messages = []
|
120
|
+
# Users could use `metadata_system_message` to pass system message.
|
121
|
+
system_message = prompt.metadata.get('system_message')
|
122
|
+
if system_message:
|
123
|
+
system_message = lf.SystemMessage.from_value(system_message)
|
124
|
+
messages.append(
|
125
|
+
dict(role='system',
|
126
|
+
content=self._content_from_message(system_message))
|
127
|
+
)
|
128
|
+
messages.append(
|
129
|
+
dict(role='user', content=self._content_from_message(prompt))
|
130
|
+
)
|
131
|
+
request = dict()
|
132
|
+
request.update(request_args)
|
133
|
+
request['messages'] = messages
|
134
|
+
return request
|
135
|
+
|
136
|
+
def _parse_choice(self, choice: dict[str, Any]) -> lf.LMSample:
|
137
|
+
# Reference:
|
138
|
+
# https://platform.openai.com/docs/api-reference/chat/object
|
139
|
+
logprobs = None
|
140
|
+
choice_logprobs = choice.get('logprobs')
|
141
|
+
if choice_logprobs:
|
142
|
+
logprobs = [
|
143
|
+
(
|
144
|
+
t['token'],
|
145
|
+
t['logprob'],
|
146
|
+
[(tt['token'], tt['logprob']) for tt in t['top_logprobs']],
|
147
|
+
)
|
148
|
+
for t in choice_logprobs['content']
|
149
|
+
]
|
150
|
+
return lf.LMSample(
|
151
|
+
choice['message']['content'],
|
152
|
+
score=0.0,
|
153
|
+
logprobs=logprobs,
|
154
|
+
)
|
155
|
+
|
156
|
+
def result(self, json: dict[str, Any]) -> lf.LMSamplingResult:
|
157
|
+
"""Returns a LMSamplingResult from a JSON response."""
|
158
|
+
usage = json['usage']
|
159
|
+
return lf.LMSamplingResult(
|
160
|
+
samples=[self._parse_choice(choice) for choice in json['choices']],
|
161
|
+
usage=lf.LMSamplingUsage(
|
162
|
+
prompt_tokens=usage['prompt_tokens'],
|
163
|
+
completion_tokens=usage['completion_tokens'],
|
164
|
+
total_tokens=usage['total_tokens'],
|
165
|
+
estimated_cost=self.estimate_cost(
|
166
|
+
num_input_tokens=usage['prompt_tokens'],
|
167
|
+
num_output_tokens=usage['completion_tokens'],
|
168
|
+
)
|
169
|
+
),
|
170
|
+
)
|
171
|
+
|
172
|
+
def estimate_cost(
|
173
|
+
self,
|
174
|
+
num_input_tokens: int,
|
175
|
+
num_output_tokens: int
|
176
|
+
) -> float | None:
|
177
|
+
"""Estimate the cost based on usage."""
|
178
|
+
del num_input_tokens, num_output_tokens
|
179
|
+
return None
|
@@ -0,0 +1,480 @@
|
|
1
|
+
# Copyright 2023 The Langfun Authors
|
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
|
+
"""Tests for OpenAI models."""
|
15
|
+
|
16
|
+
from typing import Any
|
17
|
+
import unittest
|
18
|
+
from unittest import mock
|
19
|
+
|
20
|
+
import langfun.core as lf
|
21
|
+
from langfun.core import modalities as lf_modalities
|
22
|
+
from langfun.core.llms import openai_compatible
|
23
|
+
import pyglove as pg
|
24
|
+
import requests
|
25
|
+
|
26
|
+
|
27
|
+
def mock_chat_completion_request(url: str, json: dict[str, Any], **kwargs):
|
28
|
+
del url, kwargs
|
29
|
+
messages = json['messages']
|
30
|
+
if len(messages) > 1:
|
31
|
+
system_message = f' system={messages[0]["content"]}'
|
32
|
+
else:
|
33
|
+
system_message = ''
|
34
|
+
|
35
|
+
if 'response_format' in json:
|
36
|
+
response_format = f' format={json["response_format"]["type"]}'
|
37
|
+
else:
|
38
|
+
response_format = ''
|
39
|
+
|
40
|
+
choices = []
|
41
|
+
for k in range(json['n']):
|
42
|
+
if json.get('logprobs'):
|
43
|
+
logprobs = dict(
|
44
|
+
content=[
|
45
|
+
dict(
|
46
|
+
token='chosen_token',
|
47
|
+
logprob=0.5,
|
48
|
+
top_logprobs=[
|
49
|
+
dict(
|
50
|
+
token=f'alternative_token_{i + 1}',
|
51
|
+
logprob=0.1
|
52
|
+
) for i in range(3)
|
53
|
+
]
|
54
|
+
)
|
55
|
+
]
|
56
|
+
)
|
57
|
+
else:
|
58
|
+
logprobs = None
|
59
|
+
|
60
|
+
choices.append(dict(
|
61
|
+
message=dict(
|
62
|
+
content=(
|
63
|
+
f'Sample {k} for message.{system_message}{response_format}'
|
64
|
+
)
|
65
|
+
),
|
66
|
+
logprobs=logprobs,
|
67
|
+
))
|
68
|
+
response = requests.Response()
|
69
|
+
response.status_code = 200
|
70
|
+
response._content = pg.to_json_str(
|
71
|
+
dict(
|
72
|
+
choices=choices,
|
73
|
+
usage=lf.LMSamplingUsage(
|
74
|
+
prompt_tokens=100,
|
75
|
+
completion_tokens=100,
|
76
|
+
total_tokens=200,
|
77
|
+
),
|
78
|
+
)
|
79
|
+
).encode()
|
80
|
+
return response
|
81
|
+
|
82
|
+
|
83
|
+
def mock_chat_completion_request_vision(
|
84
|
+
url: str, json: dict[str, Any], **kwargs
|
85
|
+
):
|
86
|
+
del url, kwargs
|
87
|
+
choices = []
|
88
|
+
urls = [
|
89
|
+
c['image_url']['url']
|
90
|
+
for c in json['messages'][0]['content'] if c['type'] == 'image_url'
|
91
|
+
]
|
92
|
+
for k in range(json['n']):
|
93
|
+
choices.append(pg.Dict(
|
94
|
+
message=pg.Dict(
|
95
|
+
content=f'Sample {k} for message: {"".join(urls)}'
|
96
|
+
),
|
97
|
+
logprobs=None,
|
98
|
+
))
|
99
|
+
response = requests.Response()
|
100
|
+
response.status_code = 200
|
101
|
+
response._content = pg.to_json_str(
|
102
|
+
dict(
|
103
|
+
choices=choices,
|
104
|
+
usage=lf.LMSamplingUsage(
|
105
|
+
prompt_tokens=100,
|
106
|
+
completion_tokens=100,
|
107
|
+
total_tokens=200,
|
108
|
+
),
|
109
|
+
)
|
110
|
+
).encode()
|
111
|
+
return response
|
112
|
+
|
113
|
+
|
114
|
+
class OpenAIComptibleTest(unittest.TestCase):
|
115
|
+
"""Tests for OpenAI compatible language model."""
|
116
|
+
|
117
|
+
def test_request_args(self):
|
118
|
+
self.assertEqual(
|
119
|
+
openai_compatible.OpenAICompatible(
|
120
|
+
api_endpoint='https://test-server',
|
121
|
+
model='test-model'
|
122
|
+
)._request_args(
|
123
|
+
lf.LMSamplingOptions(
|
124
|
+
temperature=1.0, stop=['\n'], n=1, random_seed=123
|
125
|
+
)
|
126
|
+
),
|
127
|
+
dict(
|
128
|
+
model='test-model',
|
129
|
+
top_logprobs=None,
|
130
|
+
n=1,
|
131
|
+
temperature=1.0,
|
132
|
+
stop=['\n'],
|
133
|
+
seed=123,
|
134
|
+
),
|
135
|
+
)
|
136
|
+
|
137
|
+
def test_call_chat_completion(self):
|
138
|
+
with mock.patch('requests.Session.post') as mock_request:
|
139
|
+
mock_request.side_effect = mock_chat_completion_request
|
140
|
+
lm = openai_compatible.OpenAICompatible(
|
141
|
+
api_endpoint='https://test-server', model='test-model',
|
142
|
+
)
|
143
|
+
self.assertEqual(
|
144
|
+
lm('hello', sampling_options=lf.LMSamplingOptions(n=2)),
|
145
|
+
'Sample 0 for message.',
|
146
|
+
)
|
147
|
+
|
148
|
+
def test_call_chat_completion_with_logprobs(self):
|
149
|
+
with mock.patch('requests.Session.post') as mock_request:
|
150
|
+
mock_request.side_effect = mock_chat_completion_request
|
151
|
+
lm = openai_compatible.OpenAICompatible(
|
152
|
+
api_endpoint='https://test-server', model='test-model',
|
153
|
+
)
|
154
|
+
results = lm.sample(['hello'], logprobs=True)
|
155
|
+
self.assertEqual(len(results), 1)
|
156
|
+
self.assertEqual(
|
157
|
+
results[0],
|
158
|
+
lf.LMSamplingResult(
|
159
|
+
[
|
160
|
+
lf.LMSample(
|
161
|
+
response=lf.AIMessage(
|
162
|
+
text='Sample 0 for message.',
|
163
|
+
metadata={
|
164
|
+
'score': 0.0,
|
165
|
+
'logprobs': [(
|
166
|
+
'chosen_token',
|
167
|
+
0.5,
|
168
|
+
[
|
169
|
+
('alternative_token_1', 0.1),
|
170
|
+
('alternative_token_2', 0.1),
|
171
|
+
('alternative_token_3', 0.1),
|
172
|
+
],
|
173
|
+
)],
|
174
|
+
'is_cached': False,
|
175
|
+
'usage': lf.LMSamplingUsage(
|
176
|
+
prompt_tokens=100,
|
177
|
+
completion_tokens=100,
|
178
|
+
total_tokens=200,
|
179
|
+
estimated_cost=None,
|
180
|
+
),
|
181
|
+
},
|
182
|
+
tags=['lm-response'],
|
183
|
+
),
|
184
|
+
logprobs=[(
|
185
|
+
'chosen_token',
|
186
|
+
0.5,
|
187
|
+
[
|
188
|
+
('alternative_token_1', 0.1),
|
189
|
+
('alternative_token_2', 0.1),
|
190
|
+
('alternative_token_3', 0.1),
|
191
|
+
],
|
192
|
+
)],
|
193
|
+
)
|
194
|
+
],
|
195
|
+
usage=lf.LMSamplingUsage(
|
196
|
+
prompt_tokens=100,
|
197
|
+
completion_tokens=100,
|
198
|
+
total_tokens=200,
|
199
|
+
estimated_cost=None,
|
200
|
+
),
|
201
|
+
),
|
202
|
+
)
|
203
|
+
|
204
|
+
def test_call_chat_completion_vision(self):
|
205
|
+
with mock.patch('requests.Session.post') as mock_request:
|
206
|
+
mock_request.side_effect = mock_chat_completion_request_vision
|
207
|
+
lm_1 = openai_compatible.OpenAICompatible(
|
208
|
+
api_endpoint='https://test-server',
|
209
|
+
model='test-model1',
|
210
|
+
multimodal=True
|
211
|
+
)
|
212
|
+
lm_2 = openai_compatible.OpenAICompatible(
|
213
|
+
api_endpoint='https://test-server',
|
214
|
+
model='test-model2',
|
215
|
+
multimodal=True
|
216
|
+
)
|
217
|
+
for lm in (lm_1, lm_2):
|
218
|
+
self.assertEqual(
|
219
|
+
lm(
|
220
|
+
lf.UserMessage(
|
221
|
+
'hello <<[[image]]>>',
|
222
|
+
image=lf_modalities.Image.from_uri('https://fake/image')
|
223
|
+
),
|
224
|
+
sampling_options=lf.LMSamplingOptions(n=2)
|
225
|
+
),
|
226
|
+
'Sample 0 for message: https://fake/image',
|
227
|
+
)
|
228
|
+
lm_3 = openai_compatible.OpenAICompatible(
|
229
|
+
api_endpoint='https://test-server', model='test-model3'
|
230
|
+
)
|
231
|
+
with self.assertRaisesRegex(ValueError, 'Unsupported modality'):
|
232
|
+
lm_3(
|
233
|
+
lf.UserMessage(
|
234
|
+
'hello <<[[image]]>>',
|
235
|
+
image=lf_modalities.Image.from_uri('https://fake/image')
|
236
|
+
),
|
237
|
+
)
|
238
|
+
|
239
|
+
def test_sample_chat_completion(self):
|
240
|
+
with mock.patch('requests.Session.post') as mock_request:
|
241
|
+
mock_request.side_effect = mock_chat_completion_request
|
242
|
+
lm = openai_compatible.OpenAICompatible(
|
243
|
+
api_endpoint='https://test-server', model='test-model'
|
244
|
+
)
|
245
|
+
results = lm.sample(
|
246
|
+
['hello', 'bye'], sampling_options=lf.LMSamplingOptions(n=3)
|
247
|
+
)
|
248
|
+
|
249
|
+
self.assertEqual(len(results), 2)
|
250
|
+
self.assertEqual(
|
251
|
+
results[0],
|
252
|
+
lf.LMSamplingResult(
|
253
|
+
[
|
254
|
+
lf.LMSample(
|
255
|
+
lf.AIMessage(
|
256
|
+
'Sample 0 for message.',
|
257
|
+
score=0.0,
|
258
|
+
logprobs=None,
|
259
|
+
is_cached=False,
|
260
|
+
usage=lf.LMSamplingUsage(
|
261
|
+
prompt_tokens=33,
|
262
|
+
completion_tokens=33,
|
263
|
+
total_tokens=66,
|
264
|
+
estimated_cost=None,
|
265
|
+
),
|
266
|
+
tags=[lf.Message.TAG_LM_RESPONSE],
|
267
|
+
),
|
268
|
+
score=0.0,
|
269
|
+
logprobs=None,
|
270
|
+
),
|
271
|
+
lf.LMSample(
|
272
|
+
lf.AIMessage(
|
273
|
+
'Sample 1 for message.',
|
274
|
+
score=0.0,
|
275
|
+
logprobs=None,
|
276
|
+
is_cached=False,
|
277
|
+
usage=lf.LMSamplingUsage(
|
278
|
+
prompt_tokens=33,
|
279
|
+
completion_tokens=33,
|
280
|
+
total_tokens=66,
|
281
|
+
estimated_cost=None,
|
282
|
+
),
|
283
|
+
tags=[lf.Message.TAG_LM_RESPONSE],
|
284
|
+
),
|
285
|
+
score=0.0,
|
286
|
+
logprobs=None,
|
287
|
+
),
|
288
|
+
lf.LMSample(
|
289
|
+
lf.AIMessage(
|
290
|
+
'Sample 2 for message.',
|
291
|
+
score=0.0,
|
292
|
+
logprobs=None,
|
293
|
+
is_cached=False,
|
294
|
+
usage=lf.LMSamplingUsage(
|
295
|
+
prompt_tokens=33,
|
296
|
+
completion_tokens=33,
|
297
|
+
total_tokens=66,
|
298
|
+
estimated_cost=None,
|
299
|
+
),
|
300
|
+
tags=[lf.Message.TAG_LM_RESPONSE],
|
301
|
+
),
|
302
|
+
score=0.0,
|
303
|
+
logprobs=None,
|
304
|
+
),
|
305
|
+
],
|
306
|
+
usage=lf.LMSamplingUsage(
|
307
|
+
prompt_tokens=100, completion_tokens=100, total_tokens=200,
|
308
|
+
estimated_cost=None,
|
309
|
+
),
|
310
|
+
),
|
311
|
+
)
|
312
|
+
self.assertEqual(
|
313
|
+
results[1],
|
314
|
+
lf.LMSamplingResult(
|
315
|
+
[
|
316
|
+
lf.LMSample(
|
317
|
+
lf.AIMessage(
|
318
|
+
'Sample 0 for message.',
|
319
|
+
score=0.0,
|
320
|
+
logprobs=None,
|
321
|
+
is_cached=False,
|
322
|
+
usage=lf.LMSamplingUsage(
|
323
|
+
prompt_tokens=33,
|
324
|
+
completion_tokens=33,
|
325
|
+
total_tokens=66,
|
326
|
+
estimated_cost=None,
|
327
|
+
),
|
328
|
+
tags=[lf.Message.TAG_LM_RESPONSE],
|
329
|
+
),
|
330
|
+
score=0.0,
|
331
|
+
logprobs=None,
|
332
|
+
),
|
333
|
+
lf.LMSample(
|
334
|
+
lf.AIMessage(
|
335
|
+
'Sample 1 for message.',
|
336
|
+
score=0.0,
|
337
|
+
logprobs=None,
|
338
|
+
is_cached=False,
|
339
|
+
usage=lf.LMSamplingUsage(
|
340
|
+
prompt_tokens=33,
|
341
|
+
completion_tokens=33,
|
342
|
+
total_tokens=66,
|
343
|
+
estimated_cost=None,
|
344
|
+
),
|
345
|
+
tags=[lf.Message.TAG_LM_RESPONSE],
|
346
|
+
),
|
347
|
+
score=0.0,
|
348
|
+
logprobs=None,
|
349
|
+
),
|
350
|
+
lf.LMSample(
|
351
|
+
lf.AIMessage(
|
352
|
+
'Sample 2 for message.',
|
353
|
+
score=0.0,
|
354
|
+
logprobs=None,
|
355
|
+
is_cached=False,
|
356
|
+
usage=lf.LMSamplingUsage(
|
357
|
+
prompt_tokens=33,
|
358
|
+
completion_tokens=33,
|
359
|
+
total_tokens=66,
|
360
|
+
estimated_cost=None,
|
361
|
+
),
|
362
|
+
tags=[lf.Message.TAG_LM_RESPONSE],
|
363
|
+
),
|
364
|
+
score=0.0,
|
365
|
+
logprobs=None,
|
366
|
+
),
|
367
|
+
],
|
368
|
+
usage=lf.LMSamplingUsage(
|
369
|
+
prompt_tokens=100, completion_tokens=100, total_tokens=200,
|
370
|
+
estimated_cost=None,
|
371
|
+
),
|
372
|
+
),
|
373
|
+
)
|
374
|
+
|
375
|
+
def test_sample_with_contextual_options(self):
|
376
|
+
with mock.patch('requests.Session.post') as mock_request:
|
377
|
+
mock_request.side_effect = mock_chat_completion_request
|
378
|
+
lm = openai_compatible.OpenAICompatible(
|
379
|
+
api_endpoint='https://test-server', model='test-model'
|
380
|
+
)
|
381
|
+
with lf.use_settings(sampling_options=lf.LMSamplingOptions(n=2)):
|
382
|
+
results = lm.sample(['hello'])
|
383
|
+
|
384
|
+
self.assertEqual(len(results), 1)
|
385
|
+
self.assertEqual(
|
386
|
+
results[0],
|
387
|
+
lf.LMSamplingResult(
|
388
|
+
[
|
389
|
+
lf.LMSample(
|
390
|
+
lf.AIMessage(
|
391
|
+
'Sample 0 for message.',
|
392
|
+
score=0.0,
|
393
|
+
logprobs=None,
|
394
|
+
is_cached=False,
|
395
|
+
usage=lf.LMSamplingUsage(
|
396
|
+
prompt_tokens=50,
|
397
|
+
completion_tokens=50,
|
398
|
+
total_tokens=100,
|
399
|
+
),
|
400
|
+
tags=[lf.Message.TAG_LM_RESPONSE],
|
401
|
+
),
|
402
|
+
score=0.0,
|
403
|
+
logprobs=None,
|
404
|
+
),
|
405
|
+
lf.LMSample(
|
406
|
+
lf.AIMessage(
|
407
|
+
'Sample 1 for message.',
|
408
|
+
score=0.0,
|
409
|
+
logprobs=None,
|
410
|
+
is_cached=False,
|
411
|
+
usage=lf.LMSamplingUsage(
|
412
|
+
prompt_tokens=50,
|
413
|
+
completion_tokens=50,
|
414
|
+
total_tokens=100,
|
415
|
+
),
|
416
|
+
tags=[lf.Message.TAG_LM_RESPONSE],
|
417
|
+
),
|
418
|
+
score=0.0,
|
419
|
+
logprobs=None,
|
420
|
+
),
|
421
|
+
],
|
422
|
+
usage=lf.LMSamplingUsage(
|
423
|
+
prompt_tokens=100, completion_tokens=100, total_tokens=200
|
424
|
+
),
|
425
|
+
)
|
426
|
+
)
|
427
|
+
|
428
|
+
def test_call_with_system_message(self):
|
429
|
+
with mock.patch('requests.Session.post') as mock_request:
|
430
|
+
mock_request.side_effect = mock_chat_completion_request
|
431
|
+
lm = openai_compatible.OpenAICompatible(
|
432
|
+
api_endpoint='https://test-server', model='test-model'
|
433
|
+
)
|
434
|
+
self.assertEqual(
|
435
|
+
lm(
|
436
|
+
lf.UserMessage(
|
437
|
+
'hello',
|
438
|
+
system_message='hi',
|
439
|
+
),
|
440
|
+
sampling_options=lf.LMSamplingOptions(n=2)
|
441
|
+
),
|
442
|
+
'''Sample 0 for message. system=[{'type': 'text', 'text': 'hi'}]''',
|
443
|
+
)
|
444
|
+
|
445
|
+
def test_call_with_json_schema(self):
|
446
|
+
with mock.patch('requests.Session.post') as mock_request:
|
447
|
+
mock_request.side_effect = mock_chat_completion_request
|
448
|
+
lm = openai_compatible.OpenAICompatible(
|
449
|
+
api_endpoint='https://test-server', model='test-model'
|
450
|
+
)
|
451
|
+
self.assertEqual(
|
452
|
+
lm(
|
453
|
+
lf.UserMessage(
|
454
|
+
'hello',
|
455
|
+
json_schema={
|
456
|
+
'type': 'object',
|
457
|
+
'properties': {
|
458
|
+
'name': {'type': 'string'},
|
459
|
+
},
|
460
|
+
'required': ['name'],
|
461
|
+
'title': 'Person',
|
462
|
+
}
|
463
|
+
),
|
464
|
+
sampling_options=lf.LMSamplingOptions(n=2)
|
465
|
+
),
|
466
|
+
'Sample 0 for message. format=json_schema',
|
467
|
+
)
|
468
|
+
|
469
|
+
# Test bad json schema.
|
470
|
+
with self.assertRaisesRegex(ValueError, '`json_schema` must be a dict'):
|
471
|
+
lm(lf.UserMessage('hello', json_schema='foo'))
|
472
|
+
|
473
|
+
with self.assertRaisesRegex(
|
474
|
+
ValueError, 'The root of `json_schema` must have a `title` field'
|
475
|
+
):
|
476
|
+
lm(lf.UserMessage('hello', json_schema={}))
|
477
|
+
|
478
|
+
|
479
|
+
if __name__ == '__main__':
|
480
|
+
unittest.main()
|