langfun 0.0.2.dev20240403__py3-none-any.whl → 0.0.2.dev20240407__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.
@@ -12,7 +12,6 @@
12
12
  # See the License for the specific language governing permissions and
13
13
  # limitations under the License.
14
14
  """Python code error correction."""
15
- import re
16
15
  from typing import Any
17
16
  import langfun.core as lf
18
17
  from langfun.core.coding.python import errors
@@ -31,11 +30,6 @@ class CorrectedCode(pg.Object):
31
30
  corrected_code: str
32
31
 
33
32
 
34
- def remove_docstrings(code):
35
- pattern = re.compile(r"(def .+?:\s*?)('''|\"\"\")((.|\s)*?)(\2)", re.DOTALL)
36
- return pattern.sub(r"\1", code)
37
-
38
-
39
33
  def run_with_correction(
40
34
  code: str,
41
35
  error: str | None = None,
@@ -86,7 +80,6 @@ def run_with_correction(
86
80
  # pytype: enable=import-error
87
81
  # pylint: enable=g-import-not-at-top
88
82
 
89
- code = remove_docstrings(code)
90
83
  if max_attempts == 0:
91
84
  result = execution.run(
92
85
  code,
langfun/core/eval/base.py CHANGED
@@ -816,11 +816,6 @@ class Evaluation(Evaluable):
816
816
  if self.schema_fn is None:
817
817
  return None
818
818
 
819
- kwargs = {}
820
- # Allow schema to be a function based on current evaluation.
821
- if 'evaluation' in self.schema_fn.__signature__.arg_names:
822
- kwargs['evaluation'] = self
823
-
824
819
  schema = self._call_schema_fn()
825
820
  fewshot_examples = None
826
821
  if isinstance(schema, tuple):
@@ -15,9 +15,7 @@
15
15
 
16
16
  import base64
17
17
  from typing import cast
18
-
19
18
  from langfun.core.modalities import mime
20
- import magic
21
19
 
22
20
 
23
21
  class Video(mime.MimeType):
@@ -29,6 +27,11 @@ class Video(mime.MimeType):
29
27
 
30
28
  @property
31
29
  def mime_type(self) -> str:
30
+ # TODO(daiyip): after cl/619658455, LaunchPad binaries cannot import `magic`
31
+ # correctly. This is to mitigate the issue for major Langfun users who do
32
+ # not use Video. We shall move this import out once the issue is fixed.
33
+ import magic # pylint: disable=g-import-not-at-top
34
+
32
35
  video_mime_type = magic.from_buffer(self.to_bytes(), mime=True)
33
36
  if 'video/' not in video_mime_type:
34
37
  raise ValueError(f'Not a video: {video_mime_type!r}.')
@@ -14,7 +14,7 @@
14
14
  """The base of symbolic mapping methods."""
15
15
 
16
16
  import io
17
- from typing import Annotated, Any
17
+ from typing import Annotated, Any, Callable
18
18
  import langfun.core as lf
19
19
  from langfun.core.structured import schema as schema_lib
20
20
  import pyglove as pg
@@ -278,6 +278,14 @@ class Mapping(lf.LangFunc):
278
278
  ),
279
279
  ] = lf.RAISE_IF_HAS_ERROR
280
280
 
281
+ response_postprocess: Annotated[
282
+ Callable[[str], str] | None,
283
+ (
284
+ 'A callable object that post process the raw LLM response before '
285
+ 'parsing it into the output Python object.'
286
+ )
287
+ ] = None
288
+
281
289
  #
282
290
  # Key methods for implementing specific mappings.
283
291
  #
@@ -296,6 +304,7 @@ class Mapping(lf.LangFunc):
296
304
  def transform_output(self, lm_output: lf.Message) -> lf.Message:
297
305
  """Transforms LM response into structure if schema is present."""
298
306
  try:
307
+ lm_output = self.postprocess_response(lm_output)
299
308
  lm_output.result = self.postprocess_result(self.parse_result(lm_output))
300
309
  except Exception as e: # pylint: disable=broad-exception-caught
301
310
  if self.default == lf.RAISE_IF_HAS_ERROR:
@@ -316,6 +325,14 @@ class Mapping(lf.LangFunc):
316
325
  autofix_lm=self.autofix_lm or self.lm,
317
326
  )
318
327
 
328
+ def postprocess_response(self, response: lf.Message) -> lf.Message:
329
+ """Post process LLM response."""
330
+ if self.response_postprocess is not None:
331
+ postprocessed_text = self.response_postprocess(response.text)
332
+ if postprocessed_text != response.text:
333
+ return lf.AIMessage(postprocessed_text, source=response)
334
+ return response
335
+
319
336
  def postprocess_result(self, result: Any) -> Any:
320
337
  """Post process structured output."""
321
338
  return result
@@ -13,7 +13,7 @@
13
13
  # limitations under the License.
14
14
  """Symbolic query."""
15
15
 
16
- from typing import Any, Type, Union
16
+ from typing import Any, Callable, Type, Union
17
17
 
18
18
  import langfun.core as lf
19
19
  from langfun.core.structured import mapping
@@ -107,6 +107,7 @@ def query(
107
107
  lm: lf.LanguageModel | None = None,
108
108
  examples: list[mapping.MappingExample] | None = None,
109
109
  cache_seed: int | None = 0,
110
+ response_postprocess: Callable[[str], str] | None = None,
110
111
  autofix: int = 0,
111
112
  autofix_lm: lf.LanguageModel | None = None,
112
113
  protocol: schema_lib.SchemaProtocol = 'python',
@@ -159,6 +160,9 @@ def query(
159
160
  cache_seed: Seed for computing cache key. The cache key is determined by a
160
161
  tuple of (lm, prompt, cache seed). If None, cache will be disabled for
161
162
  the query even cache is configured by the LM.
163
+ response_postprocess: An optional callable object to process the raw LM
164
+ response before parsing it into the final output object. If None, the
165
+ raw LM response will not be processed.
162
166
  autofix: Number of attempts to auto fix the generated code. If 0, autofix is
163
167
  disabled. Auto-fix is not supported for 'json' protocol.
164
168
  autofix_lm: The language model to use for autofix. If not specified, the
@@ -188,6 +192,10 @@ def query(
188
192
  output = lf.LangFunc.from_value(prompt, **kwargs)(
189
193
  lm=lm, cache_seed=cache_seed, skip_lm=skip_lm
190
194
  )
195
+ if response_postprocess:
196
+ processed_text = response_postprocess(output.text)
197
+ if processed_text != output.text:
198
+ output = lf.AIMessage(processed_text, source=output)
191
199
  return output if returns_message else output.text
192
200
 
193
201
  # Query with structured output.
@@ -206,6 +214,7 @@ def query(
206
214
  schema=schema,
207
215
  default=default,
208
216
  examples=examples,
217
+ response_postprocess=response_postprocess,
209
218
  autofix=autofix if protocol == 'python' else 0,
210
219
  **kwargs,
211
220
  )(
@@ -436,6 +436,23 @@ class QueryStructurePythonTest(unittest.TestCase):
436
436
  ])
437
437
  self.assertEqual(prompting.query('what is 1 + 0', int, lm=lm, autofix=3), 1)
438
438
 
439
+ def test_response_postprocess(self):
440
+ with lf.context(
441
+ lm=fake.StaticResponse('<!-- some comment-->\n3'),
442
+ override_attrs=True,
443
+ ):
444
+ self.assertEqual(
445
+ prompting.query(
446
+ 'Compute 1 + 2', response_postprocess=lambda x: x.split('\n')[1]),
447
+ '3'
448
+ )
449
+ self.assertEqual(
450
+ prompting.query(
451
+ 'Compute 1 + 2', int,
452
+ response_postprocess=lambda x: x.split('\n')[1]),
453
+ 3
454
+ )
455
+
439
456
 
440
457
  class QueryStructureJsonTest(unittest.TestCase):
441
458
 
@@ -386,10 +386,12 @@ def class_definition(
386
386
  if schema.fields:
387
387
  for key, field in schema.items():
388
388
  if not isinstance(key, pg.typing.ConstStrKey):
389
- raise TypeError(
389
+ pg.logging.warning(
390
390
  'Variable-length keyword arguments is not supported in '
391
- f'structured parsing or query. Encountered: {field}'
391
+ f'structured parsing or query. Encountered: {cls}, Schema: {schema}'
392
392
  )
393
+ continue
394
+
393
395
  # Write field doc string as comments before the field definition.
394
396
  if field.description:
395
397
  for line in field.description.split('\n'):
@@ -459,9 +459,7 @@ class SchemaPythonReprTest(unittest.TestCase):
459
459
  x: str
460
460
  __kwargs__: typing.Any
461
461
 
462
- with self.assertRaisesRegex(
463
- TypeError, 'Variable-length keyword arguments is not supported'):
464
- schema_lib.class_definition(C)
462
+ self.assertEqual(schema_lib.class_definition(C), 'class C:\n x: str\n')
465
463
 
466
464
  def test_repr(self):
467
465
  class Foo(pg.Object):
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: langfun
3
- Version: 0.0.2.dev20240403
3
+ Version: 0.0.2.dev20240407
4
4
  Summary: Langfun: Language as Functions.
5
5
  Home-page: https://github.com/google/langfun
6
6
  Author: Langfun Authors
@@ -27,7 +27,7 @@ langfun/core/text_formatting.py,sha256=ytjj7opnRJ6w-pkglL2CZUyfYDXLpNf65E42LBb31
27
27
  langfun/core/text_formatting_test.py,sha256=nyKC6tn2L4hPJiqQHgxcbQsJJi4A4Nbj8FiO8iT6B80,1514
28
28
  langfun/core/coding/__init__.py,sha256=5utju_fwEsImaiftx4oXKl9FAM8p281k8-Esdh_-m1w,835
29
29
  langfun/core/coding/python/__init__.py,sha256=MJ-vubliz-ebrZH3OBRKBwMi0S9-FrhGCp8YQLR6_I4,1776
30
- langfun/core/coding/python/correction.py,sha256=uuQmZCrAl0EA9etIUmn2-FZ-ge8iNcjOAAlm-WgkYfo,6776
30
+ langfun/core/coding/python/correction.py,sha256=a2aFUt9ocbXTCR6Z6OGNjQZDI1LfU0PBkSe7hJB8dEM,6589
31
31
  langfun/core/coding/python/correction_test.py,sha256=yLqmQ9BPORsnREkrS10PnljEaLR3BoydTVeT3OGoqfU,3507
32
32
  langfun/core/coding/python/errors.py,sha256=fX3Du63uGm25YFXW9D-bV2gntTdTAX3hBFtAnRlmg14,3166
33
33
  langfun/core/coding/python/errors_test.py,sha256=_ZbWJCFIb-FkCK7K1zCuH8W3x_NFt-jNe3dfP8yqaD4,2323
@@ -40,7 +40,7 @@ langfun/core/coding/python/parsing_test.py,sha256=9vAWF484kWIm6JZq8NFiMgKUDhXV-d
40
40
  langfun/core/coding/python/permissions.py,sha256=1QWGHvzL8MM0Ok_auQ9tURqZHtdOfJaDpBzZ29GUE-c,2544
41
41
  langfun/core/coding/python/permissions_test.py,sha256=w5EDb8QxpxgJyZkojyzVWQvDfg366zn99-g__6TbPQ0,2699
42
42
  langfun/core/eval/__init__.py,sha256=iDA2OcJ3kR6ixZizXIY3N9LsjkaVrfTbSClTiSP8ekY,1291
43
- langfun/core/eval/base.py,sha256=dLDWAYLHnLX7CyvMTBcditLFIuq-tUvGoPX1vT65GJQ,54730
43
+ langfun/core/eval/base.py,sha256=YpAPtWLeh3OpJuuPk7913xkB2OTCaGls1uWMohDA8SI,54551
44
44
  langfun/core/eval/base_test.py,sha256=8MOum0DWMEm2-NpwmFgcqmlqEmuWYF5MesrCXTySylg,21083
45
45
  langfun/core/eval/matching.py,sha256=g2yuBb4FeOlAlB10hqdWvaIg4QVQlJbiViRDcD2Y8go,9567
46
46
  langfun/core/eval/matching_test.py,sha256=jFrNOaHteNo7wxCwc6w_mGylM0VHwezAcvfaZANKKmA,4898
@@ -67,23 +67,23 @@ langfun/core/modalities/image.py,sha256=zNpLHwJi6PJMeeAcVQG6vn0oYIbilTuJq6xu-Tvr
67
67
  langfun/core/modalities/image_test.py,sha256=YxDRvC49Bjwyyndd_P7y6XjyS7dOft0Zewwxk-7q4kE,2301
68
68
  langfun/core/modalities/mime.py,sha256=wVfaYflhGz1W4v3m972rAplW3OGOFtjFpHDYIaUD5D0,2238
69
69
  langfun/core/modalities/mime_test.py,sha256=cVHxRvJ1QXC1SVhBmWkJdWGpL9Xl0UNfTQq6j0OGGL4,1881
70
- langfun/core/modalities/video.py,sha256=5-sIlzXb_ZY84RMFcpVD9ysP9GbcwbdKaZOEm3jECtc,1469
70
+ langfun/core/modalities/video.py,sha256=25M4XsNG5XEWRy57LYT_a6_aMURMPAgC41B3weEXFsY,1747
71
71
  langfun/core/modalities/video_test.py,sha256=jYuI2m8S8zDCAVBPEUbbpP205dXAht90A2_PHWo4-r8,2039
72
72
  langfun/core/structured/__init__.py,sha256=SpObW-HKpyKvkLlX8FV5ixz7CRm098j2aGfOguM3AUI,3462
73
73
  langfun/core/structured/completion.py,sha256=skBxt6V_fv2TBUKnzFgnPMbVY8HSYn8sY04MLok2yvs,7299
74
74
  langfun/core/structured/completion_test.py,sha256=98UCgA4gzfp6H6HgP2s2kcKs25YH3k4Nxj1rgAvmVBw,19249
75
75
  langfun/core/structured/description.py,sha256=SXW4MJvshFjbR-0gw6rE21o6WXq12UlRXawvDBXMZFA,5211
76
76
  langfun/core/structured/description_test.py,sha256=UtZGjSFUaQ6130t1E5tcL7ODu0xIefkapb53TbnqsK8,7362
77
- langfun/core/structured/mapping.py,sha256=m7i80GU3vfDZXw4TTnidWTS3K-c1H8JNX9KcoMw4E4s,10373
77
+ langfun/core/structured/mapping.py,sha256=7JInwZLmQdu7asHhC0vFLJNOCBnY-hrD6v5RQgf-xKk,11020
78
78
  langfun/core/structured/mapping_test.py,sha256=07DDCGbwytQHSMm7fCi5-Ly-JNgdV4ubHZq0wthX4A4,3338
79
79
  langfun/core/structured/parsing.py,sha256=keoVqEfzAbdULh6GawWFsTQzU91MzJXYFZjXGXLaD8g,11492
80
80
  langfun/core/structured/parsing_test.py,sha256=2_Uf3LYNRON1-5ysEr75xiG_cAxR3ZiixSfvUQu6mOQ,20846
81
- langfun/core/structured/prompting.py,sha256=0xRPC0K_RaFRv-j52x8_-1n1eRFSomJEpdZApVXsCV0,6902
82
- langfun/core/structured/prompting_test.py,sha256=SwoYbPyKhUT1H2QbqHvl93biCiE9Ttn1aWixoHH-v9Y,19129
83
- langfun/core/structured/schema.py,sha256=CuRXOBjoK8rv5b281-w2o7nWQ7ox2YX5kkq2dOk0Ry8,25020
81
+ langfun/core/structured/prompting.py,sha256=OAejcd7E-GTRI86i71Uel66te5zcTqyhsNtxe_Nt46U,7407
82
+ langfun/core/structured/prompting_test.py,sha256=FdEQ0Sy0zGSFXsaOYkWLjyso37-ckIBZE74hmD7QaAA,19610
83
+ langfun/core/structured/schema.py,sha256=mJXirgqx3N7SA9zBO_ISHrzcV-ZRshLhnMJyCcSjGjY,25057
84
84
  langfun/core/structured/schema_generation.py,sha256=U3nRQsqmMZg_qIVDh2fiY3K4JLfsAL1LcKzIFP1iXFg,5316
85
85
  langfun/core/structured/schema_generation_test.py,sha256=cfZyP0gHno2fXy_c9vsVdvHmqKQSfuyUsCtfO3JFmYQ,2945
86
- langfun/core/structured/schema_test.py,sha256=hLhwbUaBtTJMG4c-q21rFUksTtI-jP_oNIyr5_S-0yo,22472
86
+ langfun/core/structured/schema_test.py,sha256=XsTACSWwFmqlj4pCKsKWcVJbOaeu2DP0jMMCR4EZ_Js,22405
87
87
  langfun/core/structured/scoring.py,sha256=a3vfGnqf-DOWjD07MF54GCZTO_R1RTxTDVPzerXnU0s,2325
88
88
  langfun/core/structured/scoring_test.py,sha256=TznLMl0x9QxzmhHz_3Vr44VOXuvFnUSeRQVhu33W5cA,1437
89
89
  langfun/core/templates/__init__.py,sha256=bO0eMsVJbi7sxEB2YlInKRQ2EVP-RyyKUwcD-8msuN4,927
@@ -95,8 +95,8 @@ langfun/core/templates/demonstration.py,sha256=vCrgYubdZM5Umqcgp8NUVGXgr4P_c-fik
95
95
  langfun/core/templates/demonstration_test.py,sha256=SafcDQ0WgI7pw05EmPI2S4v1t3ABKzup8jReCljHeK4,2162
96
96
  langfun/core/templates/selfplay.py,sha256=yhgrJbiYwq47TgzThmHrDQTF4nDrTI09CWGhuQPNv-s,2273
97
97
  langfun/core/templates/selfplay_test.py,sha256=IB5rWbjK_9CTkqEo1BclQPzFAKcIiusJckH8J19HFgI,2096
98
- langfun-0.0.2.dev20240403.dist-info/LICENSE,sha256=WNHhf_5RCaeuKWyq_K39vmp9F28LxKsB4SpomwSZ2L0,11357
99
- langfun-0.0.2.dev20240403.dist-info/METADATA,sha256=2NOTKH53MG8WNbkap8zD-6kQYRhDBOGbc-eywzJKf3g,3405
100
- langfun-0.0.2.dev20240403.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92
101
- langfun-0.0.2.dev20240403.dist-info/top_level.txt,sha256=RhlEkHxs1qtzmmtWSwYoLVJAc1YrbPtxQ52uh8Z9VvY,8
102
- langfun-0.0.2.dev20240403.dist-info/RECORD,,
98
+ langfun-0.0.2.dev20240407.dist-info/LICENSE,sha256=WNHhf_5RCaeuKWyq_K39vmp9F28LxKsB4SpomwSZ2L0,11357
99
+ langfun-0.0.2.dev20240407.dist-info/METADATA,sha256=AstNjq_o1Rpd5C6aHkrQ78z_Fe38CMBXUlnwz4ArvwY,3405
100
+ langfun-0.0.2.dev20240407.dist-info/WHEEL,sha256=GJ7t_kWBFywbagK5eo9IoUwLW6oyOeTKmQ-9iHFVNxQ,92
101
+ langfun-0.0.2.dev20240407.dist-info/top_level.txt,sha256=RhlEkHxs1qtzmmtWSwYoLVJAc1YrbPtxQ52uh8Z9VvY,8
102
+ langfun-0.0.2.dev20240407.dist-info/RECORD,,