lionagi 0.0.312__py3-none-any.whl → 0.0.314__py3-none-any.whl

Sign up to get free protection for your applications and to get access to all the features.
@@ -1,6 +1,7 @@
1
1
  from .predict import predict
2
2
  from .select import select
3
3
  from .score import score
4
+ from .react import react
4
5
  from .vote import vote
5
6
 
6
- __all__ = ["predict", "select", "score", "vote"]
7
+ __all__ = ["predict", "select", "score", "vote", "react"]
@@ -6,9 +6,10 @@ using a language model. It includes fields for the input sentence, number of sen
6
6
  confidence score, and reason for the prediction.
7
7
  """
8
8
 
9
- from pydantic import Field
10
9
  from lionagi.libs import func_call
11
- from ..prompt.prompt_template import ScoredTemplate
10
+ from lionagi.integrations.bridge.pydantic_.pydantic_bridge import Field
11
+
12
+ from ..prompt.scored_template import ScoredTemplate
12
13
  from ..branch import Branch
13
14
 
14
15
 
@@ -0,0 +1,167 @@
1
+ from lionagi.libs import func_call, convert, AsyncUtil
2
+
3
+ from lionagi.integrations.bridge.pydantic_.pydantic_bridge import Field
4
+ from ..prompt.action_template import ActionedTemplate
5
+ from ..branch import Branch
6
+
7
+
8
+ class ReactTemplate(ActionedTemplate):
9
+ template_name: str = "default_react"
10
+ sentence: str | list | dict = Field(
11
+ default_factory=str,
12
+ description="the given sentence(s) to reason and take actions on",
13
+ )
14
+
15
+ def __init__(
16
+ self,
17
+ sentence=None,
18
+ instruction=None,
19
+ confidence_score=False,
20
+ **kwargs,
21
+ ):
22
+ super().__init__(**kwargs)
23
+
24
+ self.sentence = sentence
25
+ self.task = f"Think step by step. Perform reasoning and prepare actions with given tools only.Instruction: {instruction}. Absolutely DO NOT MAKE UP FUNCTIONS !!!"
26
+
27
+ if confidence_score:
28
+ self.output_fields.append("confidence_score")
29
+
30
+
31
+ async def _react(
32
+ sentence,
33
+ *,
34
+ instruction=None,
35
+ branch=None,
36
+ confidence_score=False,
37
+ retries=2,
38
+ delay=0.5,
39
+ backoff_factor=2,
40
+ default_value=None,
41
+ timeout=None,
42
+ branch_name=None,
43
+ system=None,
44
+ messages=None,
45
+ service=None,
46
+ sender=None,
47
+ llmconfig=None,
48
+ tools=None,
49
+ datalogger=None,
50
+ persist_path=None,
51
+ tool_manager=None,
52
+ return_branch=False,
53
+ **kwargs,
54
+ ):
55
+
56
+ if "temperature" not in kwargs:
57
+ kwargs["temperature"] = 0.1
58
+
59
+ instruction = instruction or ""
60
+
61
+ branch = branch or Branch(
62
+ name=branch_name,
63
+ system=system,
64
+ messages=messages,
65
+ service=service,
66
+ sender=sender,
67
+ llmconfig=llmconfig,
68
+ tools=tools,
69
+ datalogger=datalogger,
70
+ persist_path=persist_path,
71
+ tool_manager=tool_manager,
72
+ )
73
+
74
+ _template = ReactTemplate(
75
+ sentence=sentence,
76
+ instruction=instruction,
77
+ confidence_score=confidence_score,
78
+ )
79
+
80
+ await func_call.rcall(
81
+ branch.chat,
82
+ prompt_template=_template,
83
+ retries=retries,
84
+ delay=delay,
85
+ backoff_factor=backoff_factor,
86
+ default=default_value,
87
+ timeout=timeout,
88
+ **kwargs,
89
+ )
90
+
91
+ if _template.action_needed:
92
+ actions = _template.actions
93
+ tasks = [branch.tool_manager.invoke(i.values()) for i in actions]
94
+ results = await AsyncUtil.execute_tasks(*tasks)
95
+
96
+ a = []
97
+ for idx, item in enumerate(actions):
98
+ res = {
99
+ "function": item["function"],
100
+ "arguments": item["arguments"],
101
+ "output": results[idx],
102
+ }
103
+ branch.add_message(response=res)
104
+ a.append(res)
105
+
106
+ _template.__setattr__("action_response", a)
107
+
108
+ return (_template, branch) if return_branch else _template
109
+
110
+
111
+ async def react(
112
+ sentence,
113
+ *,
114
+ instruction=None,
115
+ num_instances=1,
116
+ branch=None,
117
+ confidence_score=False,
118
+ retries=2,
119
+ delay=0.5,
120
+ backoff_factor=2,
121
+ default_value=None,
122
+ timeout=None,
123
+ branch_name=None,
124
+ system=None,
125
+ messages=None,
126
+ service=None,
127
+ sender=None,
128
+ llmconfig=None,
129
+ tools=None,
130
+ datalogger=None,
131
+ persist_path=None,
132
+ tool_manager=None,
133
+ return_branch=False,
134
+ **kwargs,
135
+ ):
136
+
137
+ async def _inner(i=0):
138
+ return await _react(
139
+ sentence=sentence,
140
+ instruction=instruction,
141
+ num_instances=num_instances,
142
+ branch=branch,
143
+ confidence_score=confidence_score,
144
+ retries=retries,
145
+ delay=delay,
146
+ backoff_factor=backoff_factor,
147
+ default_value=default_value,
148
+ timeout=timeout,
149
+ branch_name=branch_name,
150
+ system=system,
151
+ messages=messages,
152
+ service=service,
153
+ sender=sender,
154
+ llmconfig=llmconfig,
155
+ tools=tools,
156
+ datalogger=datalogger,
157
+ persist_path=persist_path,
158
+ tool_manager=tool_manager,
159
+ return_branch=return_branch,
160
+ **kwargs,
161
+ )
162
+
163
+ if num_instances == 1:
164
+ return await _inner()
165
+
166
+ elif num_instances > 1:
167
+ return await func_call.alcall(range(num_instances), _inner)
@@ -12,7 +12,7 @@ ScoreTemplate class and a language model.
12
12
  from pydantic import Field
13
13
  import numpy as np
14
14
  from lionagi.libs import func_call, convert
15
- from ..prompt.prompt_template import ScoredTemplate
15
+ from ..prompt.scored_template import ScoredTemplate
16
16
  from ..branch import Branch
17
17
 
18
18
 
@@ -183,6 +183,7 @@ async def _score(
183
183
 
184
184
  async def score(
185
185
  sentence,
186
+ *,
186
187
  num_instances=1,
187
188
  instruction=None,
188
189
  score_range=(1, 10),
@@ -13,7 +13,7 @@ from enum import Enum
13
13
  from pydantic import Field
14
14
 
15
15
  from lionagi.libs import func_call, StringMatch
16
- from ..prompt.prompt_template import ScoredTemplate
16
+ from ..prompt.scored_template import ScoredTemplate
17
17
  from ..branch import Branch
18
18
 
19
19
 
@@ -39,6 +39,9 @@ class SelectTemplate(ScoredTemplate):
39
39
  answer: Enum | str = Field(
40
40
  default_factory=str, description="selection from given choices"
41
41
  )
42
+ choices: list = Field(
43
+ default_factory=list, description="the given choices"
44
+ )
42
45
 
43
46
  signature: str = "sentence -> answer"
44
47
 
@@ -173,7 +173,7 @@ class Instruction(BaseMessage):
173
173
 
174
174
  if output_fields:
175
175
  format_ = f"""
176
- Follow the following response format.
176
+ MUST EXACTLY Follow the following response format. NO ADDITIONAL COMMENTS ALLOWED!
177
177
  ```json
178
178
  {output_fields}
179
179
  ```
@@ -0,0 +1,26 @@
1
+ from typing import Any
2
+ from lionagi.integrations.bridge.pydantic_.pydantic_bridge import Field
3
+
4
+ from .scored_template import ScoredTemplate
5
+
6
+
7
+ class ActionRequest: ...
8
+
9
+
10
+ class ActionedTemplate(ScoredTemplate):
11
+
12
+ action_needed: bool | None = Field(
13
+ False, description="true if actions are needed else false"
14
+ )
15
+
16
+ actions: list[dict | ActionRequest | Any] | None = Field(
17
+ default_factory=list,
18
+ description="""provide The list of action(s) to take, each action in {"function": function_name, "arguments": {param1:..., param2:..., ...}}. Leave blank if no further actions are needed, you must use provided parameters for each action, DO NOT MAKE UP KWARG NAME!!!""",
19
+ )
20
+
21
+ answer: str | dict | Any | None = Field(
22
+ default_factory=str,
23
+ description="output answer to the questions asked if further actions are not needed, leave blank if an accurate answer cannot be provided from context during this step",
24
+ )
25
+
26
+ signature: str = "sentence -> reason, action_needed, actions, answer"
@@ -6,7 +6,45 @@ including numeric, boolean, string, and enum. It also provides a dictionary `val
6
6
  maps data types to their corresponding validation functions.
7
7
  """
8
8
 
9
- from lionagi.libs import convert, StringMatch
9
+ from lionagi.libs import convert, StringMatch, ParseUtil
10
+
11
+
12
+ def _has_action_keys(dict_):
13
+ return list(dict_.keys()) >= ["function", "arguments"]
14
+
15
+
16
+ def check_action_field(x, fix_=True, **kwargs):
17
+ if (
18
+ isinstance(x, list)
19
+ and convert.is_same_dtype(x, dict)
20
+ and all(_has_action_keys(y) for y in x)
21
+ ):
22
+ return x
23
+ try:
24
+ x = _fix_action_field(x, fix_)
25
+ return x
26
+ except Exception as e:
27
+ raise ValueError("Invalid action field type.") from e
28
+
29
+
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
10
48
 
11
49
 
12
50
  def check_number_field(x, fix_=True, **kwargs):
@@ -236,4 +274,5 @@ validation_funcs = {
236
274
  "bool": check_bool_field,
237
275
  "str": check_str_field,
238
276
  "enum": check_enum_field,
277
+ "action": check_action_field,
239
278
  }
@@ -207,6 +207,10 @@ class PromptTemplate(BaseComponent):
207
207
  setattr(self, k, v_)
208
208
  return True
209
209
 
210
+ if "lionagi.core.prompt.action_template.actionrequest" in str_:
211
+ self.__setattr__(k, validation_funcs["action"](v))
212
+ return True
213
+
210
214
  elif "bool" in str_:
211
215
  self.__setattr__(k, validation_funcs["bool"](v, fix_=fix_, **kwargs))
212
216
  return True
@@ -227,48 +231,50 @@ class PromptTemplate(BaseComponent):
227
231
  if k not in kwargs:
228
232
  kwargs = {k: {}}
229
233
 
230
- try:
231
- if (
232
- self.model_fields[k].json_schema_extra["choices"] is not None
233
- and "choices" in self.model_fields[k].json_schema_extra
234
+ if self._field_has_choices(k):
235
+ self.choices[k] = self.model_fields[k].json_schema_extra["choices"]
236
+ if self._validate_field(
237
+ k, v, choices=self.choices[k], fix_=fix_, **kwargs[k]
234
238
  ):
235
- self.choices[k] = self.model_fields[k].json_schema_extra["choices"]
236
- if self._validate_field(
237
- k, v, choices=self.choices[k], fix_=fix_, **kwargs[k]
238
- ):
239
- continue
240
- else:
241
- raise ValueError(f"{k} has no choices")
242
-
243
- except Exception as e:
244
- if self._validate_field(k, v, fix_=fix_, **kwargs[k]):
245
239
  continue
246
240
  else:
247
- raise ValueError(f"failed to validate field {k}") from e
241
+ raise ValueError(f"{k} has no choices")
242
+
243
+ elif self._validate_field(k, v, fix_=fix_, **kwargs[k]):
244
+ continue
245
+ else:
246
+ raise ValueError(f"failed to validate field {k}")
247
+
248
+ def _field_has_choices(self, k):
249
+ try:
250
+ a = (
251
+ self.model_fields[k].json_schema_extra["choices"] is not None
252
+ and "choices" in self.model_fields[k].json_schema_extra
253
+ )
254
+ return a if isinstance(a, bool) else False
255
+ except Exception:
256
+ return False
248
257
 
249
258
  def _process_response(self, out_, fix_=True):
250
259
  kwargs = self.out_validation_kwargs.copy()
251
260
  for k, v in out_.items():
252
261
  if k not in kwargs:
253
262
  kwargs = {k: {}}
254
- try:
255
- if (
256
- self.model_fields[k].json_schema_extra["choices"] is not None
257
- and "choices" in self.model_fields[k].json_schema_extra
263
+
264
+ if self._field_has_choices(k):
265
+ self.choices[k] = self.model_fields[k].json_schema_extra["choices"]
266
+ if self._validate_field(
267
+ k, v, choices=self.choices[k], fix_=fix_, **kwargs[k]
258
268
  ):
259
- self.choices[k] = self.model_fields[k].json_schema_extra["choices"]
260
- if self._validate_field(
261
- k, v, choices=self.choices[k], fix_=fix_, **kwargs[k]
262
- ):
263
- continue
264
- else:
265
- raise ValueError(f"{k} has no choices")
266
-
267
- except Exception as e:
268
- if self._validate_field(k, v, fix_=fix_, **kwargs[k]):
269
269
  continue
270
270
  else:
271
- raise ValueError(f"failed to validate field {k}") from e
271
+ raise ValueError(f"{k} has no choices")
272
+
273
+ elif self._validate_field(k, v, fix_=fix_, **kwargs[k]):
274
+ continue
275
+
276
+ else:
277
+ raise ValueError(f"failed to validate field {k} with value {v}")
272
278
 
273
279
  @property
274
280
  def in_(self):
@@ -288,16 +294,6 @@ class PromptTemplate(BaseComponent):
288
294
  return self
289
295
 
290
296
 
291
- class ScoredTemplate(PromptTemplate):
292
- confidence_score: float | None = Field(
293
- -1,
294
- description="a numeric score between 0 to 1 formatted in num:0.2f",
295
- )
296
- reason: str | None = Field(
297
- default_factory=str, description="brief reason for the given output"
298
- )
299
-
300
-
301
297
  # class Weather(PromptTemplate):
302
298
  # sunny: bool = Field(True, description="true if the weather is sunny outside else false")
303
299
  # rainy: bool = Field(False, description="true if it is raining outside else false")
@@ -0,0 +1,13 @@
1
+ from lionagi.integrations.bridge.pydantic_.pydantic_bridge import Field
2
+
3
+ from .prompt_template import PromptTemplate
4
+
5
+
6
+ class ScoredTemplate(PromptTemplate):
7
+ confidence_score: float | None = Field(
8
+ -1,
9
+ description="a numeric score between 0 to 1 formatted in num:0.2f",
10
+ )
11
+ reason: str | None = Field(
12
+ default_factory=str, description="brief reason for the given output"
13
+ )
@@ -504,7 +504,9 @@ class Structure(BaseRelatableNode):
504
504
  Args:
505
505
  node (BaseNode): The node to add.
506
506
  """
507
- func_call.lcall(node, self.graph.add_node)
507
+ nodes = [node] if isinstance(node, BaseNode) else node
508
+ for i in nodes:
509
+ self.graph.add_node(i)
508
510
 
509
511
  def add_relationship(
510
512
  self,
@@ -0,0 +1 @@
1
+ # TODO: tool manual, instruction on how to use the tool for LLM
@@ -38,7 +38,7 @@ class ToolManager:
38
38
  def has_tools(self):
39
39
  return self.registry != {}
40
40
 
41
- def _register_tool(self, tool: Tool) -> None:
41
+ def _register_tool(self, tool: Tool | Callable) -> None:
42
42
  """
43
43
  Registers a tool in the registry. Raises a TypeError if the object is not an instance of Tool.
44
44
 
@@ -48,6 +48,8 @@ class ToolManager:
48
48
  Raises:
49
49
  TypeError: If the provided object is not an instance of Tool.
50
50
  """
51
+ if isinstance(tool, Callable):
52
+ tool = func_to_tool(tool)[0]
51
53
  if not isinstance(tool, Tool):
52
54
  raise TypeError("Please register a Tool object.")
53
55
  name = tool.schema_["function"]["name"]
@@ -0,0 +1 @@
1
+ from pydantic import BaseModel, Field, ValidationError, AliasChoices, field_serializer
@@ -11,7 +11,7 @@ allowed_kwargs = [
11
11
  "seed",
12
12
  "stop",
13
13
  "stream",
14
- "temperature",
14
+ # "temperature",
15
15
  "top_p",
16
16
  "tools",
17
17
  "tool_choice",
lionagi/libs/sys_util.py CHANGED
@@ -1,3 +1,15 @@
1
+ """
2
+ MIT License
3
+
4
+ Copyright (c) 2023 HaiyangLi quantocean.li@gmail.com
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
7
+
8
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
9
+
10
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
11
+ """
12
+
1
13
  import copy
2
14
  import importlib
3
15
  import logging
lionagi/version.py CHANGED
@@ -1 +1 @@
1
- __version__ = "0.0.312"
1
+ __version__ = "0.0.314"
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 HaiyangLi quantocean.li@gmail.com
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.