lionagi 0.0.106__py3-none-any.whl → 0.0.107__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.
- lionagi/api/oai_service.py +25 -13
- lionagi/session/conversation.py +18 -9
- lionagi/session/message.py +38 -14
- lionagi/session/session.py +122 -55
- lionagi/utils/__init__.py +4 -7
- lionagi/utils/api_util.py +91 -45
- lionagi/utils/doc_util.py +69 -26
- lionagi/utils/log_util.py +15 -4
- lionagi/utils/sys_util.py +74 -11
- lionagi/utils/tool_util.py +39 -24
- lionagi/version.py +1 -1
- {lionagi-0.0.106.dist-info → lionagi-0.0.107.dist-info}/METADATA +7 -12
- lionagi-0.0.107.dist-info/RECORD +20 -0
- lionagi/tools/__init__.py +0 -0
- lionagi-0.0.106.dist-info/RECORD +0 -21
- {lionagi-0.0.106.dist-info → lionagi-0.0.107.dist-info}/LICENSE +0 -0
- {lionagi-0.0.106.dist-info → lionagi-0.0.107.dist-info}/WHEEL +0 -0
- {lionagi-0.0.106.dist-info → lionagi-0.0.107.dist-info}/top_level.txt +0 -0
lionagi/api/oai_service.py
CHANGED
@@ -19,20 +19,25 @@ class OpenAIRateLimiter(RateLimiter):
|
|
19
19
|
and replenishing these limits at regular intervals.
|
20
20
|
|
21
21
|
Attributes:
|
22
|
-
max_requests_per_minute (int):
|
23
|
-
|
22
|
+
max_requests_per_minute (int):
|
23
|
+
Maximum number of requests allowed per minute.
|
24
|
+
max_tokens_per_minute (int):
|
25
|
+
Maximum number of tokens allowed per minute.
|
24
26
|
|
25
27
|
Methods:
|
26
|
-
rate_limit_replenisher:
|
27
|
-
|
28
|
+
rate_limit_replenisher:
|
29
|
+
Coroutine to replenish rate limits over time.
|
30
|
+
calculate_num_token:
|
31
|
+
Calculates the required tokens for a request.
|
28
32
|
"""
|
29
33
|
|
30
34
|
def __init__(self, max_requests_per_minute: int, max_tokens_per_minute: int) -> None:
|
31
35
|
"""
|
32
36
|
Initializes the rate limiter with specific limits for OpenAI API.
|
33
37
|
|
34
|
-
|
38
|
+
Parameters:
|
35
39
|
max_requests_per_minute (int): The maximum number of requests allowed per minute.
|
40
|
+
|
36
41
|
max_tokens_per_minute (int): The maximum number of tokens that can accumulate per minute.
|
37
42
|
"""
|
38
43
|
super().__init__(max_requests_per_minute, max_tokens_per_minute)
|
@@ -66,8 +71,9 @@ class OpenAIRateLimiter(RateLimiter):
|
|
66
71
|
This method should be implemented in a subclass to provide the specific calculation logic
|
67
72
|
for the OpenAI API.
|
68
73
|
|
69
|
-
|
74
|
+
Parameters:
|
70
75
|
payload (Dict[str, Any]): The payload of the request.
|
76
|
+
|
71
77
|
api_endpoint (str): The specific API endpoint for the request.
|
72
78
|
|
73
79
|
Returns:
|
@@ -160,12 +166,17 @@ class OpenAIService(BaseAPIService):
|
|
160
166
|
"""
|
161
167
|
Initializes the OpenAI service with configuration for API interaction.
|
162
168
|
|
163
|
-
|
169
|
+
Parameters:
|
164
170
|
api_key (str): The API key for authenticating with OpenAI.
|
171
|
+
|
165
172
|
token_encoding_name (str): The name of the text encoding used by OpenAI.
|
173
|
+
|
166
174
|
max_attempts (int): The maximum number of attempts for calling an API endpoint.
|
175
|
+
|
167
176
|
status_tracker (Optional[StatusTracker]): Tracker for API call outcomes.
|
168
|
-
|
177
|
+
|
178
|
+
ratelimiter (Optional[OpenAIRateLimiter]): Rate limiter for OpenAI's limits.
|
179
|
+
|
169
180
|
queue (Optional[AsyncQueue]): Queue for managing asynchronous API calls.
|
170
181
|
|
171
182
|
Example:
|
@@ -183,15 +194,16 @@ class OpenAIService(BaseAPIService):
|
|
183
194
|
super().__init__(api_key, token_encoding_name, max_attempts,
|
184
195
|
max_requests_per_minute, max_tokens_per_minute,
|
185
196
|
ratelimiter, status_tracker, queue)
|
186
|
-
|
187
197
|
|
188
|
-
async def call_api(self, http_session, endpoint, payload: Dict[str, any] =None) -> Optional[Dict[str, any]]:
|
198
|
+
async def call_api(self, http_session, endpoint, payload: Dict[str, any] = None) -> Optional[Dict[str, any]]:
|
189
199
|
"""
|
190
200
|
Call an OpenAI API endpoint with a specific payload and handle the response.
|
191
201
|
|
192
|
-
|
193
|
-
|
194
|
-
|
202
|
+
Parameters:
|
203
|
+
http_session: The session object for making HTTP requests.
|
204
|
+
|
205
|
+
endpoint (str): The full URL of the OpenAI API endpoint to be called.
|
206
|
+
|
195
207
|
payload (Dict[str, any]): The payload to send with the API request.
|
196
208
|
|
197
209
|
Returns:
|
lionagi/session/conversation.py
CHANGED
@@ -1,5 +1,6 @@
|
|
1
1
|
from .message import Message
|
2
2
|
|
3
|
+
|
3
4
|
class Conversation:
|
4
5
|
"""
|
5
6
|
A class representing a conversation between users and the assistant.
|
@@ -8,21 +9,22 @@ class Conversation:
|
|
8
9
|
user instructions, and assistant responses.
|
9
10
|
|
10
11
|
Attributes:
|
11
|
-
response_counts (int):
|
12
|
-
|
13
|
-
|
14
|
-
|
12
|
+
response_counts (int):
|
13
|
+
The count of assistant responses in the conversation.
|
14
|
+
messages (list):
|
15
|
+
A list to store messages in the conversation.
|
16
|
+
msg (Message):
|
17
|
+
An instance of the Message class for creating messages.
|
18
|
+
responses (list):
|
19
|
+
A list to store assistant responses in the conversation.
|
15
20
|
|
16
21
|
Methods:
|
17
22
|
initiate_conversation(system, instruction, context=None, name=None):
|
18
23
|
Initiate a conversation with a system setting and user instruction.
|
19
|
-
|
20
24
|
add_messages(system, instruction, context=None, response=None, tool=None, name=None):
|
21
25
|
Add messages to the conversation, including system setting, user instruction, and assistant response.
|
22
|
-
|
23
26
|
change_system(system):
|
24
27
|
Change the system setting in the conversation.
|
25
|
-
|
26
28
|
keep_last_n_exchanges(n: int):
|
27
29
|
Keep the last n exchanges in the conversation.
|
28
30
|
"""
|
@@ -46,8 +48,11 @@ class Conversation:
|
|
46
48
|
|
47
49
|
Parameters:
|
48
50
|
system (str): The system setting for the conversation.
|
51
|
+
|
49
52
|
instruction (str): The user instruction to initiate the conversation.
|
53
|
+
|
50
54
|
context (dict): Additional context for the conversation. Default is None.
|
55
|
+
|
51
56
|
name (str): The name associated with the user. Default is None.
|
52
57
|
"""
|
53
58
|
self.messages, self.responses = [], []
|
@@ -61,10 +66,13 @@ class Conversation:
|
|
61
66
|
|
62
67
|
Parameters:
|
63
68
|
system (str): The system setting for the message. Default is None.
|
69
|
+
|
64
70
|
instruction (str): The instruction content for the message. Default is None.
|
71
|
+
|
65
72
|
context (dict): Additional context for the message. Default is None.
|
73
|
+
|
66
74
|
response (dict): The response content for the message. Default is None.
|
67
|
-
|
75
|
+
|
68
76
|
name (str): The name associated with the message. Default is None.
|
69
77
|
"""
|
70
78
|
msg = self.msg(system=system, instruction=instruction, context=context,
|
@@ -93,4 +101,5 @@ class Conversation:
|
|
93
101
|
]
|
94
102
|
if len(response_indices) >= n:
|
95
103
|
first_index_to_keep = response_indices[-n] + 1
|
96
|
-
self.messages =
|
104
|
+
self.messages = self.messages[0] + self.messages[first_index_to_keep:]
|
105
|
+
|
lionagi/session/message.py
CHANGED
@@ -11,11 +11,16 @@ class Message:
|
|
11
11
|
This class encapsulates messages from users, the assistant, systems, and external tools.
|
12
12
|
|
13
13
|
Attributes:
|
14
|
-
role (str):
|
15
|
-
|
16
|
-
|
17
|
-
|
18
|
-
|
14
|
+
role (str):
|
15
|
+
The role of the message, indicating if it's from the user, assistant, system, or tool.
|
16
|
+
content:
|
17
|
+
The content of the message, which can be an instruction, response, system setting, or tool information.
|
18
|
+
name (str):
|
19
|
+
The name associated with the message, specifying the source (user, assistant, system, or tool).
|
20
|
+
metadata (dict):
|
21
|
+
Additional metadata including id, timestamp, and name.
|
22
|
+
_logger (DataLogger):
|
23
|
+
An instance of the DataLogger class for logging message details.
|
19
24
|
|
20
25
|
Methods:
|
21
26
|
create_message(system, instruction, context, response, tool, name):
|
@@ -47,10 +52,13 @@ class Message:
|
|
47
52
|
|
48
53
|
Parameters:
|
49
54
|
system (str): The system setting for the message. Default is None.
|
55
|
+
|
50
56
|
instruction (str): The instruction content for the message. Default is None.
|
57
|
+
|
51
58
|
context (dict): Additional context for the message. Default is None.
|
59
|
+
|
52
60
|
response (dict): The response content for the message. Default is None.
|
53
|
-
|
61
|
+
|
54
62
|
name (str): The name associated with the message. Default is None.
|
55
63
|
"""
|
56
64
|
if sum(l_call([system, instruction, response], bool)) > 1:
|
@@ -63,10 +71,17 @@ class Message:
|
|
63
71
|
response = response["message"]
|
64
72
|
if str(response['content']) == "None":
|
65
73
|
try:
|
66
|
-
|
67
|
-
|
68
|
-
|
69
|
-
|
74
|
+
tool_count = 0
|
75
|
+
func_list = []
|
76
|
+
while tool_count < len(response['tool_calls']):
|
77
|
+
if response['tool_calls'][tool_count]['type'] == 'function':
|
78
|
+
func_content = {"function": ("func_" + response['tool_calls'][tool_count]['function']['name']),
|
79
|
+
"arguments": response['tool_calls'][tool_count]['function']['arguments']}
|
80
|
+
func_list.append(func_content)
|
81
|
+
tool_count += 1
|
82
|
+
|
83
|
+
self.name = name or "func_request"
|
84
|
+
self.content = {'function_list': func_list}
|
70
85
|
except:
|
71
86
|
raise ValueError("Response message must be one of regular response or function calling")
|
72
87
|
else:
|
@@ -74,7 +89,7 @@ class Message:
|
|
74
89
|
self.name = name or "assistant"
|
75
90
|
except:
|
76
91
|
self.name = name or "func_call"
|
77
|
-
self.content =
|
92
|
+
self.content = response
|
78
93
|
|
79
94
|
elif instruction:
|
80
95
|
self.role = "user"
|
@@ -92,7 +107,7 @@ class Message:
|
|
92
107
|
Convert the message to a JSON format.
|
93
108
|
|
94
109
|
Returns:
|
95
|
-
|
110
|
+
dict: The message in JSON format.
|
96
111
|
"""
|
97
112
|
out = {
|
98
113
|
"role": self.role,
|
@@ -114,11 +129,14 @@ class Message:
|
|
114
129
|
|
115
130
|
Parameters:
|
116
131
|
system (str): The system setting for the message. Default is None.
|
132
|
+
|
117
133
|
instruction (str): The instruction content for the message. Default is None.
|
134
|
+
|
118
135
|
context (dict): Additional context for the message. Default is None.
|
136
|
+
|
119
137
|
response (dict): The response content for the message. Default is None.
|
138
|
+
|
120
139
|
name (str): The name associated with the message. Default is None.
|
121
|
-
tool (dict): The tool information for the message. Default is None.
|
122
140
|
|
123
141
|
Returns:
|
124
142
|
dict: The message in JSON format.
|
@@ -133,10 +151,16 @@ class Message:
|
|
133
151
|
|
134
152
|
Parameters:
|
135
153
|
dir (str): The directory path for saving the CSV file. Default is None.
|
154
|
+
|
136
155
|
filename (str): The filename for the CSV file. Default is None.
|
156
|
+
|
137
157
|
verbose (bool): Whether to include verbose information in the CSV. Default is True.
|
158
|
+
|
138
159
|
timestamp (bool): Whether to include timestamps in the CSV. Default is True.
|
160
|
+
|
139
161
|
dir_exist_ok (bool): Whether to allow the directory to exist. Default is True.
|
162
|
+
|
140
163
|
file_exist_ok (bool): Whether to allow the file to exist. Default is False.
|
141
164
|
"""
|
142
|
-
self._logger.to_csv(dir, filename, verbose, timestamp, dir_exist_ok, file_exist_ok)
|
165
|
+
self._logger.to_csv(dir, filename, verbose, timestamp, dir_exist_ok, file_exist_ok)
|
166
|
+
|
lionagi/session/session.py
CHANGED
@@ -3,19 +3,19 @@ import asyncio
|
|
3
3
|
import json
|
4
4
|
from typing import Any
|
5
5
|
|
6
|
+
import lionagi
|
6
7
|
from .conversation import Conversation
|
7
|
-
from ..utils.sys_util import to_list
|
8
|
+
from ..utils.sys_util import to_list, l_call, al_call
|
8
9
|
from ..utils.log_util import DataLogger
|
9
10
|
from ..utils.api_util import StatusTracker
|
10
11
|
from ..utils.tool_util import ToolManager
|
11
12
|
from ..api.oai_service import OpenAIService
|
12
|
-
|
13
13
|
from ..api.oai_config import oai_llmconfig
|
14
14
|
|
15
|
-
|
16
15
|
status_tracker = StatusTracker()
|
17
16
|
OAIService = OpenAIService()
|
18
17
|
|
18
|
+
|
19
19
|
class Session():
|
20
20
|
"""
|
21
21
|
A class representing a conversation session with a conversational AI system.
|
@@ -23,12 +23,18 @@ class Session():
|
|
23
23
|
This class manages the flow of conversation, system settings, and interactions with external tools.
|
24
24
|
|
25
25
|
Attributes:
|
26
|
-
conversation (Conversation):
|
27
|
-
|
28
|
-
|
29
|
-
|
30
|
-
|
31
|
-
|
26
|
+
conversation (Conversation):
|
27
|
+
An instance of the Conversation class to manage messages.
|
28
|
+
system (str):
|
29
|
+
The current system setting for the conversation.
|
30
|
+
llmconfig (dict):
|
31
|
+
Configuration settings for the language model.
|
32
|
+
_logger (DataLogger):
|
33
|
+
An instance of the DataLogger class for logging conversation details.
|
34
|
+
api_service:
|
35
|
+
An instance of the API service for making calls to the conversational AI model.
|
36
|
+
_toolmanager (ToolManager):
|
37
|
+
An instance of the ToolManager class for managing external tools.
|
32
38
|
|
33
39
|
Methods:
|
34
40
|
set_dir(dir):
|
@@ -55,6 +61,9 @@ class Session():
|
|
55
61
|
followup(instruction, system=None, context=None, out=True, name=None, invoke=True, **kwargs) -> Any:
|
56
62
|
Continue the conversation with the provided instruction.
|
57
63
|
|
64
|
+
auto_followup(self, instruct, num=3, tool_parser=None, **kwags):
|
65
|
+
Automates the follow-up process for a specified number of times or until the session concludes.
|
66
|
+
|
58
67
|
create_payload_chatcompletion(**kwargs) -> dict:
|
59
68
|
Create a payload for chat completion based on the conversation state and configuration.
|
60
69
|
|
@@ -74,8 +83,11 @@ class Session():
|
|
74
83
|
|
75
84
|
Parameters:
|
76
85
|
system (str): The initial system setting for the conversation.
|
86
|
+
|
77
87
|
dir (Optional[str]): The directory for logging. Default is None.
|
88
|
+
|
78
89
|
llmconfig (Optional[dict]): Configuration settings for the language model. Default is oai_llmconfig.
|
90
|
+
|
79
91
|
api_service: An instance of the API service for making calls to the conversational AI model.
|
80
92
|
"""
|
81
93
|
self.conversation = Conversation()
|
@@ -83,7 +95,7 @@ class Session():
|
|
83
95
|
self.llmconfig = llmconfig
|
84
96
|
self._logger = DataLogger(dir=dir)
|
85
97
|
self.api_service = api_service
|
86
|
-
self.
|
98
|
+
self._toolmanager = ToolManager()
|
87
99
|
|
88
100
|
def set_dir(self, dir):
|
89
101
|
"""
|
@@ -126,51 +138,89 @@ class Session():
|
|
126
138
|
Process the output, invoke tools if needed, and optionally return the output.
|
127
139
|
|
128
140
|
Parameters:
|
129
|
-
output: The output to process.
|
130
141
|
invoke (bool): Whether to invoke tools based on the output. Default is True.
|
142
|
+
|
131
143
|
out (bool): Whether to return the output. Default is True.
|
132
144
|
|
133
145
|
Returns:
|
134
146
|
Any: The processed output.
|
135
147
|
"""
|
136
148
|
if invoke:
|
137
|
-
try:
|
138
|
-
|
139
|
-
|
140
|
-
|
141
|
-
|
149
|
+
try:
|
150
|
+
tool_uses = json.loads(self.conversation.responses[-1]['content'])
|
151
|
+
if 'function_list' in tool_uses.keys():
|
152
|
+
func_calls = l_call(tool_uses['function_list'], self._toolmanager._get_function_call)
|
153
|
+
|
154
|
+
else:
|
155
|
+
func_calls = l_call(tool_uses['tool_uses'], self._toolmanager._get_function_call)
|
156
|
+
|
157
|
+
outs = await al_call(func_calls, self._toolmanager.ainvoke)
|
158
|
+
if tool_parser:
|
159
|
+
outs = l_call(outs, tool_parser)
|
160
|
+
for out, f in zip(outs, func_calls):
|
161
|
+
response = {"function": f[0], "arguments": f[1], "output": out}
|
162
|
+
self.conversation.add_messages(response=response)
|
163
|
+
|
142
164
|
except:
|
143
165
|
pass
|
166
|
+
|
144
167
|
if out:
|
145
168
|
return self.conversation.responses[-1]['content']
|
146
|
-
|
169
|
+
|
170
|
+
def _is_invoked(self):
|
171
|
+
"""
|
172
|
+
Checks if the current message indicates the invocation of a function call.
|
173
|
+
|
174
|
+
Returns:
|
175
|
+
bool: True if a function call is detected in the content of the last message, False otherwise.
|
176
|
+
"""
|
177
|
+
msg = self.conversation.messages[-1]
|
178
|
+
try:
|
179
|
+
if json.loads(msg['content']).keys() >= {'function', 'arguments', 'output'}:
|
180
|
+
return True
|
181
|
+
except:
|
182
|
+
return False
|
183
|
+
|
147
184
|
def register_tools(self, tools, funcs, update=False, new=False, prefix=None, postfix=None):
|
148
185
|
"""
|
149
186
|
Register tools and their corresponding functions.
|
150
187
|
|
151
188
|
Parameters:
|
152
189
|
tools (list): The list of tool information dictionaries.
|
190
|
+
|
153
191
|
funcs (list): The list of corresponding functions.
|
192
|
+
|
154
193
|
update (bool): Whether to update existing functions.
|
194
|
+
|
155
195
|
new (bool): Whether to create new registries for existing functions.
|
196
|
+
|
156
197
|
prefix (Optional[str]): A prefix to add to the function names.
|
198
|
+
|
157
199
|
postfix (Optional[str]): A postfix to add to the function names.
|
158
200
|
"""
|
159
201
|
funcs = to_list(funcs)
|
160
|
-
self.
|
202
|
+
self._toolmanager.register_tools(tools, funcs, update, new, prefix, postfix)
|
161
203
|
|
162
204
|
async def initiate(self, instruction, system=None, context=None, name=None, invoke=True, out=True, tool_parser=None, **kwargs) -> Any:
|
163
205
|
"""
|
164
206
|
Start a new conversation session with the provided instruction.
|
165
207
|
|
166
208
|
Parameters:
|
167
|
-
instruction (str): The instruction to initiate the conversation.
|
209
|
+
instruction (Union[str, dict]): The instruction to initiate the conversation.
|
210
|
+
|
168
211
|
system (Optional[str]): The system setting for the conversation. Default is None.
|
212
|
+
|
169
213
|
context (Optional[dict]): Additional context for the instruction. Default is None.
|
214
|
+
|
170
215
|
out (bool): Whether to return the output. Default is True.
|
216
|
+
|
171
217
|
name (Optional[str]): The name associated with the instruction. Default is None.
|
218
|
+
|
172
219
|
invoke (bool): Whether to invoke tools based on the output. Default is True.
|
173
|
-
|
220
|
+
|
221
|
+
tool_parser (Optional[callable]): A custom tool parser function. Default is None.
|
222
|
+
|
223
|
+
**kwargs: Additional keyword arguments for configuration.
|
174
224
|
|
175
225
|
Returns:
|
176
226
|
Any: The processed output.
|
@@ -178,7 +228,7 @@ class Session():
|
|
178
228
|
config = {**self.llmconfig, **kwargs}
|
179
229
|
system = system or self.system
|
180
230
|
self.conversation.initiate_conversation(system=system, instruction=instruction, context=context, name=name)
|
181
|
-
await self.
|
231
|
+
await self._call_chatcompletion(**config)
|
182
232
|
|
183
233
|
return await self._output(invoke, out, tool_parser)
|
184
234
|
|
@@ -187,13 +237,21 @@ class Session():
|
|
187
237
|
Continue the conversation with the provided instruction.
|
188
238
|
|
189
239
|
Parameters:
|
190
|
-
instruction (str): The instruction to continue the conversation.
|
240
|
+
instruction (Union[str, dict]): The instruction to continue the conversation.
|
241
|
+
|
191
242
|
system (Optional[str]): The system setting for the conversation. Default is None.
|
243
|
+
|
192
244
|
context (Optional[dict]): Additional context for the instruction. Default is None.
|
245
|
+
|
193
246
|
out (bool): Whether to return the output. Default is True.
|
247
|
+
|
194
248
|
name (Optional[str]): The name associated with the instruction. Default is None.
|
249
|
+
|
195
250
|
invoke (bool): Whether to invoke tools based on the output. Default is True.
|
196
|
-
|
251
|
+
|
252
|
+
tool_parser (Optional[callable]): A custom tool parser function. Default is None.
|
253
|
+
|
254
|
+
**kwargs: Additional keyword arguments for configuration.
|
197
255
|
|
198
256
|
Returns:
|
199
257
|
Any: The processed output.
|
@@ -202,17 +260,38 @@ class Session():
|
|
202
260
|
self.conversation.change_system(system)
|
203
261
|
self.conversation.add_messages(instruction=instruction, context=context, name=name)
|
204
262
|
config = {**self.llmconfig, **kwargs}
|
205
|
-
await self.
|
263
|
+
await self._call_chatcompletion(**config)
|
206
264
|
|
207
|
-
|
208
265
|
return await self._output(invoke, out, tool_parser)
|
209
|
-
|
210
|
-
def
|
266
|
+
|
267
|
+
async def auto_followup(self, instruct, num=3, tool_parser=None, **kwargs):
|
268
|
+
"""
|
269
|
+
Automates the follow-up process for a specified number of times or until the session concludes.
|
270
|
+
|
271
|
+
Parameters:
|
272
|
+
instruct (Union[str, dict]): The instruction for the follow-up.
|
273
|
+
|
274
|
+
num (int, optional): The number of times to automatically follow up. Defaults to 3.
|
275
|
+
|
276
|
+
tool_parser (callable, optional): A custom tool parser function. Defaults to None.
|
277
|
+
|
278
|
+
**kwargs: Additional keyword arguments passed to the underlying `followup` method.
|
279
|
+
|
280
|
+
"""
|
281
|
+
cont_ = True
|
282
|
+
while num > 0 and cont_ is True:
|
283
|
+
await self.followup(instruct, tool_parser=tool_parser, tool_choice="auto", **kwargs)
|
284
|
+
num -= 1
|
285
|
+
cont_ = True if self._is_invoked() else False
|
286
|
+
if num == 0:
|
287
|
+
await self.followup(instruct, **kwargs)
|
288
|
+
|
289
|
+
def _create_payload_chatcompletion(self, **kwargs):
|
211
290
|
"""
|
212
291
|
Create a payload for chat completion based on the conversation state and configuration.
|
213
292
|
|
214
293
|
Parameters:
|
215
|
-
kwargs: Additional keyword arguments for configuration.
|
294
|
+
**kwargs: Additional keyword arguments for configuration.
|
216
295
|
|
217
296
|
Returns:
|
218
297
|
dict: The payload for chat completion.
|
@@ -236,22 +315,23 @@ class Session():
|
|
236
315
|
payload.update({key: config[key]})
|
237
316
|
return payload
|
238
317
|
|
239
|
-
async def
|
318
|
+
async def _call_chatcompletion(self, sleep=0.1, **kwargs):
|
240
319
|
"""
|
241
320
|
Make a call to the chat completion API and process the response.
|
242
321
|
|
243
322
|
Parameters:
|
244
323
|
sleep (float): The sleep duration after making the API call. Default is 0.1.
|
245
|
-
|
324
|
+
|
325
|
+
**kwargs: Additional keyword arguments for configuration.
|
246
326
|
"""
|
247
327
|
endpoint = f"chat/completions"
|
248
328
|
try:
|
249
329
|
async with aiohttp.ClientSession() as session:
|
250
|
-
payload = self.
|
330
|
+
payload = self._create_payload_chatcompletion(**kwargs)
|
251
331
|
completion = await self.api_service.call_api(
|
252
332
|
session, endpoint, payload)
|
253
333
|
if "choices" in completion:
|
254
|
-
self._logger({"input":payload, "output": completion})
|
334
|
+
self._logger({"input": payload, "output": completion})
|
255
335
|
self.conversation.add_messages(response=completion['choices'][0])
|
256
336
|
self.conversation.responses.append(self.conversation.messages[-1])
|
257
337
|
self.conversation.response_counts += 1
|
@@ -263,47 +343,34 @@ class Session():
|
|
263
343
|
status_tracker.num_tasks_failed += 1
|
264
344
|
raise e
|
265
345
|
|
266
|
-
def messages_to_csv(self, dir=None, filename="_messages.csv", **
|
346
|
+
def messages_to_csv(self, dir=None, filename="_messages.csv", **kwargs):
|
267
347
|
"""
|
268
348
|
Save conversation messages to a CSV file.
|
269
349
|
|
270
350
|
Parameters:
|
271
351
|
dir (Optional[str]): The directory path for saving the CSV file. Default is None.
|
352
|
+
|
272
353
|
filename (Optional[str]): The filename for the CSV file. Default is "_messages.csv".
|
273
|
-
|
354
|
+
|
355
|
+
**kwargs: Additional keyword arguments for CSV file settings.
|
274
356
|
"""
|
275
357
|
dir = dir or self._logger.dir
|
276
358
|
if dir is None:
|
277
359
|
raise ValueError("No directory specified.")
|
278
|
-
self.conversation.msg.to_csv(dir=dir, filename=filename, **
|
360
|
+
self.conversation.msg.to_csv(dir=dir, filename=filename, **kwargs)
|
279
361
|
|
280
|
-
def log_to_csv(self, dir=None, filename="_llmlog.csv", **
|
362
|
+
def log_to_csv(self, dir=None, filename="_llmlog.csv", **kwargs):
|
281
363
|
"""
|
282
364
|
Save conversation logs to a CSV file.
|
283
365
|
|
284
366
|
Parameters:
|
285
367
|
dir (Optional[str]): The directory path for saving the CSV file. Default is None.
|
368
|
+
|
286
369
|
filename (Optional[str]): The filename for the CSV file. Default is "_llmlog.csv".
|
287
|
-
|
370
|
+
|
371
|
+
**kwargs: Additional keyword arguments for CSV file settings.
|
288
372
|
"""
|
289
373
|
dir = dir or self._logger.dir
|
290
374
|
if dir is None:
|
291
375
|
raise ValueError("No directory specified.")
|
292
|
-
self._logger.to_csv(dir=dir, filename=filename, **
|
293
|
-
|
294
|
-
def is_invoked(self):
|
295
|
-
msg = self.conversation.messages[-1]
|
296
|
-
try:
|
297
|
-
if "function call result" in json.loads(msg['content']).keys():
|
298
|
-
return True
|
299
|
-
except:
|
300
|
-
return False
|
301
|
-
|
302
|
-
async def auto_followup(self, instruct, num=3, tool_parser=None, **kwags):
|
303
|
-
cont_ = True
|
304
|
-
while num > 0 and cont_ is True:
|
305
|
-
await self.followup(instruct,tool_parser=tool_parser, tool_choice="auto", **kwags)
|
306
|
-
num -= 1
|
307
|
-
cont_ = True if self.is_invoked() else False
|
308
|
-
if num == 0:
|
309
|
-
await self.followup(instruct, **kwags)
|
376
|
+
self._logger.to_csv(dir=dir, filename=filename, **kwargs)
|
lionagi/utils/__init__.py
CHANGED
@@ -1,10 +1,7 @@
|
|
1
|
-
from .sys_util import to_flat_dict,
|
2
|
-
from .doc_util import dir_to_path, read_text, dir_to_files,
|
3
|
-
from .log_util import DataLogger
|
4
|
-
from .tool_util import ToolManager
|
1
|
+
from .sys_util import to_flat_dict, to_list, str_to_num, make_copy, to_temp, to_csv, hold_call, ahold_call, l_call, al_call, m_call, am_call, e_call, ae_call, get_timestamp, create_path
|
2
|
+
from .doc_util import dir_to_path, read_text, dir_to_files, file_to_chunks, get_bins
|
5
3
|
|
6
4
|
__all__ = [
|
7
|
-
"to_list", "str_to_num", "make_copy", "to_temp", "to_csv", "hold_call", "ahold_call", "l_call", "al_call", "m_call", "am_call", "e_call", "ae_call", "get_timestamp", "create_path", "to_flat_dict",
|
8
|
-
"dir_to_path", "read_text", "dir_to_files", "
|
9
|
-
"DataLogger", "ToolManager"
|
5
|
+
"to_list", "str_to_num", "make_copy", "to_temp", "to_csv", "hold_call", "ahold_call", "l_call", "al_call", "m_call", "am_call", "e_call", "ae_call", "get_timestamp", "create_path", "to_flat_dict",
|
6
|
+
"dir_to_path", "read_text", "dir_to_files", "file_to_chunks", "get_bins"
|
10
7
|
]
|