langfun 0.0.2.dev20240207__py3-none-any.whl → 0.0.2.dev20240209__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/__init__.py CHANGED
@@ -109,6 +109,8 @@ from langfun.core.memory import Memory
109
109
  # Utility for console output.
110
110
  from langfun.core import console
111
111
 
112
+ # Import internal modules.
113
+
112
114
  # pylint: enable=g-import-not-at-top
113
115
  # pylint: enable=g-importing-member
114
116
  # pylint: enable=g-bad-import-order
@@ -83,7 +83,7 @@ def run_with_correction(
83
83
  # pylint: disable=g-import-not-at-top
84
84
  # pytype: disable=import-error
85
85
  from langfun.core.structured import prompting
86
- # pytype: disable=import-error
86
+ # pytype: enable=import-error
87
87
  # pylint: enable=g-import-not-at-top
88
88
 
89
89
  code = remove_docstrings(code)
@@ -538,11 +538,12 @@ def concurrent_map(
538
538
  An iterator of (input, output, error).
539
539
 
540
540
  Raises:
541
- Exception: Erros that are not in `silence_on_errors` or `retry_on_errors`,
541
+ Exception: Errors that are not in `silence_on_errors` or `retry_on_errors`,
542
542
  or retry on such errors has reached max attempts.
543
543
  TimeoutError: Any item timed out while TimeoutError is not silenced via
544
544
  `silence_on_errors`.
545
545
  """
546
+ # Internal usage logging.
546
547
 
547
548
  if retry_on_errors:
548
549
  func = with_retry(
@@ -683,7 +684,7 @@ def concurrent_map(
683
684
  class ExecutorPool:
684
685
  """A pool of managed executors.
685
686
 
686
- Managed executors are used for controlling the parallism of execution based
687
+ Managed executors are used for controlling the parallelism of execution based
687
688
  on resource id. This design is to honor overall rate limit of LMs globally
688
689
  (with current process).
689
690
  """
langfun/core/eval/base.py CHANGED
@@ -211,6 +211,8 @@ class Evaluable(lf.Component):
211
211
  **kwargs,
212
212
  ) -> Union['Summary', pg.Dict]:
213
213
  """Run the evaluation, which fills and returns the result."""
214
+ # Internal usage logging.
215
+
214
216
  if dryrun:
215
217
  self.dryrun(filter=filter, verbose=False, debug=debug)
216
218
 
@@ -582,8 +584,22 @@ class Suite(Evaluable):
582
584
 
583
585
  children: Annotated[list[Evaluable], 'Child evaluation sets or suites.']
584
586
 
587
+ __kwargs__: Annotated[
588
+ Any,
589
+ (
590
+ 'Wildcard keyword arguments for `__init__` that can be accessed from '
591
+ 'parent suite if the argument is absent from current evaluation set.'
592
+ ),
593
+ ]
594
+
585
595
  def _on_bound(self):
586
596
  super()._on_bound()
597
+ overrides = {
598
+ k: v for k, v in self.sym_init_args.items()
599
+ if k not in ('id', 'children')
600
+ }
601
+ for child in self.children:
602
+ child.rebind(overrides, notify_parents=False)
587
603
  self.__dict__.pop('hash', None)
588
604
 
589
605
  @functools.cached_property
@@ -618,7 +634,7 @@ class Evaluation(Evaluable):
618
634
 
619
635
  method: Annotated[
620
636
  Literal['call', 'query', 'complete'], 'Method for symbolic prompting.'
621
- ]
637
+ ] = lf.contextual(default='query')
622
638
 
623
639
  prompt: Annotated[
624
640
  lf.Template,
@@ -626,7 +642,7 @@ class Evaluation(Evaluable):
626
642
  'Template for rendering the template. Example object could be '
627
643
  'accessed via `example`.'
628
644
  ),
629
- ]
645
+ ] = lf.contextual()
630
646
 
631
647
  schema_fn: pg.typing.Annotated[
632
648
  pg.typing.Functor().noneable(),
@@ -660,9 +676,11 @@ class Evaluation(Evaluable):
660
676
  ```
661
677
  """)
662
678
  ),
663
- ]
679
+ ] = lf.contextual()
664
680
 
665
- lm: Annotated[lf.LanguageModel, 'Language model to use for evaluation.']
681
+ lm: Annotated[lf.LanguageModel, 'Language model to use for evaluation.'] = (
682
+ lf.contextual()
683
+ )
666
684
 
667
685
  parsing_lm: Annotated[
668
686
  lf.LanguageModel | None,
@@ -670,7 +688,7 @@ class Evaluation(Evaluable):
670
688
  'Language model for parsing. Applicable only when method is set'
671
689
  'to `call`. If None, `lm` will also be used for parsing. '
672
690
  ),
673
- ] = None
691
+ ] = lf.contextual(default=None)
674
692
 
675
693
  completion_prompt_field: Annotated[
676
694
  str | None,
@@ -680,8 +698,8 @@ class Evaluation(Evaluable):
680
698
  'the class, instead the prompt will be passed as the first argument '
681
699
  'of the input object to complete. Applicable only when `method` is '
682
700
  'set to `complete`.'
683
- )
684
- ] = None
701
+ ),
702
+ ] = lf.contextual(default=None)
685
703
 
686
704
  autofix: Annotated[
687
705
  int,
@@ -690,7 +708,7 @@ class Evaluation(Evaluable):
690
708
  'generated code for the output structure. If 0, autofix will be '
691
709
  'disabled.'
692
710
  ),
693
- ] = 0
711
+ ] = lf.contextual(default=0)
694
712
 
695
713
  autofix_lm: Annotated[
696
714
  lf.LanguageModel | None,
@@ -698,14 +716,16 @@ class Evaluation(Evaluable):
698
716
  'Language model for autofix. If None, `lm` will also be used for '
699
717
  'autofix.'
700
718
  ),
701
- ] = None
719
+ ] = lf.contextual(default=None)
702
720
 
703
721
  additional_args: Annotated[
704
722
  dict[str, Any] | None,
705
- 'Additional kwargs that will be passed to `self.process`'
706
- ] = None
723
+ 'Additional kwargs that will be passed to `self.process`',
724
+ ] = lf.contextual(default=None)
707
725
 
708
- use_cache: Annotated[bool, 'If True, LM cache will be enabled.'] = True
726
+ use_cache: Annotated[bool, 'If True, LM cache will be enabled.'] = (
727
+ lf.contextual(default=True)
728
+ )
709
729
 
710
730
  max_workers: Annotated[
711
731
  int, 'Max workers to run the evaluation in parallel.'
@@ -744,7 +764,11 @@ class Evaluation(Evaluable):
744
764
  @functools.cached_property
745
765
  def examples(self):
746
766
  """Returns examples for evaluation."""
747
- return self.inputs()
767
+ kwargs = {}
768
+ # Allow inputs to be dependent on current evaluation.
769
+ if 'evaluation' in self.inputs.__signature__.arg_names:
770
+ kwargs['evaluation'] = self
771
+ return self.inputs(**kwargs)
748
772
 
749
773
  @property
750
774
  def num_examples(self) -> int:
@@ -784,7 +808,12 @@ class Evaluation(Evaluable):
784
808
  if self.schema_fn is None:
785
809
  return None
786
810
 
787
- schema = self.schema_fn()
811
+ kwargs = {}
812
+ # Allow schema to be a function based on current evaluation.
813
+ if 'evaluation' in self.schema_fn.__signature__.arg_names:
814
+ kwargs['evaluation'] = self
815
+
816
+ schema = self._call_schema_fn()
788
817
  fewshot_examples = None
789
818
  if isinstance(schema, tuple):
790
819
  schema, fewshot_examples = schema
@@ -798,13 +827,20 @@ class Evaluation(Evaluable):
798
827
  if self.schema_fn is None:
799
828
  return None
800
829
 
801
- schema = self.schema_fn()
830
+ schema = self._call_schema_fn()
802
831
  fewshot_examples = None
803
832
  if isinstance(schema, tuple):
804
833
  schema, fewshot_examples = schema
805
834
  self.__dict__['schema'] = self._formalize_schema(schema)
806
835
  return self._maybe_adjust_examples_for_completion(fewshot_examples)
807
836
 
837
+ def _call_schema_fn(self):
838
+ kwargs = {}
839
+ # Allow schema to be a function based on current evaluation.
840
+ if 'evaluation' in self.schema_fn.__signature__.arg_names:
841
+ kwargs['evaluation'] = self
842
+ return self.schema_fn(**kwargs)
843
+
808
844
  def _formalize_schema(self, annotation) -> lf_structured.Schema:
809
845
  """Formalizes schema from annotation."""
810
846
  if self.method == 'complete':
@@ -854,9 +890,9 @@ class Evaluation(Evaluable):
854
890
  return []
855
891
  children = []
856
892
  for i, child in enumerate(pg.iter(self)):
857
- child.rebind(id=f'{self.id}@{child.hash}', skip_notification=True)
858
893
  child.sym_setparent(self)
859
894
  child.sym_setpath(self.sym_path + f'children[{i}]')
895
+ child.rebind(id=f'{self.id}@{child.hash}', skip_notification=True)
860
896
  children.append(child)
861
897
  return children
862
898
 
@@ -873,9 +909,6 @@ class Evaluation(Evaluable):
873
909
 
874
910
  def _on_bound(self):
875
911
  super()._on_bound()
876
- if self.method != 'call' and self.schema_fn is None:
877
- raise ValueError(
878
- f'`schema_fn` must be specified for method {self.method!r}')
879
912
  self.__dict__.pop('hash', None)
880
913
  self.__dict__.pop('children', None)
881
914
  self.__dict__.pop('examples', None)
@@ -1442,11 +1475,11 @@ class Summary(pg.Object):
1442
1475
  cols = set()
1443
1476
  nonpivot_values = collections.defaultdict(set)
1444
1477
  for e in evaluations:
1445
- for k, v in e.sym_init_args.items():
1478
+ for k in e.sym_init_args:
1446
1479
  if pivot_field == k:
1447
- cols.add(SymbolicComparable(v))
1480
+ cols.add(SymbolicComparable(e.sym_inferred(k)))
1448
1481
  elif k not in ('id', 'groundtruth'):
1449
- nonpivot_values[k].add(SymbolicComparable(v))
1482
+ nonpivot_values[k].add(SymbolicComparable(e.sym_inferred(k)))
1450
1483
 
1451
1484
  cols = sorted(cols)
1452
1485
 
@@ -42,7 +42,8 @@ def answer_schema():
42
42
 
43
43
 
44
44
  @pg.functor
45
- def answer_schema_with_fewshot_examples():
45
+ def answer_schema_with_fewshot_examples(evaluation):
46
+ del evaluation
46
47
  return Solution, [
47
48
  lf_structured.MappingExample(
48
49
  input='The result of one plus two',
@@ -61,7 +62,7 @@ def eval_set(
61
62
  eval_id: str,
62
63
  method: str,
63
64
  schema_fn,
64
- lm: lf.LanguageModel,
65
+ lm: lf.LanguageModel = pg.MISSING_VALUE,
65
66
  use_cache: bool = True,
66
67
  cls: Type[base.Evaluation] = base.Evaluation,
67
68
  **kwargs,
@@ -170,8 +171,6 @@ class EvaluationTest(unittest.TestCase):
170
171
  )
171
172
 
172
173
  def test_bad_init(self):
173
- with self.assertRaisesRegex(ValueError, '.*'):
174
- eval_set('bad_init1', 'complete', None, lm=fake.StaticResponse('hi'))
175
174
 
176
175
  @pg.functor()
177
176
  def _bad_completion_schema():
@@ -438,18 +437,18 @@ class SuiteTest(unittest.TestCase):
438
437
  lm = fake.StaticSequence([
439
438
  'Solution(final_answer=2)',
440
439
  '3',
441
- ])
440
+ ] * 5)
442
441
  s = base.Suite(
443
442
  'suite_run_test',
444
443
  [
445
- eval_set('run_test_1', 'query', schema_fn=answer_schema(), lm=lm),
444
+ eval_set('run_test_1', 'query', schema_fn=answer_schema()),
446
445
  # A suite of search space. Two of the sub-experiments are identical,
447
446
  # thus the result of run_test_2 would include only two keys.
448
447
  eval_set('run_test_2',
449
448
  pg.oneof(['call', 'query']),
450
- schema_fn=pg.oneof([answer_schema(), answer_schema()]),
451
- lm=lm),
449
+ schema_fn=pg.oneof([answer_schema(), answer_schema()])),
452
450
  ],
451
+ lm=lm
453
452
  )
454
453
  # Test for persistent hash.
455
454
  self.assertEqual(s.hash, '7285e52b')
@@ -482,7 +481,7 @@ class SuiteTest(unittest.TestCase):
482
481
  schema_fn='answer_schema()',
483
482
  ),
484
483
  cache_stats=dict(
485
- use_cache=True, num_queries=3, num_hits=0, num_updates=2
484
+ use_cache=True, num_queries=4, num_hits=0, num_updates=4
486
485
  ),
487
486
  metrics=dict(total=2, failures=2, failure_rate=1.0),
488
487
  ),
@@ -288,6 +288,8 @@ class LanguageModel(component.Component):
288
288
  **kwargs,
289
289
  ) -> list[LMSamplingResult]:
290
290
  """Samples one or multiple prompts."""
291
+ # Internal usage logging.
292
+
291
293
  prompts = [message_lib.UserMessage.from_value(p) for p in prompts]
292
294
 
293
295
  with component.context(override_attrs=True, **kwargs):
@@ -174,6 +174,8 @@ def query(
174
174
  Returns:
175
175
  The result based on the schema.
176
176
  """
177
+ # Internal usage logging.
178
+
177
179
  # When `lf.query` is used for symbolic completion, schema is automatically
178
180
  # inferred when it is None.
179
181
  if isinstance(prompt, pg.Symbolic) and prompt.sym_partial and schema is None:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: langfun
3
- Version: 0.0.2.dev20240207
3
+ Version: 0.0.2.dev20240209
4
4
  Summary: Langfun: Language as Functions.
5
5
  Home-page: https://github.com/google/langfun
6
6
  Author: Langfun Authors
@@ -24,7 +24,7 @@ License-File: LICENSE
24
24
  Requires-Dist: google-generativeai >=0.3.2
25
25
  Requires-Dist: jinja2 >=3.1.2
26
26
  Requires-Dist: openai ==0.27.2
27
- Requires-Dist: pyglove >=0.4.5.dev20240109
27
+ Requires-Dist: pyglove >=0.4.5.dev20240201
28
28
  Requires-Dist: requests >=2.31.0
29
29
  Requires-Dist: termcolor ==1.1.0
30
30
  Requires-Dist: tqdm >=4.64.1
@@ -1,14 +1,14 @@
1
1
  langfun/__init__.py,sha256=2HUBxiByAEu63XqaF89hQfI4sqFG1qGffua-JPy4XIY,1689
2
- langfun/core/__init__.py,sha256=0dIlw2ehlzx7XtTTAyDCXIsX_jKB2F6gQMki-bnqqNM,4108
2
+ langfun/core/__init__.py,sha256=dl7itWvZUEvqDeK2EWd-9lGlZu8cLXCO45HcaZKWAo4,4136
3
3
  langfun/core/component.py,sha256=VRPfDB_2jEnxcB3-HoiVjG4ID-SMenNPIsytb0uXMPg,9674
4
4
  langfun/core/component_test.py,sha256=VAPd6V_-odAe8rBvesW3ogYDd6OSqRq4FaPhfgOM4Zg,7949
5
- langfun/core/concurrent.py,sha256=If8fYv3BrdAuV5yysmPLz24UKlqiKCExD3l1ZkQqGCA,24114
5
+ langfun/core/concurrent.py,sha256=HQJOseNZ-XZZR5VmC8lHoDNFzlkkCa_-ri7nOKJfV5s,24147
6
6
  langfun/core/concurrent_test.py,sha256=qQT6_Dq5NVz7qXFLzSf2Rhzkfkh07gocjHMBaT1nSeE,14928
7
7
  langfun/core/console.py,sha256=bk5rNPNm9rMGW5YT2HixxU04p2umnoabn5SDz6Dqe88,2317
8
8
  langfun/core/console_test.py,sha256=5SYJdxpJGLgdSSQqqMPoA1X6jpsLD8rgcyk-EgI65oE,1077
9
9
  langfun/core/langfunc.py,sha256=266xNz8Vgal7K4HSsrYt7z7_qPYV4bWWK626IbbohrE,11573
10
10
  langfun/core/langfunc_test.py,sha256=ukv5cnad5ZBckM2PhyIFq79BPN0Db4cszMrPqh_CZkA,8163
11
- langfun/core/language_model.py,sha256=HG2XQhisyiyvMBws5dASH1OkbGJB3twn0p2e_As8hUo,12889
11
+ langfun/core/language_model.py,sha256=JHIfW0GxFx1YVEM-drS_Iy4goFJt63LBosCM4CILWTY,12920
12
12
  langfun/core/language_model_test.py,sha256=gcW4OJJjB-V1b4kEF8zG91t36sVn3H0Yuj0LQxi83Ek,9122
13
13
  langfun/core/memory.py,sha256=f-asN1F7Vehgdn_fK84v73GrEUOxRtaW934keutTKjk,2416
14
14
  langfun/core/message.py,sha256=QhvV9t5qaryPcruyxxcXi3gm9QDInkSldwTtK6sVJ3c,15734
@@ -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=6yO7eIuu2K4tchaAwbVcRro9mCGUzzZ_QbIGZB5P41c,6777
30
+ langfun/core/coding/python/correction.py,sha256=uuQmZCrAl0EA9etIUmn2-FZ-ge8iNcjOAAlm-WgkYfo,6776
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,8 +40,8 @@ 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=wWFDDrf0jBzs9H_5XfdZSeOBGXyUtXAJJouk7cLckSM,52602
44
- langfun/core/eval/base_test.py,sha256=uXu6EtTagolDIcSadnVyMmlrz6ixx943jkZhquCRQPI,21275
43
+ langfun/core/eval/base.py,sha256=tT_85jpLMCbXufKf64BMslid9FB1TNhe3AIkIpLULhA,53782
44
+ langfun/core/eval/base_test.py,sha256=cep-f0pj2o7Gd5KNQV-IP0blJ-dzhlcvnt4tSbqXun4,21177
45
45
  langfun/core/eval/matching.py,sha256=g2yuBb4FeOlAlB10hqdWvaIg4QVQlJbiViRDcD2Y8go,9567
46
46
  langfun/core/eval/matching_test.py,sha256=IfuMF_dEmy4VzK6tIldRzD2Nqlml7SSh4u-baFNcZrw,4912
47
47
  langfun/core/eval/scoring.py,sha256=mshqbV_WM0zcp15TSR32ACMBDymlsbf6YH06PPx1Tw0,6139
@@ -74,7 +74,7 @@ langfun/core/structured/mapping.py,sha256=lGkjhmvVdhBGgJmc5KbfT2xQjC1MuU4OCcCfsA
74
74
  langfun/core/structured/mapping_test.py,sha256=07DDCGbwytQHSMm7fCi5-Ly-JNgdV4ubHZq0wthX4A4,3338
75
75
  langfun/core/structured/parsing.py,sha256=V3i8-AuBI4zdpsi_f6H-mbQ3h0HPgCle2OnDQolWJnA,10244
76
76
  langfun/core/structured/parsing_test.py,sha256=2_Uf3LYNRON1-5ysEr75xiG_cAxR3ZiixSfvUQu6mOQ,20846
77
- langfun/core/structured/prompting.py,sha256=OmI21qQQikoQLAmr5W8nBJ8PWCu9w0lmsCnmbQg9hMc,6632
77
+ langfun/core/structured/prompting.py,sha256=wTnbb2gO4MZ7RdwUTY6f7cR35qq8sSM0iZcyTPjwfA8,6663
78
78
  langfun/core/structured/prompting_test.py,sha256=8lakKCidYuRlf-U1KexTOqQdKrBXUt8fb2J7epCdt84,19143
79
79
  langfun/core/structured/schema.py,sha256=5DKba0LrvXCJFRY-NVfER3p54BLOB7M3Yi2-u5IAJTw,24115
80
80
  langfun/core/structured/schema_test.py,sha256=LEtCST5Bfwoke59I6Q1mnOJLf2cFXQwKwTeAkI2hgqM,20912
@@ -87,8 +87,8 @@ langfun/core/templates/demonstration.py,sha256=vCrgYubdZM5Umqcgp8NUVGXgr4P_c-fik
87
87
  langfun/core/templates/demonstration_test.py,sha256=SafcDQ0WgI7pw05EmPI2S4v1t3ABKzup8jReCljHeK4,2162
88
88
  langfun/core/templates/selfplay.py,sha256=yhgrJbiYwq47TgzThmHrDQTF4nDrTI09CWGhuQPNv-s,2273
89
89
  langfun/core/templates/selfplay_test.py,sha256=IB5rWbjK_9CTkqEo1BclQPzFAKcIiusJckH8J19HFgI,2096
90
- langfun-0.0.2.dev20240207.dist-info/LICENSE,sha256=WNHhf_5RCaeuKWyq_K39vmp9F28LxKsB4SpomwSZ2L0,11357
91
- langfun-0.0.2.dev20240207.dist-info/METADATA,sha256=NPHG-e-l1M32PgSNSOdNo8y3pUUJOAOnv3M_dw5nlzs,3368
92
- langfun-0.0.2.dev20240207.dist-info/WHEEL,sha256=oiQVh_5PnQM0E3gPdiz09WCNmwiHDMaGer_elqB3coM,92
93
- langfun-0.0.2.dev20240207.dist-info/top_level.txt,sha256=RhlEkHxs1qtzmmtWSwYoLVJAc1YrbPtxQ52uh8Z9VvY,8
94
- langfun-0.0.2.dev20240207.dist-info/RECORD,,
90
+ langfun-0.0.2.dev20240209.dist-info/LICENSE,sha256=WNHhf_5RCaeuKWyq_K39vmp9F28LxKsB4SpomwSZ2L0,11357
91
+ langfun-0.0.2.dev20240209.dist-info/METADATA,sha256=7arY2SNgfb7JcbwaIKwgOwTeRHElh_KNrWKiscHLdiM,3368
92
+ langfun-0.0.2.dev20240209.dist-info/WHEEL,sha256=oiQVh_5PnQM0E3gPdiz09WCNmwiHDMaGer_elqB3coM,92
93
+ langfun-0.0.2.dev20240209.dist-info/top_level.txt,sha256=RhlEkHxs1qtzmmtWSwYoLVJAc1YrbPtxQ52uh8Z9VvY,8
94
+ langfun-0.0.2.dev20240209.dist-info/RECORD,,