langfun 0.0.2.dev20240330__py3-none-any.whl → 0.0.2.dev20240429__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.
Files changed (49) hide show
  1. langfun/__init__.py +2 -0
  2. langfun/core/__init__.py +1 -0
  3. langfun/core/coding/python/correction.py +0 -7
  4. langfun/core/component.py +6 -0
  5. langfun/core/component_test.py +1 -0
  6. langfun/core/eval/__init__.py +2 -0
  7. langfun/core/eval/base.py +202 -23
  8. langfun/core/eval/base_test.py +49 -10
  9. langfun/core/eval/matching.py +26 -9
  10. langfun/core/eval/matching_test.py +2 -1
  11. langfun/core/eval/scoring.py +15 -6
  12. langfun/core/eval/scoring_test.py +2 -1
  13. langfun/core/langfunc.py +0 -5
  14. langfun/core/langfunc_test.py +6 -4
  15. langfun/core/language_model.py +124 -24
  16. langfun/core/language_model_test.py +249 -26
  17. langfun/core/llms/__init__.py +19 -2
  18. langfun/core/llms/anthropic.py +263 -0
  19. langfun/core/llms/anthropic_test.py +167 -0
  20. langfun/core/llms/cache/in_memory_test.py +37 -28
  21. langfun/core/llms/fake.py +31 -22
  22. langfun/core/llms/fake_test.py +122 -11
  23. langfun/core/llms/google_genai_test.py +8 -3
  24. langfun/core/llms/groq.py +260 -0
  25. langfun/core/llms/groq_test.py +170 -0
  26. langfun/core/llms/llama_cpp.py +3 -1
  27. langfun/core/llms/openai.py +97 -79
  28. langfun/core/llms/openai_test.py +285 -59
  29. langfun/core/modalities/video.py +5 -2
  30. langfun/core/structured/__init__.py +3 -0
  31. langfun/core/structured/completion_test.py +2 -2
  32. langfun/core/structured/function_generation.py +245 -0
  33. langfun/core/structured/function_generation_test.py +329 -0
  34. langfun/core/structured/mapping.py +56 -2
  35. langfun/core/structured/mapping_test.py +17 -0
  36. langfun/core/structured/parsing_test.py +18 -13
  37. langfun/core/structured/prompting.py +27 -6
  38. langfun/core/structured/prompting_test.py +79 -12
  39. langfun/core/structured/schema.py +4 -2
  40. langfun/core/structured/schema_generation_test.py +2 -2
  41. langfun/core/structured/schema_test.py +4 -6
  42. langfun/core/template.py +125 -10
  43. langfun/core/template_test.py +75 -0
  44. langfun/core/templates/selfplay_test.py +6 -2
  45. {langfun-0.0.2.dev20240330.dist-info → langfun-0.0.2.dev20240429.dist-info}/METADATA +3 -2
  46. {langfun-0.0.2.dev20240330.dist-info → langfun-0.0.2.dev20240429.dist-info}/RECORD +49 -43
  47. {langfun-0.0.2.dev20240330.dist-info → langfun-0.0.2.dev20240429.dist-info}/LICENSE +0 -0
  48. {langfun-0.0.2.dev20240330.dist-info → langfun-0.0.2.dev20240429.dist-info}/WHEEL +0 -0
  49. {langfun-0.0.2.dev20240330.dist-info → langfun-0.0.2.dev20240429.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,167 @@
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 Anthropic models."""
15
+
16
+ import base64
17
+ import os
18
+ from typing import Any
19
+ import unittest
20
+ from unittest import mock
21
+ from langfun.core import modalities as lf_modalities
22
+ from langfun.core.llms import anthropic
23
+ import pyglove as pg
24
+ import requests
25
+
26
+
27
+ def mock_requests_post(url: str, json: dict[str, Any], **kwargs):
28
+ del url, kwargs
29
+
30
+ response = requests.Response()
31
+ response.status_code = 200
32
+ response._content = pg.to_json_str({
33
+ 'content': [{
34
+ 'type': 'text',
35
+ 'text': (
36
+ f'hello with temperature={json.get("temperature")}, '
37
+ f'top_k={json.get("top_k")}, '
38
+ f'top_p={json.get("top_p")}, '
39
+ f'max_tokens={json.get("max_tokens")}, '
40
+ f'stop={json.get("stop_sequences")}.'
41
+ ),
42
+ }],
43
+ 'usage': {
44
+ 'input_tokens': 2,
45
+ 'output_tokens': 1,
46
+ },
47
+ }).encode()
48
+ return response
49
+
50
+
51
+ image_content = (
52
+ b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x18\x00\x00\x00\x18\x04'
53
+ b'\x03\x00\x00\x00\x12Y \xcb\x00\x00\x00\x18PLTE\x00\x00'
54
+ b'\x00fff_chaag_cg_ch^ci_ciC\xedb\x94\x00\x00\x00\x08tRNS'
55
+ b'\x00\n\x9f*\xd4\xff_\xf4\xe4\x8b\xf3a\x00\x00\x00>IDATx'
56
+ b'\x01c \x05\x08)"\xd8\xcc\xae!\x06pNz\x88k\x19\\Q\xa8"\x10'
57
+ b'\xc1\x14\x95\x01%\xc1\n\xa143Ta\xa8"D-\x84\x03QM\x98\xc3'
58
+ b'\x1a\x1a\x1a@5\x0e\x04\xa0q\x88\x05\x00\x07\xf8\x18\xf9'
59
+ b'\xdao\xd0|\x00\x00\x00\x00IEND\xaeB`\x82'
60
+ )
61
+
62
+
63
+ def mock_mm_requests_post(url: str, json: dict[str, Any], **kwargs):
64
+ del url, kwargs
65
+ v = json['messages'][0]['content'][0]
66
+ image = lf_modalities.Image.from_bytes(base64.b64decode(v['source']['data']))
67
+
68
+ response = requests.Response()
69
+ response.status_code = 200
70
+ response._content = pg.to_json_str({
71
+ 'content': [{
72
+ 'type': 'text',
73
+ 'text': f'{v["type"]}: {image.mime_type}',
74
+ }],
75
+ 'usage': {
76
+ 'input_tokens': 2,
77
+ 'output_tokens': 1,
78
+ },
79
+ }).encode()
80
+ return response
81
+
82
+
83
+ def mock_requests_post_error(status_code, error_type, error_message):
84
+ def _mock_requests(url: str, json: dict[str, Any], **kwargs):
85
+ del url, json, kwargs
86
+ response = requests.Response()
87
+ response.status_code = status_code
88
+ response._content = pg.to_json_str(
89
+ {
90
+ 'error': {
91
+ 'type': error_type,
92
+ 'message': error_message,
93
+ }
94
+ }
95
+ ).encode()
96
+ return response
97
+
98
+ return _mock_requests
99
+
100
+
101
+ class AnthropicTest(unittest.TestCase):
102
+
103
+ def test_basics(self):
104
+ self.assertEqual(
105
+ anthropic.Claude3Haiku().model_id, 'claude-3-haiku-20240307'
106
+ )
107
+ self.assertGreater(anthropic.Claude3Haiku().max_concurrency, 0)
108
+
109
+ def test_api_key(self):
110
+ lm = anthropic.Claude3Haiku()
111
+ with self.assertRaisesRegex(ValueError, 'Please specify `api_key`'):
112
+ lm('hi')
113
+
114
+ with mock.patch('requests.Session.post') as mock_request:
115
+ mock_request.side_effect = mock_requests_post
116
+
117
+ lm = anthropic.Claude3Haiku(api_key='fake key')
118
+ self.assertRegex(lm('hi').text, 'hello.*')
119
+
120
+ os.environ['ANTHROPIC_API_KEY'] = 'abc'
121
+ lm = anthropic.Claude3Haiku()
122
+ self.assertRegex(lm('hi').text, 'hello.*')
123
+ del os.environ['ANTHROPIC_API_KEY']
124
+
125
+ def test_call(self):
126
+ with mock.patch('requests.Session.post') as mock_request:
127
+ mock_request.side_effect = mock_requests_post
128
+ lm = anthropic.Claude3Haiku(api_key='fake_key')
129
+ response = lm('hello', temperature=0.0, top_k=0.1, top_p=0.2, stop=['\n'])
130
+ self.assertEqual(
131
+ response.text,
132
+ (
133
+ 'hello with temperature=0.0, top_k=0.1, top_p=0.2, '
134
+ "max_tokens=4096, stop=['\\n']."
135
+ ),
136
+ )
137
+ self.assertIsNotNone(response.usage)
138
+ self.assertIsNotNone(response.usage.prompt_tokens, 2)
139
+ self.assertIsNotNone(response.usage.completion_tokens, 1)
140
+ self.assertIsNotNone(response.usage.total_tokens, 3)
141
+
142
+ def test_mm_call(self):
143
+ with mock.patch('requests.Session.post') as mock_mm_request:
144
+ mock_mm_request.side_effect = mock_mm_requests_post
145
+ lm = anthropic.Claude3Haiku(api_key='fake_key')
146
+ response = lm(lf_modalities.Image.from_bytes(image_content), lm=lm)
147
+ self.assertEqual(response.text, 'image: image/png')
148
+
149
+ def test_call_errors(self):
150
+ for status_code, error_type, error_message in [
151
+ (429, 'rate_limit', 'Rate limit exceeded.'),
152
+ (529, 'service_unavailable', 'Service unavailable.'),
153
+ (500, 'bad_request', 'Bad request.'),
154
+ ]:
155
+ with mock.patch('requests.Session.post') as mock_mm_request:
156
+ mock_mm_request.side_effect = mock_requests_post_error(
157
+ status_code, error_type, error_message
158
+ )
159
+ lm = anthropic.Claude3Haiku(api_key='fake_key')
160
+ with self.assertRaisesRegex(
161
+ Exception, f'.*{status_code}: .*{error_message}'
162
+ ):
163
+ lm('hello', lm=lm, max_attempts=1)
164
+
165
+
166
+ if __name__ == '__main__':
167
+ unittest.main()
@@ -44,28 +44,37 @@ class InMemoryLMCacheTest(unittest.TestCase):
44
44
  self.assertEqual(
45
45
  list(cache.keys()),
46
46
  [
47
- ('a', (0.0, 1024, 1, 40, None, None), 0),
48
- ('a', (0.0, 1024, 1, 40, None, None), 1),
49
- ('b', (0.0, 1024, 1, 40, None, None), 0),
50
- ('c', (0.0, 1024, 1, 40, None, None), 0),
47
+ ('a', (None, None, 1, 40, None, None), 0),
48
+ ('a', (None, None, 1, 40, None, None), 1),
49
+ ('b', (None, None, 1, 40, None, None), 0),
50
+ ('c', (None, None, 1, 40, None, None), 0),
51
51
  ],
52
52
  )
53
53
  self.assertEqual(
54
54
  list(cache.keys('StaticSequence')),
55
55
  [
56
- ('a', (0.0, 1024, 1, 40, None, None), 0),
57
- ('a', (0.0, 1024, 1, 40, None, None), 1),
58
- ('b', (0.0, 1024, 1, 40, None, None), 0),
59
- ('c', (0.0, 1024, 1, 40, None, None), 0),
56
+ ('a', (None, None, 1, 40, None, None), 0),
57
+ ('a', (None, None, 1, 40, None, None), 1),
58
+ ('b', (None, None, 1, 40, None, None), 0),
59
+ ('c', (None, None, 1, 40, None, None), 0),
60
60
  ],
61
61
  )
62
62
 
63
63
  def cache_entry(response_text, cache_seed=0):
64
64
  return base.LMCacheEntry(
65
- lf.LMSamplingResult([
66
- lf.LMSample(
67
- lf.AIMessage(response_text, cache_seed=cache_seed), score=1.0)
68
- ])
65
+ lf.LMSamplingResult(
66
+ [
67
+ lf.LMSample(
68
+ lf.AIMessage(response_text, cache_seed=cache_seed),
69
+ score=1.0
70
+ )
71
+ ],
72
+ usage=lf.LMSamplingUsage(
73
+ 1,
74
+ len(response_text),
75
+ len(response_text) + 1,
76
+ )
77
+ )
69
78
  )
70
79
 
71
80
  self.assertEqual(
@@ -90,19 +99,19 @@ class InMemoryLMCacheTest(unittest.TestCase):
90
99
  list(cache.items()),
91
100
  [
92
101
  (
93
- ('a', (0.0, 1024, 1, 40, None, None), 0),
102
+ ('a', (None, None, 1, 40, None, None), 0),
94
103
  cache_entry('1'),
95
104
  ),
96
105
  (
97
- ('a', (0.0, 1024, 1, 40, None, None), 1),
106
+ ('a', (None, None, 1, 40, None, None), 1),
98
107
  cache_entry('2', 1),
99
108
  ),
100
109
  (
101
- ('b', (0.0, 1024, 1, 40, None, None), 0),
110
+ ('b', (None, None, 1, 40, None, None), 0),
102
111
  cache_entry('3'),
103
112
  ),
104
113
  (
105
- ('c', (0.0, 1024, 1, 40, None, None), 0),
114
+ ('c', (None, None, 1, 40, None, None), 0),
106
115
  cache_entry('4'),
107
116
  ),
108
117
  ],
@@ -111,19 +120,19 @@ class InMemoryLMCacheTest(unittest.TestCase):
111
120
  list(cache.items('StaticSequence')),
112
121
  [
113
122
  (
114
- ('a', (0.0, 1024, 1, 40, None, None), 0),
123
+ ('a', (None, None, 1, 40, None, None), 0),
115
124
  cache_entry('1'),
116
125
  ),
117
126
  (
118
- ('a', (0.0, 1024, 1, 40, None, None), 1),
127
+ ('a', (None, None, 1, 40, None, None), 1),
119
128
  cache_entry('2', 1),
120
129
  ),
121
130
  (
122
- ('b', (0.0, 1024, 1, 40, None, None), 0),
131
+ ('b', (None, None, 1, 40, None, None), 0),
123
132
  cache_entry('3'),
124
133
  ),
125
134
  (
126
- ('c', (0.0, 1024, 1, 40, None, None), 0),
135
+ ('c', (None, None, 1, 40, None, None), 0),
127
136
  cache_entry('4'),
128
137
  ),
129
138
  ],
@@ -161,15 +170,15 @@ class InMemoryLMCacheTest(unittest.TestCase):
161
170
  self.assertEqual(
162
171
  list(cache.keys()),
163
172
  [
164
- ('a', (0.0, 1024, 1, 40, None, None), 0),
165
- ('a', (1.0, 1024, 1, 40, None, None), 0),
173
+ ('a', (None, None, 1, 40, None, None), 0),
174
+ ('a', (1.0, None, 1, 40, None, None), 0),
166
175
  ],
167
176
  )
168
177
 
169
178
  def test_different_model(self):
170
179
  cache = in_memory.InMemory()
171
- lm1 = fake.StaticSequence(['1', '2', '3'], cache=cache)
172
- lm2 = fake.Echo(cache=cache)
180
+ lm1 = fake.StaticSequence(['1', '2', '3'], cache=cache, temperature=0.0)
181
+ lm2 = fake.Echo(cache=cache, temperature=0.0)
173
182
 
174
183
  self.assertEqual(lm1('a'), '1')
175
184
  self.assertEqual(lm2('a'), 'a')
@@ -180,15 +189,15 @@ class InMemoryLMCacheTest(unittest.TestCase):
180
189
  self.assertEqual(
181
190
  list(cache.keys('StaticSequence')),
182
191
  [
183
- ('a', (0.0, 1024, 1, 40, None, None), 0),
184
- ('b', (0.0, 1024, 1, 40, None, None), 0),
192
+ ('a', (0.0, None, 1, 40, None, None), 0),
193
+ ('b', (0.0, None, 1, 40, None, None), 0),
185
194
  ],
186
195
  )
187
196
  self.assertEqual(
188
197
  list(cache.keys('Echo')),
189
198
  [
190
- ('a', (0.0, 1024, 1, 40, None, None), 0),
191
- ('b', (0.0, 1024, 1, 40, None, None), 0),
199
+ ('a', (0.0, None, 1, 40, None, None), 0),
200
+ ('b', (0.0, None, 1, 40, None, None), 0),
192
201
  ],
193
202
  )
194
203
  self.assertEqual(len(cache), 4)
langfun/core/llms/fake.py CHANGED
@@ -13,6 +13,7 @@
13
13
  # limitations under the License.
14
14
  """Fake LMs for testing."""
15
15
 
16
+ import abc
16
17
  from typing import Annotated
17
18
  import langfun.core as lf
18
19
 
@@ -23,15 +24,32 @@ class Fake(lf.LanguageModel):
23
24
  def _score(self, prompt: lf.Message, completions: list[lf.Message]):
24
25
  return [lf.LMScoringResult(score=-i * 1.0) for i in range(len(completions))]
25
26
 
27
+ def _sample(self, prompts: list[lf.Message]) -> list[lf.LMSamplingResult]:
28
+ results = []
29
+ for prompt in prompts:
30
+ response = self._response_from(prompt)
31
+ results.append(
32
+ lf.LMSamplingResult(
33
+ [lf.LMSample(response, 1.0)],
34
+ usage=lf.LMSamplingUsage(
35
+ prompt_tokens=len(prompt.text),
36
+ completion_tokens=len(response.text),
37
+ total_tokens=len(prompt.text) + len(response.text),
38
+ )
39
+ )
40
+ )
41
+ return results
42
+
43
+ @abc.abstractmethod
44
+ def _response_from(self, prompt: lf.Message) -> lf.Message:
45
+ """Returns the response for the given prompt."""
46
+
26
47
 
27
48
  class Echo(Fake):
28
49
  """A simple echo language model for testing."""
29
50
 
30
- def _sample(self, prompts: list[lf.Message]) -> list[lf.LMSamplingResult]:
31
- return [
32
- lf.LMSamplingResult([lf.LMSample(prompt.text, 1.0)])
33
- for prompt in prompts
34
- ]
51
+ def _response_from(self, prompt: lf.Message) -> lf.Message:
52
+ return lf.AIMessage(prompt.text)
35
53
 
36
54
 
37
55
  @lf.use_init_args(['response'])
@@ -43,11 +61,8 @@ class StaticResponse(Fake):
43
61
  'A canned response that will be returned regardless of the prompt.'
44
62
  ]
45
63
 
46
- def _sample(self, prompts: list[lf.Message]) -> list[lf.LMSamplingResult]:
47
- return [
48
- lf.LMSamplingResult([lf.LMSample(self.response, 1.0)])
49
- for _ in prompts
50
- ]
64
+ def _response_from(self, prompt: lf.Message) -> lf.Message:
65
+ return lf.AIMessage(self.response)
51
66
 
52
67
 
53
68
  @lf.use_init_args(['mapping'])
@@ -59,11 +74,8 @@ class StaticMapping(Fake):
59
74
  'A mapping from prompt to response.'
60
75
  ]
61
76
 
62
- def _sample(self, prompts: list[str]) -> list[lf.LMSamplingResult]:
63
- return [
64
- lf.LMSamplingResult([lf.LMSample(self.mapping[prompt], 1.0)])
65
- for prompt in prompts
66
- ]
77
+ def _response_from(self, prompt: lf.Message) -> lf.Message:
78
+ return lf.AIMessage(self.mapping[prompt])
67
79
 
68
80
 
69
81
  @lf.use_init_args(['sequence'])
@@ -79,10 +91,7 @@ class StaticSequence(Fake):
79
91
  super()._on_bound()
80
92
  self._pos = 0
81
93
 
82
- def _sample(self, prompts: list[str]) -> list[lf.LMSamplingResult]:
83
- results = []
84
- for _ in prompts:
85
- results.append(lf.LMSamplingResult(
86
- [lf.LMSample(self.sequence[self._pos], 1.0)]))
87
- self._pos += 1
88
- return results
94
+ def _response_from(self, prompt: lf.Message) -> lf.Message:
95
+ r = lf.AIMessage(self.sequence[self._pos])
96
+ self._pos += 1
97
+ return r
@@ -25,7 +25,24 @@ class EchoTest(unittest.TestCase):
25
25
  def test_sample(self):
26
26
  lm = fakelm.Echo()
27
27
  self.assertEqual(
28
- lm.sample(['hi']), [lf.LMSamplingResult([lf.LMSample('hi', 1.0)])]
28
+ lm.sample(['hi']),
29
+ [
30
+ lf.LMSamplingResult(
31
+ [
32
+ lf.LMSample(
33
+ lf.AIMessage(
34
+ 'hi',
35
+ score=1.0,
36
+ logprobs=None,
37
+ usage=lf.LMSamplingUsage(2, 2, 4),
38
+ tags=[lf.Message.TAG_LM_RESPONSE],
39
+ ),
40
+ score=1.0,
41
+ logprobs=None,
42
+ )
43
+ ],
44
+ lf.LMSamplingUsage(2, 2, 4))
45
+ ]
29
46
  )
30
47
 
31
48
  def test_call(self):
@@ -34,8 +51,8 @@ class EchoTest(unittest.TestCase):
34
51
  with contextlib.redirect_stdout(string_io):
35
52
  self.assertEqual(lm('hi'), 'hi')
36
53
  debug_info = string_io.getvalue()
37
- self.assertIn('[0] LM INFO:', debug_info)
38
- self.assertIn('[0] PROMPT SENT TO LM:', debug_info)
54
+ self.assertIn('[0] LM INFO', debug_info)
55
+ self.assertIn('[0] PROMPT SENT TO LM', debug_info)
39
56
  self.assertIn('[0] LM RESPONSE', debug_info)
40
57
 
41
58
  def test_score(self):
@@ -53,11 +70,45 @@ class StaticResponseTest(unittest.TestCase):
53
70
  lm = fakelm.StaticResponse(canned_response)
54
71
  self.assertEqual(
55
72
  lm.sample(['hi']),
56
- [lf.LMSamplingResult([lf.LMSample(canned_response, 1.0)])],
73
+ [
74
+ lf.LMSamplingResult(
75
+ [
76
+ lf.LMSample(
77
+ lf.AIMessage(
78
+ canned_response,
79
+ score=1.0,
80
+ logprobs=None,
81
+ usage=lf.LMSamplingUsage(2, 38, 40),
82
+ tags=[lf.Message.TAG_LM_RESPONSE],
83
+ ),
84
+ score=1.0,
85
+ logprobs=None,
86
+ )
87
+ ],
88
+ usage=lf.LMSamplingUsage(2, 38, 40)
89
+ )
90
+ ],
57
91
  )
58
92
  self.assertEqual(
59
93
  lm.sample(['Tell me a joke.']),
60
- [lf.LMSamplingResult([lf.LMSample(canned_response, 1.0)])],
94
+ [
95
+ lf.LMSamplingResult(
96
+ [
97
+ lf.LMSample(
98
+ lf.AIMessage(
99
+ canned_response,
100
+ score=1.0,
101
+ logprobs=None,
102
+ usage=lf.LMSamplingUsage(15, 38, 53),
103
+ tags=[lf.Message.TAG_LM_RESPONSE],
104
+ ),
105
+ score=1.0,
106
+ logprobs=None,
107
+ )
108
+ ],
109
+ usage=lf.LMSamplingUsage(15, 38, 53)
110
+ )
111
+ ],
61
112
  )
62
113
 
63
114
  def test_call(self):
@@ -69,8 +120,8 @@ class StaticResponseTest(unittest.TestCase):
69
120
  self.assertEqual(lm('hi'), canned_response)
70
121
 
71
122
  debug_info = string_io.getvalue()
72
- self.assertIn('[0] LM INFO:', debug_info)
73
- self.assertIn('[0] PROMPT SENT TO LM:', debug_info)
123
+ self.assertIn('[0] LM INFO', debug_info)
124
+ self.assertIn('[0] PROMPT SENT TO LM', debug_info)
74
125
  self.assertIn('[0] LM RESPONSE', debug_info)
75
126
 
76
127
 
@@ -85,8 +136,38 @@ class StaticMappingTest(unittest.TestCase):
85
136
  self.assertEqual(
86
137
  lm.sample(['Hi', 'How are you?']),
87
138
  [
88
- lf.LMSamplingResult([lf.LMSample('Hello', 1.0)]),
89
- lf.LMSamplingResult([lf.LMSample('I am fine, how about you?', 1.0)])
139
+ lf.LMSamplingResult(
140
+ [
141
+ lf.LMSample(
142
+ lf.AIMessage(
143
+ 'Hello',
144
+ score=1.0,
145
+ logprobs=None,
146
+ usage=lf.LMSamplingUsage(2, 5, 7),
147
+ tags=[lf.Message.TAG_LM_RESPONSE],
148
+ ),
149
+ score=1.0,
150
+ logprobs=None,
151
+ )
152
+ ],
153
+ usage=lf.LMSamplingUsage(2, 5, 7)
154
+ ),
155
+ lf.LMSamplingResult(
156
+ [
157
+ lf.LMSample(
158
+ lf.AIMessage(
159
+ 'I am fine, how about you?',
160
+ score=1.0,
161
+ logprobs=None,
162
+ usage=lf.LMSamplingUsage(12, 25, 37),
163
+ tags=[lf.Message.TAG_LM_RESPONSE],
164
+ ),
165
+ score=1.0,
166
+ logprobs=None,
167
+ )
168
+ ],
169
+ usage=lf.LMSamplingUsage(12, 25, 37)
170
+ )
90
171
  ]
91
172
  )
92
173
  with self.assertRaises(KeyError):
@@ -104,8 +185,38 @@ class StaticSequenceTest(unittest.TestCase):
104
185
  self.assertEqual(
105
186
  lm.sample(['Hi', 'How are you?']),
106
187
  [
107
- lf.LMSamplingResult([lf.LMSample('Hello', 1.0)]),
108
- lf.LMSamplingResult([lf.LMSample('I am fine, how about you?', 1.0)])
188
+ lf.LMSamplingResult(
189
+ [
190
+ lf.LMSample(
191
+ lf.AIMessage(
192
+ 'Hello',
193
+ score=1.0,
194
+ logprobs=None,
195
+ usage=lf.LMSamplingUsage(2, 5, 7),
196
+ tags=[lf.Message.TAG_LM_RESPONSE],
197
+ ),
198
+ score=1.0,
199
+ logprobs=None,
200
+ )
201
+ ],
202
+ usage=lf.LMSamplingUsage(2, 5, 7)
203
+ ),
204
+ lf.LMSamplingResult(
205
+ [
206
+ lf.LMSample(
207
+ lf.AIMessage(
208
+ 'I am fine, how about you?',
209
+ score=1.0,
210
+ logprobs=None,
211
+ usage=lf.LMSamplingUsage(12, 25, 37),
212
+ tags=[lf.Message.TAG_LM_RESPONSE],
213
+ ),
214
+ score=1.0,
215
+ logprobs=None,
216
+ )
217
+ ],
218
+ usage=lf.LMSamplingUsage(12, 25, 37)
219
+ )
109
220
  ]
110
221
  )
111
222
  with self.assertRaises(IndexError):
@@ -152,10 +152,15 @@ class GenAITest(unittest.TestCase):
152
152
  )
153
153
 
154
154
  def test_model_hub(self):
155
+ orig_get_model = genai.get_model
156
+ genai.get_model = mock_get_model
157
+
155
158
  model = google_genai._GOOGLE_GENAI_MODEL_HUB.get('gemini-pro')
156
159
  self.assertIsNotNone(model)
157
160
  self.assertIs(google_genai._GOOGLE_GENAI_MODEL_HUB.get('gemini-pro'), model)
158
161
 
162
+ genai.get_model = orig_get_model
163
+
159
164
  def test_api_key_check(self):
160
165
  with self.assertRaisesRegex(ValueError, 'Please specify `api_key`'):
161
166
  _ = google_genai.GeminiPro()._api_initialized
@@ -167,7 +172,7 @@ class GenAITest(unittest.TestCase):
167
172
 
168
173
  def test_call(self):
169
174
  with mock.patch(
170
- 'google.generativeai.generative_models.GenerativeModel.generate_content'
175
+ 'google.generativeai.GenerativeModel.generate_content',
171
176
  ) as mock_generate:
172
177
  orig_get_model = genai.get_model
173
178
  genai.get_model = mock_get_model
@@ -176,7 +181,7 @@ class GenAITest(unittest.TestCase):
176
181
  lm = google_genai.GeminiPro(api_key='test_key')
177
182
  self.maxDiff = None
178
183
  self.assertEqual(
179
- lm('hello', temperature=2.0, top_k=20).text,
184
+ lm('hello', temperature=2.0, top_k=20, max_tokens=1024).text,
180
185
  (
181
186
  'This is a response to hello with n=1, temperature=2.0, '
182
187
  'top_p=None, top_k=20, max_tokens=1024, stop=None.'
@@ -197,7 +202,7 @@ class GenAITest(unittest.TestCase):
197
202
  (
198
203
  "hello to models/text-bison-001 with {'temperature': 2.0, "
199
204
  "'top_k': 20, 'top_p': None, 'candidate_count': 1, "
200
- "'max_output_tokens': 1024, 'stop_sequences': None}"
205
+ "'max_output_tokens': None, 'stop_sequences': None}"
201
206
  ),
202
207
  )
203
208
  genai.get_model = orig_get_model