lionagi 0.0.315__py3-none-any.whl → 0.1.0__py3-none-any.whl

Sign up to get free protection for your applications and to get access to all the features.
Files changed (103) hide show
  1. lionagi/core/__init__.py +19 -8
  2. lionagi/core/agent/__init__.py +0 -3
  3. lionagi/core/agent/base_agent.py +26 -30
  4. lionagi/core/branch/__init__.py +0 -4
  5. lionagi/core/branch/{base_branch.py → base.py} +13 -14
  6. lionagi/core/branch/branch.py +22 -20
  7. lionagi/core/branch/executable_branch.py +0 -347
  8. lionagi/core/branch/{branch_flow_mixin.py → flow_mixin.py} +6 -6
  9. lionagi/core/branch/util.py +1 -1
  10. lionagi/core/direct/__init__.py +13 -1
  11. lionagi/core/direct/cot.py +123 -1
  12. lionagi/core/direct/plan.py +164 -0
  13. lionagi/core/direct/predict.py +13 -9
  14. lionagi/core/direct/react.py +12 -8
  15. lionagi/core/direct/score.py +4 -4
  16. lionagi/core/direct/select.py +4 -4
  17. lionagi/core/direct/utils.py +23 -0
  18. lionagi/core/direct/vote.py +2 -2
  19. lionagi/core/execute/base_executor.py +50 -0
  20. lionagi/core/execute/branch_executor.py +233 -0
  21. lionagi/core/execute/instruction_map_executor.py +131 -0
  22. lionagi/core/execute/structure_executor.py +218 -0
  23. lionagi/core/flow/monoflow/ReAct.py +4 -4
  24. lionagi/core/flow/monoflow/chat.py +6 -6
  25. lionagi/core/flow/monoflow/chat_mixin.py +24 -34
  26. lionagi/core/flow/monoflow/followup.py +4 -4
  27. lionagi/core/flow/polyflow/__init__.py +1 -1
  28. lionagi/core/flow/polyflow/chat.py +15 -12
  29. lionagi/core/{prompt/action_template.py → form/action_form.py} +2 -2
  30. lionagi/core/{prompt → form}/field_validator.py +40 -31
  31. lionagi/core/form/form.py +302 -0
  32. lionagi/core/form/mixin.py +214 -0
  33. lionagi/core/{prompt/scored_template.py → form/scored_form.py} +2 -2
  34. lionagi/core/generic/__init__.py +37 -0
  35. lionagi/core/generic/action.py +26 -0
  36. lionagi/core/generic/component.py +457 -0
  37. lionagi/core/generic/condition.py +44 -0
  38. lionagi/core/generic/data_logger.py +305 -0
  39. lionagi/core/generic/edge.py +110 -0
  40. lionagi/core/generic/mail.py +90 -0
  41. lionagi/core/generic/mailbox.py +36 -0
  42. lionagi/core/generic/node.py +285 -0
  43. lionagi/core/generic/relation.py +70 -0
  44. lionagi/core/generic/signal.py +22 -0
  45. lionagi/core/generic/structure.py +362 -0
  46. lionagi/core/generic/transfer.py +20 -0
  47. lionagi/core/generic/work.py +40 -0
  48. lionagi/core/graph/graph.py +126 -0
  49. lionagi/core/graph/tree.py +190 -0
  50. lionagi/core/mail/__init__.py +0 -8
  51. lionagi/core/mail/mail_manager.py +12 -10
  52. lionagi/core/mail/schema.py +9 -2
  53. lionagi/core/messages/__init__.py +0 -3
  54. lionagi/core/messages/schema.py +17 -225
  55. lionagi/core/session/__init__.py +0 -3
  56. lionagi/core/session/session.py +25 -23
  57. lionagi/core/tool/__init__.py +3 -1
  58. lionagi/core/tool/tool.py +28 -0
  59. lionagi/core/tool/tool_manager.py +75 -75
  60. lionagi/integrations/chunker/chunk.py +7 -7
  61. lionagi/integrations/config/oai_configs.py +4 -4
  62. lionagi/integrations/loader/load.py +6 -6
  63. lionagi/integrations/loader/load_util.py +8 -8
  64. lionagi/libs/ln_api.py +3 -3
  65. lionagi/libs/ln_parse.py +43 -6
  66. lionagi/libs/ln_validate.py +288 -0
  67. lionagi/libs/sys_util.py +28 -6
  68. lionagi/tests/libs/test_async.py +0 -0
  69. lionagi/tests/libs/test_field_validators.py +353 -0
  70. lionagi/tests/test_core/test_base_branch.py +0 -1
  71. lionagi/tests/test_core/test_branch.py +3 -0
  72. lionagi/tests/test_core/test_session_base_util.py +1 -0
  73. lionagi/version.py +1 -1
  74. {lionagi-0.0.315.dist-info → lionagi-0.1.0.dist-info}/METADATA +1 -1
  75. lionagi-0.1.0.dist-info/RECORD +136 -0
  76. lionagi/core/prompt/prompt_template.py +0 -312
  77. lionagi/core/schema/__init__.py +0 -22
  78. lionagi/core/schema/action_node.py +0 -29
  79. lionagi/core/schema/base_mixin.py +0 -296
  80. lionagi/core/schema/base_node.py +0 -199
  81. lionagi/core/schema/condition.py +0 -24
  82. lionagi/core/schema/data_logger.py +0 -354
  83. lionagi/core/schema/data_node.py +0 -93
  84. lionagi/core/schema/prompt_template.py +0 -67
  85. lionagi/core/schema/structure.py +0 -912
  86. lionagi/core/tool/manual.py +0 -1
  87. lionagi-0.0.315.dist-info/RECORD +0 -121
  88. /lionagi/core/{branch/base → execute}/__init__.py +0 -0
  89. /lionagi/core/flow/{base/baseflow.py → baseflow.py} +0 -0
  90. /lionagi/core/flow/{base/__init__.py → mono_chat_mixin.py} +0 -0
  91. /lionagi/core/{prompt → form}/__init__.py +0 -0
  92. /lionagi/{tests/test_integrations → core/graph}/__init__.py +0 -0
  93. /lionagi/tests/{test_libs → integrations}/__init__.py +0 -0
  94. /lionagi/tests/{test_libs/test_async.py → libs/__init__.py} +0 -0
  95. /lionagi/tests/{test_libs → libs}/test_api.py +0 -0
  96. /lionagi/tests/{test_libs → libs}/test_convert.py +0 -0
  97. /lionagi/tests/{test_libs → libs}/test_func_call.py +0 -0
  98. /lionagi/tests/{test_libs → libs}/test_nested.py +0 -0
  99. /lionagi/tests/{test_libs → libs}/test_parse.py +0 -0
  100. /lionagi/tests/{test_libs → libs}/test_sys_util.py +0 -0
  101. {lionagi-0.0.315.dist-info → lionagi-0.1.0.dist-info}/LICENSE +0 -0
  102. {lionagi-0.0.315.dist-info → lionagi-0.1.0.dist-info}/WHEEL +0 -0
  103. {lionagi-0.0.315.dist-info → lionagi-0.1.0.dist-info}/top_level.txt +0 -0
@@ -5,14 +5,10 @@ This module contains mixins for configuring and invoking chatbots.
5
5
  from abc import ABC
6
6
  from typing import Any
7
7
 
8
+ import re
9
+ from lionagi.libs import nested, func_call, convert, StringMatch, ParseUtil
10
+ from lionagi.core.tool.tool import TOOL_TYPE
8
11
  from lionagi.core.messages.schema import Instruction
9
- from lionagi.core.schema.base_node import TOOL_TYPE
10
- from lionagi.libs import (
11
- ln_nested as nested,
12
- ln_func_call as func_call,
13
- ln_convert as convert,
14
- )
15
- from lionagi.libs.ln_parse import ParseUtil, StringMatch
16
12
 
17
13
 
18
14
  class MonoChatConfigMixin(ABC):
@@ -21,8 +17,8 @@ class MonoChatConfigMixin(ABC):
21
17
 
22
18
  Methods:
23
19
  _create_chat_config(self, instruction=None, context=None, sender=None, system=None,
24
- output_fields=None, prompt_template=None, tools=False, **kwargs) -> Any:
25
- Creates a chat configuration based on the provided parameters.
20
+ output_fields=None, form=None, tools=False, **kwargs) -> Any:
21
+ Creates a chat configuration based on the provided parameters.
26
22
  """
27
23
 
28
24
  def _create_chat_config(
@@ -32,7 +28,7 @@ class MonoChatConfigMixin(ABC):
32
28
  sender: str | None = None,
33
29
  system: str | dict[str, Any] | None = None,
34
30
  output_fields=None,
35
- prompt_template=None,
31
+ form=None,
36
32
  tools: TOOL_TYPE = False,
37
33
  **kwargs,
38
34
  ) -> Any:
@@ -45,7 +41,7 @@ class MonoChatConfigMixin(ABC):
45
41
  sender (str): The sender of the message (optional).
46
42
  system (str | dict[str, Any]): The system message for the chatbot (optional).
47
43
  output_fields: The output fields for the chatbot (optional).
48
- prompt_template: The prompt template for the chatbot (optional).
44
+ form: The prompt template for the chatbot (optional).
49
45
  tools (TOOL_TYPE): The tools for the chatbot (default: False).
50
46
  **kwargs: Additional keyword arguments for the chat configuration.
51
47
 
@@ -55,7 +51,7 @@ class MonoChatConfigMixin(ABC):
55
51
  if system:
56
52
  self.branch.change_first_system_message(system)
57
53
 
58
- if not prompt_template:
54
+ if not form:
59
55
  self.branch.add_message(
60
56
  instruction=instruction,
61
57
  context=context,
@@ -63,7 +59,7 @@ class MonoChatConfigMixin(ABC):
63
59
  output_fields=output_fields,
64
60
  )
65
61
  else:
66
- instruct_ = Instruction.from_prompt_template(prompt_template)
62
+ instruct_ = Instruction.from_form(form)
67
63
  self.branch.add_message(instruction=instruct_)
68
64
 
69
65
  if "tool_parsed" in kwargs:
@@ -85,8 +81,8 @@ class MonoChatInvokeMixin(ABC):
85
81
  Mixin class for invoking chatbots.
86
82
 
87
83
  Methods:
88
- async _output(self, invoke, out, output_fields, func_calls_=None, prompt_template=None,
89
- return_template=True):
84
+ async _output(self, invoke, out, output_fields, func_calls_=None, form=None,
85
+ return_template=True):
90
86
  Processes the output of the chatbot.
91
87
 
92
88
  _return_response(content_, output_fields) -> Any:
@@ -108,7 +104,7 @@ class MonoChatInvokeMixin(ABC):
108
104
  out,
109
105
  output_fields,
110
106
  func_calls_=None,
111
- prompt_template=None,
107
+ form=None,
112
108
  return_template=True,
113
109
  ):
114
110
  """
@@ -119,7 +115,7 @@ class MonoChatInvokeMixin(ABC):
119
115
  out: Flag indicating whether to return the output.
120
116
  output_fields: The output fields for the chatbot.
121
117
  func_calls_: The function calls for invoking the tools (optional).
122
- prompt_template: The prompt template for the chatbot (optional).
118
+ form: The prompt template for the chatbot (optional).
123
119
  return_template (bool): Flag indicating whether to return the prompt template (default: True).
124
120
  """
125
121
 
@@ -132,9 +128,10 @@ class MonoChatInvokeMixin(ABC):
132
128
  pass
133
129
 
134
130
  response_ = self._return_response(content_, output_fields)
135
- if prompt_template:
136
- prompt_template._process_response(response_)
137
- return prompt_template if return_template else prompt_template.out
131
+
132
+ if form:
133
+ form._process_response(response_)
134
+ return form if return_template else form.outputs
138
135
 
139
136
  if out:
140
137
  return response_
@@ -159,24 +156,17 @@ class MonoChatInvokeMixin(ABC):
159
156
 
160
157
  if output_fields:
161
158
  try:
162
- if isinstance(out_, dict):
163
- out_ = convert.to_str(out_.values())
164
-
165
- if isinstance(out_, str):
166
- try:
167
- out_ = ParseUtil.md_to_json(out_)
168
- except Exception:
169
- out_ = ParseUtil.md_to_json(out_.replace("'", '"'))
170
-
171
- out_ = StringMatch.correct_keys(output_fields=output_fields, out_=out_)
159
+ return StringMatch.force_validate_dict(
160
+ out_, keys=list(output_fields.keys())
161
+ )
172
162
  except Exception:
173
163
  pass
174
164
 
175
165
  if isinstance(out_, str):
176
166
  try:
177
- out_ = ParseUtil.md_to_json(out_)
178
- out_ = StringMatch.correct_keys(output_fields=output_fields, out_=out_)
179
- return out_
167
+ match = re.search(r"```json\n({.*?})\n```", out_, re.DOTALL)
168
+ if match:
169
+ out_ = ParseUtil.fuzzy_parse_json(match.group(1))
180
170
  except Exception:
181
171
  pass
182
172
 
@@ -260,4 +250,4 @@ class MonoChatMixin(MonoChatConfigMixin, MonoChatInvokeMixin, ABC):
260
250
  Mixin class that combines MonoChatConfigMixin and MonoChatInvokeMixin.
261
251
  """
262
252
 
263
- pass
253
+ pass
@@ -6,9 +6,9 @@ process instructions, system messages, and invoke tools during the conversation.
6
6
  """
7
7
 
8
8
  from typing import Callable
9
- from lionagi.core.messages import Instruction
10
- from lionagi.core.schema import Tool
11
- from .chat import MonoChat
9
+ from lionagi.core.messages.schema import Instruction
10
+ from lionagi.core.tool.tool import Tool
11
+ from lionagi.core.flow.monoflow.chat import MonoChat
12
12
 
13
13
 
14
14
  class MonoFollowup(MonoChat):
@@ -211,4 +211,4 @@ class MonoFollowup(MonoChat):
211
211
  instruction=instruction,
212
212
  )
213
213
  _out = await self.chat(_prompt, sender=sender, **kwargs)
214
- return _out if out else None
214
+ return _out if out else None
@@ -1 +1 @@
1
- from .chat import PolyChat
1
+ from .chat import PolyChat
@@ -8,13 +8,10 @@ created branches within the session.
8
8
 
9
9
  from typing import Any
10
10
 
11
- from lionagi.libs import ln_convert as convert
12
- from lionagi.libs.ln_async import AsyncUtil
13
-
11
+ from lionagi.libs import convert, AsyncUtil
14
12
  from lionagi.core.messages.schema import Instruction
15
13
  from lionagi.core.branch.branch import Branch
16
-
17
- from lionagi.core.flow.base.baseflow import BasePolyFlow
14
+ from lionagi.core.flow.baseflow import BasePolyFlow
18
15
 
19
16
 
20
17
  class PolyChat(BasePolyFlow):
@@ -22,17 +19,23 @@ class PolyChat(BasePolyFlow):
22
19
  A class for performing parallel chat conversations with multiple branches.
23
20
 
24
21
  Methods:
25
- __init__(self, session) -> None:
22
+ __init__(self, session: Any) -> None:
26
23
  Initializes the PolyChat instance.
27
24
 
28
- async parallel_chat(self, instruction, num_instances=1, context=None, sender=None, branch_system=None,
29
- messages=None, tools=False, out=True, invoke=True, output_fields=None,
30
- persist_path=None, branch_config=None, explode=False, **kwargs) -> Any:
25
+ async parallel_chat(self, instruction: Union[Instruction, str], num_instances: int = 1,
26
+ context: Optional[Any] = None, sender: Optional[str] = None,
27
+ branch_system: Optional[Any] = None, messages: Optional[Any] = None,
28
+ tools: bool = False, out: bool = True, invoke: bool = True,
29
+ output_fields: Optional[Any] = None, persist_path: Optional[str] = None,
30
+ branch_config: Optional[dict] = None, explode: bool = False, **kwargs) -> Any:
31
31
  Performs parallel chat conversations with multiple branches.
32
32
 
33
- async _parallel_chat(self, instruction, num_instances=1, context=None, sender=None, messages=None,
34
- tools=False, out=True, invoke=True, output_fields=None, persist_path=None,
35
- branch_config={}, explode=False, include_mapping=True, default_key="response",
33
+ async _parallel_chat(self, instruction: Union[Instruction, str], num_instances: int = 1,
34
+ context: Optional[Any] = None, sender: Optional[str] = None,
35
+ messages: Optional[Any] = None, tools: bool = False, out: bool = True,
36
+ invoke: bool = True, output_fields: Optional[Any] = None,
37
+ persist_path: Optional[str] = None, branch_config: dict = {},
38
+ explode: bool = False, include_mapping: bool = True, default_key: str = "response",
36
39
  **kwargs) -> Any:
37
40
  Internal method for performing parallel chat conversations with multiple branches.
38
41
  """
@@ -1,13 +1,13 @@
1
1
  from typing import Any
2
2
  from lionagi.integrations.bridge.pydantic_.pydantic_bridge import Field
3
3
 
4
- from .scored_template import ScoredTemplate
4
+ from lionagi.core.form.scored_form import ScoredForm
5
5
 
6
6
 
7
7
  class ActionRequest: ...
8
8
 
9
9
 
10
- class ActionedTemplate(ScoredTemplate):
10
+ class ActionForm(ScoredForm):
11
11
 
12
12
  action_needed: bool | None = Field(
13
13
  False, description="true if actions are needed else false"
@@ -9,8 +9,16 @@ maps data types to their corresponding validation functions.
9
9
  from lionagi.libs import convert, StringMatch, ParseUtil
10
10
 
11
11
 
12
- def _has_action_keys(dict_):
13
- return list(dict_.keys()) >= ["function", "arguments"]
12
+ def check_dict_field(x, keys: list[str] | dict, fix_=True, **kwargs):
13
+ if isinstance(x, dict):
14
+ return x
15
+ if fix_:
16
+ try:
17
+ x = convert.to_str(x)
18
+ return StringMatch.force_validate_dict(x, keys=keys, **kwargs)
19
+ except Exception as e:
20
+ raise ValueError("Invalid dict field type.") from e
21
+ raise ValueError(f"Default value for DICT must be a dict, got {type(x).__name__}")
14
22
 
15
23
 
16
24
  def check_action_field(x, fix_=True, **kwargs):
@@ -27,26 +35,6 @@ def check_action_field(x, fix_=True, **kwargs):
27
35
  raise ValueError("Invalid action field type.") from e
28
36
 
29
37
 
30
- def _fix_action_field(x, discard_=True):
31
- corrected = []
32
- if isinstance(x, str):
33
- x = ParseUtil.fuzzy_parse_json(x)
34
-
35
- try:
36
- x = convert.to_list(x)
37
-
38
- for i in x:
39
- i = convert.to_dict(i)
40
- if _has_action_keys(i):
41
- corrected.append(i)
42
- elif not discard_:
43
- raise ValueError(f"Invalid action field: {i}")
44
- except Exception as e:
45
- raise ValueError(f"Invalid action field: {e}") from e
46
-
47
- return corrected
48
-
49
-
50
38
  def check_number_field(x, fix_=True, **kwargs):
51
39
  """
52
40
  Checks if the given value is a valid numeric field.
@@ -171,6 +159,30 @@ def check_enum_field(x, choices, fix_=True, **kwargs):
171
159
  return x
172
160
 
173
161
 
162
+ def _has_action_keys(dict_):
163
+ return list(dict_.keys()) >= ["function", "arguments"]
164
+
165
+
166
+ def _fix_action_field(x, discard_=True):
167
+ corrected = []
168
+ if isinstance(x, str):
169
+ x = ParseUtil.fuzzy_parse_json(x)
170
+
171
+ try:
172
+ x = convert.to_list(x)
173
+
174
+ for i in x:
175
+ i = convert.to_dict(i)
176
+ if _has_action_keys(i):
177
+ corrected.append(i)
178
+ elif not discard_:
179
+ raise ValueError(f"Invalid action field: {i}")
180
+ except Exception as e:
181
+ raise ValueError(f"Invalid action field: {e}") from e
182
+
183
+ return corrected
184
+
185
+
174
186
  def _fix_number_field(x, *args, **kwargs):
175
187
  """
176
188
  Attempts to fix an invalid numeric field value.
@@ -209,17 +221,13 @@ def _fix_bool_field(x):
209
221
  ValueError: If the value cannot be converted into a valid boolean value.
210
222
  """
211
223
  try:
212
- x = convert.to_str(x)
213
- if (
214
- convert.strip_lower(x) in ["true", "1", "correct", "yes"]
215
- or convert.to_num(x) == 1
216
- ):
224
+ x = convert.strip_lower(convert.to_str(x))
225
+ if x in ["true", "1", "correct", "yes"]:
217
226
  return True
218
- elif (
219
- convert.strip_lower(x) in ["false", "0", "incorrect", "no", "none", "n/a"]
220
- or convert.to_num(x) == 0
221
- ):
227
+
228
+ elif x in ["false", "0", "incorrect", "no", "none", "n/a"]:
222
229
  return False
230
+
223
231
  raise ValueError(f"Failed to convert {x} into a boolean value")
224
232
  except Exception as e:
225
233
  raise ValueError(f"Failed to convert {x} into a boolean value") from e
@@ -275,4 +283,5 @@ validation_funcs = {
275
283
  "str": check_str_field,
276
284
  "enum": check_enum_field,
277
285
  "action": check_action_field,
286
+ "dict": check_dict_field,
278
287
  }
@@ -0,0 +1,302 @@
1
+ from typing import Any
2
+ from pydantic import Field
3
+
4
+ from lionagi.libs import convert, func_call
5
+
6
+ from lionagi.core.generic import BaseComponent
7
+ from lionagi.core.form.field_validator import validation_funcs
8
+
9
+
10
+ non_prompt_words = [
11
+ "id_",
12
+ "node_id",
13
+ "meta",
14
+ "metadata",
15
+ "timestamp",
16
+ "content",
17
+ "signature",
18
+ "task",
19
+ "template_name",
20
+ "version",
21
+ "description",
22
+ "in_validation_kwargs",
23
+ "out_validation_kwargs",
24
+ "fix_input",
25
+ "fix_output",
26
+ "input_fields",
27
+ "output_fields",
28
+ "choices",
29
+ "prompt_fields",
30
+ "prompt_fields_annotation",
31
+ "instruction_context",
32
+ "instruction",
33
+ "instruction_output_fields",
34
+ "inputs",
35
+ "outputs",
36
+ "process",
37
+ "_validate_field",
38
+ "_process_input",
39
+ "_process_response",
40
+ "_validate_field_choices",
41
+ "_validate_input_choices",
42
+ "_validate_output_choices",
43
+ ]
44
+
45
+
46
+ class Form(BaseComponent):
47
+ template_name: str = Field(
48
+ default="default_form",
49
+ description="The name of the prompt template.",
50
+ )
51
+ signature: str = Field("null", description="signature indicating inputs, outputs")
52
+ version: str | float | int | None = Field(
53
+ default=None, description="The version of the prompt template."
54
+ )
55
+ description: str | dict[str, Any] | None | Any = Field(
56
+ default=None, description="The description of the prompt template."
57
+ )
58
+ task: str | dict[str, Any] | None = Field(
59
+ default=None, description="The task associated with the prompt template."
60
+ )
61
+ out_validation_kwargs: dict[str, Any] = Field(
62
+ default_factory=dict, description="validation kwargs for output"
63
+ )
64
+ in_validation_kwargs: dict[str, Any] = Field(
65
+ default_factory=dict, description="validation kwargs for input"
66
+ )
67
+ fix_input: bool = Field(True, description="whether to fix input")
68
+ fix_output: bool = Field(True, description="whether to fix output")
69
+ input_fields: list[str] = Field(
70
+ default_factory=list, description="Extracted input fields from the signature."
71
+ )
72
+ output_fields: list[str] = Field(
73
+ default_factory=list, description="Extracted output fields from the signature."
74
+ )
75
+ choices: dict[str, list[str]] = Field(
76
+ default_factory=dict, description="Choices available for each template field."
77
+ )
78
+
79
+ def __init__(self, **kwargs):
80
+ super().__init__(**kwargs)
81
+ self.input_fields, self.output_fields = self._get_input_output_fields(
82
+ self.signature
83
+ )
84
+ self.process(in_=True)
85
+
86
+ @property
87
+ def prompt_fields(self):
88
+ return self.input_fields + self.output_fields
89
+
90
+ @property
91
+ def instruction_context(self):
92
+ a = "".join(
93
+ f"""
94
+ ## input: {i}:
95
+ - description: {self.model_fields[i].description}
96
+ - value: {str(self.__getattribute__(self.input_fields[idx]))}
97
+ """
98
+ for idx, i in enumerate(self.input_fields)
99
+ )
100
+ return a.replace(" ", "")
101
+
102
+ @property
103
+ def instruction(self):
104
+ ccc = f"""
105
+ 0. Your task is {self.task},
106
+ 1. provided: {self.input_fields},
107
+ 2. requested: {self.output_fields}
108
+ ----------
109
+ """
110
+ return ccc.replace(" ", "")
111
+
112
+ @property
113
+ def instruction_output_fields(self):
114
+ return {i: self.model_fields[i].description for i in self.output_fields}
115
+
116
+ @property
117
+ def inputs(self):
118
+ return {i: getattr(self, i) for i in self.input_fields}
119
+
120
+ @property
121
+ def outputs(self):
122
+ return {i: getattr(self, i) for i in self.output_fields}
123
+
124
+ def process(self, in_=None, out_=None):
125
+ if in_:
126
+ self._process_input()
127
+ self._validate_input_choices()
128
+ if out_:
129
+ self._process_response(out_)
130
+ self._validate_output_choices()
131
+ return self
132
+
133
+ def _validate_field_choices(self, fields, fix_: bool = False):
134
+ if len(self.choices) >= 1:
135
+ for k, choices in self.choices.items():
136
+ if k in fields and not self._validate_field(
137
+ k, getattr(self, k), choices, fix_
138
+ ):
139
+ raise ValueError(
140
+ f"Invalid choice for field {k}: {getattr(self, k)} is not in {choices}"
141
+ )
142
+
143
+ def _validate_input_choices(self):
144
+ return self._validate_field_choices(self.input_fields, self.fix_input)
145
+
146
+ def _validate_output_choices(self):
147
+ return self._validate_field_choices(self.output_fields, self.fix_output)
148
+
149
+ def _validate_field(self, k, v, choices=None, keys=None, fix_=False, **kwargs):
150
+
151
+ str_ = self._prompt_fields_annotation[k]
152
+
153
+ if keys:
154
+ v_ = validation_funcs["dict"](v, keys=keys, fix_=fix_, **kwargs)
155
+ setattr(self, k, v_)
156
+ return True
157
+
158
+ if choices:
159
+ v_ = validation_funcs["enum"](v, choices=choices, fix_=fix_, **kwargs)
160
+ if v_ not in choices:
161
+ raise ValueError(f"{v} is not in chocies {choices}")
162
+ setattr(self, k, v_)
163
+ return True
164
+
165
+ if "lionagi.core.form.action_form.actionrequest" in str_:
166
+ self.__setattr__(k, validation_funcs["action"](v))
167
+ return True
168
+
169
+ if "bool" in str_ and "str" not in str_:
170
+ self.__setattr__(k, validation_funcs["bool"](v, fix_=fix_, **kwargs))
171
+ return True
172
+
173
+ if any(i in str_ for i in ["int", "float", "number"]) and "str" not in str_:
174
+ self.__setattr__(k, validation_funcs["number"](v, fix_=fix_, **kwargs))
175
+ return True
176
+
177
+ elif "str" in str_:
178
+ self.__setattr__(k, validation_funcs["str"](v, fix_=fix_, **kwargs))
179
+ return True
180
+
181
+ return False
182
+
183
+ def _process_input(self, fix_=False):
184
+ kwargs = self.in_validation_kwargs.copy()
185
+ for k, v in self.inputs.items():
186
+ if k not in kwargs:
187
+ kwargs = {k: {}}
188
+
189
+ if self._field_has_choices(k):
190
+ self.choices[k] = self.model_fields[k].json_schema_extra["choices"]
191
+ if self._validate_field(
192
+ k, v, choices=self.choices[k], fix_=fix_, **kwargs[k]
193
+ ):
194
+ continue
195
+ else:
196
+ raise ValueError(f"{k} has no choices")
197
+
198
+ elif self._validate_field(k, v, fix_=fix_, **kwargs[k]):
199
+ continue
200
+ else:
201
+ raise ValueError(f"failed to validate field {k}")
202
+
203
+ def _get_field_attr(self, k, attr) -> Any:
204
+ if not self._field_has_attr(k, attr):
205
+ raise ValueError(f"field {k} has no attribute {attr}")
206
+ field = self.model_fields[k]
207
+ a = getattr(field, attr)
208
+ if not a:
209
+ try:
210
+ a = field.json_schema_extra[attr]
211
+ return a
212
+ except Exception:
213
+ return None
214
+ return a
215
+
216
+ def _field_has_attr(self, k, attr):
217
+ a = False
218
+
219
+ field = self.model_fields[k]
220
+ a = hasattr(field, attr)
221
+
222
+ if not a:
223
+ try:
224
+ a = (
225
+ self.model_fields[k].json_schema_extra[attr] is not None
226
+ and attr in self.model_fields[k].json_schema_extra
227
+ )
228
+ return a if isinstance(a, bool) else False
229
+ except Exception:
230
+ return False
231
+
232
+ def _field_has_keys(self, k):
233
+ return self._field_has_attr(k, "keys")
234
+
235
+ def _field_has_choices(self, k):
236
+ return self._field_has_attr(k, "choices")
237
+
238
+ def _process_choices(self, k, v, fix_=False, kwargs=None):
239
+ choices = self._get_field_attr(k, "choices")
240
+
241
+ if self._validate_field(k, v, choices=choices, fix_=fix_, **kwargs):
242
+ self.choices[k] = choices
243
+ return True
244
+ else:
245
+ raise ValueError(f"{k} has no choices")
246
+
247
+ def _process_keys(self, k, v, fix_=False, kwargs=None):
248
+ keys = self._get_field_attr(k, "keys")
249
+ if self._validate_field(k, v, keys=keys, fix_=fix_, **kwargs):
250
+ return True
251
+ else:
252
+ raise ValueError(f"{k} has no keys")
253
+
254
+ def _process_response(self, out_, fix_=fix_output):
255
+ kwargs = self.out_validation_kwargs.copy()
256
+ for k, v in out_.items():
257
+ if k not in kwargs:
258
+ kwargs = {k: {}}
259
+
260
+ if self._field_has_choices(k):
261
+ try:
262
+ return self._process_choices(k, v, fix_=fix_, kwargs=kwargs[k])
263
+ except Exception as e:
264
+ raise ValueError(
265
+ f"failed to process field {k} with value {v}"
266
+ ) from e
267
+
268
+ elif self._field_has_keys(k):
269
+ try:
270
+ return self._process_keys(k, v, fix_=fix_, kwargs=kwargs[k])
271
+ except Exception as e:
272
+ raise ValueError(
273
+ f"failed to process field {k} with value {v}"
274
+ ) from e
275
+
276
+ elif self._validate_field(k, v, fix_=fix_, **kwargs[k]):
277
+ continue
278
+
279
+ else:
280
+ raise ValueError(f"failed to validate field {k} with value {v}")
281
+
282
+ @staticmethod
283
+ def _get_input_output_fields(str_: str) -> Any:
284
+ inputs, outputs = str_.split("->")
285
+
286
+ input_fields = [convert.strip_lower(i) for i in inputs.split(",")]
287
+ output_fields = [convert.strip_lower(o) for o in outputs.split(",")]
288
+
289
+ return input_fields, output_fields
290
+
291
+ @property
292
+ def _prompt_fields_annotation(self):
293
+ dict_ = {i: self.model_fields[i].annotation for i in self.prompt_fields}
294
+ for k, v in dict_.items():
295
+ if "|" in str(v):
296
+ v = str(v)
297
+ v = v.split("|")
298
+ dict_[k] = func_call.lcall(v, convert.strip_lower)
299
+ else:
300
+ dict_[k] = [v.__name__]
301
+
302
+ return dict_