autonomous-app 0.3.18__py3-none-any.whl → 0.3.19__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.
autonomous/__init__.py CHANGED
@@ -1,4 +1,4 @@
1
- __version__ = "0.3.18"
1
+ __version__ = "0.3.19"
2
2
 
3
3
  from dotenv import load_dotenv
4
4
 
@@ -16,3 +16,6 @@ class AudioAgent(BaseAgent):
16
16
 
17
17
  def generate(self, prompt, **kwargs):
18
18
  return self.get_client().generate_audio(prompt, **kwargs)
19
+
20
+ def generate_text(self, audio, **kwargs):
21
+ return self.get_client().generate_audio_text(audio, **kwargs)
@@ -2,15 +2,25 @@ from autonomous import log
2
2
  from autonomous.model.autoattr import ReferenceAttr
3
3
  from autonomous.model.automodel import AutoModel
4
4
 
5
+ from .models.gemini import GeminiAIModel
5
6
  from .models.openai import OpenAIModel
6
7
 
7
8
 
9
+ def clear_agents():
10
+ for agent in OpenAIModel.all():
11
+ log(f"Deleting {agent.name}")
12
+ agent.clear_agents()
13
+ agent.clear_files()
14
+ agent.delete()
15
+ return "Success"
16
+
17
+
8
18
  class BaseAgent(AutoModel):
9
19
  meta = {"abstract": True, "allow_inheritance": True, "strict": False}
10
20
 
11
- client = ReferenceAttr(choices=[OpenAIModel])
21
+ client = ReferenceAttr(choices=[GeminiAIModel])
12
22
 
13
- _ai_model = OpenAIModel
23
+ _ai_model = GeminiAIModel
14
24
 
15
25
  def delete(self):
16
26
  if self.client:
@@ -30,9 +40,3 @@ class BaseAgent(AutoModel):
30
40
  self.client.save()
31
41
  self.save()
32
42
  return self.client
33
-
34
- def clear_files(self, file_id=None):
35
- return self.client.clear_files(file_id)
36
-
37
- def attach_file(self, file_contents, filename="dbdata.json"):
38
- return self.client.attach_file(file_contents, filename)
@@ -15,12 +15,6 @@ class JSONAgent(BaseAgent):
15
15
  default="A helpful AI assistant trained to assist with generating JSON formatted data."
16
16
  )
17
17
 
18
- def clear_files(self, file_id=None):
19
- return self.get_client().clear_files(file_id)
20
-
21
- def attach_file(self, file_contents, filename="dbdata.json"):
22
- return self.get_client().attach_file(file_contents, filename)
23
-
24
18
  def generate(self, messages, function, additional_instructions=""):
25
19
  result = self.get_client().generate_json(
26
20
  messages, function, additional_instructions
@@ -0,0 +1,317 @@
1
+ import io
2
+ import json
3
+ import os
4
+ import random
5
+ import time
6
+ from base64 import b64decode
7
+
8
+ import openai
9
+ from openai import NotFoundError as openai_NotFoundError
10
+ from openai import OpenAI
11
+
12
+ from autonomous import log
13
+ from autonomous.model.autoattr import DictAttr, ListAttr, StringAttr
14
+ from autonomous.model.automodel import AutoModel
15
+
16
+
17
+ class AWSAIModel(AutoModel):
18
+ _client = None
19
+ instructions = StringAttr(
20
+ default="You are highly skilled AI trained to assist with various tasks."
21
+ )
22
+ description = StringAttr(
23
+ default="A helpful AI assistant trained to assist with various tasks."
24
+ )
25
+
26
+ @property
27
+ def client(self):
28
+ if not self._client:
29
+ self._client = "TBD" # OpenAI(api_key=os.environ.get("OPENAI_KEY"))
30
+ return self._client
31
+
32
+ # def delete(self):
33
+ # self.clear_files()
34
+ # if self.agent_id:
35
+ # self.client.beta.assistants.delete(self.agent_id)
36
+ # return super().delete()
37
+
38
+
39
+ # def clear_agent(self):
40
+ # if self.agent_id:
41
+ # self.client.beta.assistants.delete(self.agent_id)
42
+ # self.agent_id = ""
43
+ # self.save()
44
+
45
+ # def clear_agents(self):
46
+ # assistants = self.client.beta.assistants.list().data
47
+ # log(assistants)
48
+ # for assistant in assistants:
49
+ # log(f"==== Deleting Agent with ID: {assistant.id} ====")
50
+ # try:
51
+ # self.client.beta.assistants.delete(assistant.id)
52
+ # except openai_NotFoundError:
53
+ # log(f"==== Agent with ID: {assistant.id} not found ====")
54
+ # self.agent_id = ""
55
+ # self.save()
56
+
57
+ # def _get_agent_id(self):
58
+ # try:
59
+ # self.client.beta.assistants.retrieve(self.agent_id)
60
+ # except (ValueError, openai.NotFoundError) as e:
61
+ # log(f"{e} -- no agent found, creating a new one")
62
+ # agent = self.client.beta.assistants.create(
63
+ # instructions=self.instructions,
64
+ # description=self.description,
65
+ # name=self.name,
66
+ # model=self._json_model,
67
+ # )
68
+ # self.agent_id = agent.id
69
+ # log(f"==== Creating Agent with ID: {self.agent_id} ====")
70
+ # self.save()
71
+ # return self.agent_id
72
+
73
+ # def clear_files(self, file_id=None):
74
+ # if not file_id:
75
+ # for vs in self.client.beta.vector_stores.list().data:
76
+ # try:
77
+ # self.client.beta.vector_stores.delete(vs.id)
78
+ # except openai_NotFoundError:
79
+ # log(f"==== Vector Store {vs.id} not found ====")
80
+ # for sf in self.client.files.list().data:
81
+ # self.client.files.delete(file_id=sf.id)
82
+ # else:
83
+ # self.client.files.delete(file_id=file_id)
84
+ # self.tools.pop("file_search", None)
85
+ # self.save()
86
+ # return self.client.files.list()
87
+
88
+ # def attach_file(self, file_contents, filename="dbdata.json"):
89
+ # # Upload the user provided file to OpenAI
90
+ # self.tools["file_search"] = {"type": "file_search"}
91
+ # # Create a vector store
92
+ # try:
93
+ # if vs := self.client.beta.vector_stores.list().data:
94
+ # self.vector_store = self.client.beta.vector_stores.retrieve(
95
+ # vector_store_id=vs[0].id
96
+ # ).id
97
+ # else:
98
+ # for sf in self.client.files.list().data:
99
+ # self.client.files.delete(file_id=sf.id)
100
+ # raise FileNotFoundError("No vector store found")
101
+ # except FileNotFoundError:
102
+ # self.vector_store = self.client.beta.vector_stores.create(
103
+ # name="World Reference",
104
+ # expires_after={"anchor": "last_active_at", "days": 14},
105
+ # ).id
106
+ # log(f"==== Vector Store ID: {self.vector_store}====")
107
+ # # Attach File
108
+ # file_obj = self.client.files.create(
109
+ # file=(filename, file_contents), purpose="assistants"
110
+ # )
111
+ # log(f"==== FileStore ID: {file_obj.id}====")
112
+ # self.client.beta.vector_stores.files.create(
113
+ # vector_store_id=self.vector_store,
114
+ # file_id=file_obj.id,
115
+ # )
116
+ # self.client.beta.assistants.update(
117
+ # self._get_agent_id(),
118
+ # tools=list(self.tools.values()),
119
+ # tool_resources={"file_search": {"vector_store_ids": [self.vector_store]}},
120
+ # )
121
+ # self.save()
122
+ # return file_obj.id
123
+
124
+ # def _add_function(self, user_function):
125
+ # user_function["strict"] = True
126
+ # user_function["parameters"]["additionalProperties"] = False
127
+ # if not user_function["parameters"].get("required"):
128
+ # user_function["parameters"]["required"] = list(
129
+ # user_function["parameters"]["properties"].keys()
130
+ # )
131
+
132
+ # self.tools["function"] = {"type": "function", "function": user_function}
133
+ # self.client.beta.assistants.update(
134
+ # self._get_agent_id(), tools=list(self.tools.values())
135
+ # )
136
+ # return """
137
+ # IMPORTANT: Always use the function 'response' tool to respond to the user with only the requested JSON schema. DO NOT add any text to the response outside of the JSON schema.
138
+
139
+ # """
140
+
141
+ # def _format_messages(self, messages):
142
+ # message_list = []
143
+ # if isinstance(messages, str):
144
+ # message_list.insert(0, {"role": "user", "content": messages})
145
+ # else:
146
+ # for message in messages:
147
+ # if isinstance(message, str):
148
+ # message_list.insert(0, {"role": "user", "content": message})
149
+ # else:
150
+ # raise Exception(
151
+ # f"==== Invalid message: {message} ====\nMust be a string "
152
+ # )
153
+ # return message_list
154
+
155
+ # def generate_json(self, messages, function, additional_instructions=""):
156
+ # # _instructions_addition = self._add_function(function)
157
+ # function["strict"] = True
158
+ # function["parameters"]["additionalProperties"] = False
159
+ # function["parameters"]["required"] = list(
160
+ # function["parameters"]["properties"].keys()
161
+ # )
162
+
163
+ # formatted_messages = self._format_messages(messages)
164
+ # thread = self.client.beta.threads.create(messages=formatted_messages)
165
+ # # log(function, _print=True)
166
+ # running_job = True
167
+ # while running_job:
168
+ # try:
169
+ # run = self.client.beta.threads.runs.create_and_poll(
170
+ # thread_id=thread.id,
171
+ # assistant_id=self._get_agent_id(),
172
+ # additional_instructions=additional_instructions,
173
+ # parallel_tool_calls=False,
174
+ # tools=[
175
+ # {"type": "file_search"},
176
+ # {"type": "function", "function": function},
177
+ # ],
178
+ # tool_choice={
179
+ # "type": "function",
180
+ # "function": {"name": function["name"]},
181
+ # },
182
+ # )
183
+ # log(f"==== Job Status: {run.status} ====", _print=True)
184
+ # if run.status in [
185
+ # "failed",
186
+ # "expired",
187
+ # "canceled",
188
+ # "completed",
189
+ # "incomplete",
190
+ # "requires_action",
191
+ # ]:
192
+ # running_job = False
193
+
194
+ # except openai.BadRequestError as err:
195
+ # # Handle specific bad request errors
196
+ # log(f"==== Error: {err} ====", _print=True)
197
+ # if "already has an active run" in err:
198
+ # log("Previous run is still active. Waiting...", _print=True)
199
+ # time.sleep(2) # wait before retrying or checking run status
200
+ # else:
201
+ # raise err
202
+
203
+ # # while run.status in ["queued", "in_progress"]:
204
+ # # run = self.client.beta.threads.runs.retrieve(
205
+ # # thread_id=thread.id,
206
+ # # run_id=run.id,
207
+ # # )
208
+ # # time.sleep(0.5)
209
+ # if run.status in ["failed", "expired", "canceled"]:
210
+ # log(f"==== !!! ERROR !!!: {run.last_error} ====", _print=True)
211
+ # return None
212
+ # log("=================== RUN COMPLETED ===================", _print=True)
213
+ # # log(run.status, _print=True)
214
+ # if run.status == "completed":
215
+ # response = self.client.beta.threads.messages.list(thread_id=thread.id)
216
+ # results = response.data[0].content[0].text.value
217
+ # elif run.status == "requires_action":
218
+ # results = run.required_action.submit_tool_outputs.tool_calls[
219
+ # 0
220
+ # ].function.arguments
221
+ # else:
222
+ # log(f"====Status: {run.status} Error: {run.last_error} ====", _print=True)
223
+ # return None
224
+
225
+ # results = results[results.find("{") : results.rfind("}") + 1]
226
+ # try:
227
+ # results = json.loads(results, strict=False)
228
+ # except Exception:
229
+ # log(f"==== Invalid JSON:\n{results}", _print=True)
230
+ # return {}
231
+ # else:
232
+ # # log(f"==== Results: {results}", _print=True)
233
+ # # log("=================== END REPORT ===================", _print=True)
234
+ # return results
235
+
236
+ # def generate_text(self, messages, additional_instructions=""):
237
+ # self._get_agent_id()
238
+ # formatted_messages = self._format_messages(messages)
239
+ # thread = self.client.beta.threads.create(messages=formatted_messages)
240
+
241
+ # run = self.client.beta.threads.runs.create(
242
+ # thread_id=thread.id,
243
+ # assistant_id=self._get_agent_id(),
244
+ # additional_instructions=additional_instructions,
245
+ # parallel_tool_calls=False,
246
+ # )
247
+
248
+ # while run.status in ["queued", "in_progress"]:
249
+ # run = self.client.beta.threads.runs.retrieve(
250
+ # thread_id=thread.id,
251
+ # run_id=run.id,
252
+ # )
253
+ # time.sleep(0.5)
254
+ # log(f"==== Job Status: {run.status} ====", _print=True)
255
+
256
+ # if run.status in ["failed", "expired", "canceled"]:
257
+ # log(f"==== Error: {run.last_error} ====", _print=True)
258
+ # return None
259
+ # # log("=================== RUN COMPLETED ===================", _print=True)
260
+ # # log(run.status, _print=True)
261
+ # if run.status == "completed":
262
+ # response = self.client.beta.threads.messages.list(thread_id=thread.id)
263
+ # results = response.data[0].content[0].text.value
264
+ # else:
265
+ # log(f"====Status: {run.status} Error: {run.last_error} ====", _print=True)
266
+ # return None
267
+
268
+ # # log(results, _print=True)
269
+ # # log("=================== END REPORT ===================", _print=True)
270
+ # return results
271
+
272
+ # def generate_audio(self, prompt, **kwargs):
273
+ # voice = kwargs.get("voice") or random.choice(
274
+ # ["alloy", "echo", "fable", "onyx", "nova", "shimmer"]
275
+ # )
276
+ # response = self.client.audio.speech.create(
277
+ # model="tts-1",
278
+ # voice=voice,
279
+ # input=prompt,
280
+ # )
281
+ # # log(response, _print=True)
282
+ # return response.read()
283
+
284
+ # def generate_image(self, prompt, **kwargs):
285
+ # image = None
286
+ # try:
287
+ # response = self.client.images.generate(
288
+ # model=self._image_model,
289
+ # prompt=prompt,
290
+ # response_format="b64_json",
291
+ # **kwargs,
292
+ # )
293
+ # image_dict = response.data[0]
294
+ # except Exception as e:
295
+ # log(f"==== Error: Unable to create image ====\n\n{e}", _print=True)
296
+ # else:
297
+ # image = b64decode(image_dict.b64_json)
298
+ # return image
299
+
300
+ # def summarize_text(self, text, primer=""):
301
+ # message = [
302
+ # {
303
+ # "role": "system",
304
+ # "content": f"You are a highly skilled AI trained in language comprehension and summarization.{primer}",
305
+ # },
306
+ # {"role": "user", "content": text},
307
+ # ]
308
+ # response = self.client.chat.completions.create(
309
+ # model=self._text_model, messages=message
310
+ # )
311
+ # try:
312
+ # result = response.choices[0].message.content
313
+ # except Exception as e:
314
+ # log(f"{type(e)}:{e}\n\n Unable to generate content ====")
315
+ # return None
316
+
317
+ # return result
@@ -0,0 +1,99 @@
1
+ import io
2
+ import json
3
+ import os
4
+ import random
5
+ import time
6
+ from base64 import b64decode
7
+
8
+ import openai
9
+ from ollama import ChatResponse, chat
10
+
11
+ from autonomous import log
12
+ from autonomous.model.autoattr import DictAttr, ListAttr, StringAttr
13
+ from autonomous.model.automodel import AutoModel
14
+
15
+
16
+ class LocalAIModel(AutoModel):
17
+ _client = None
18
+ instructions = StringAttr(
19
+ default="You are highly skilled AI trained to assist with various tasks."
20
+ )
21
+ description = StringAttr(
22
+ default="A helpful AI assistant trained to assist with various tasks."
23
+ )
24
+
25
+ @property
26
+ def client(self):
27
+ if not self._client:
28
+ self._client = "deepseek-r1" # OpenAI(api_key=os.environ.get("OPENAI_KEY"))
29
+ return self._client
30
+
31
+ def clear_agent(self):
32
+ pass
33
+
34
+ def clear_agents(self):
35
+ pass
36
+
37
+ # def _get_agent_id(self):
38
+ # pass
39
+
40
+ # def _add_function(self, user_function):
41
+ pass
42
+
43
+ def _format_messages(self, messages):
44
+ pass
45
+
46
+ def clear_files(self, file_id=None):
47
+ pass
48
+
49
+ def attach_file(self, file_contents, filename="dbdata.json"):
50
+ pass
51
+
52
+ def generate_json(self, messages, function, additional_instructions=""):
53
+ message = messages + additional_instructions
54
+ message += f"""
55
+ IMPORTANT: Respond in JSON FORMAT using the SCHEMA below. DO NOT add any text to the response outside of the supplied JSON schema:
56
+ {function}
57
+ """
58
+ response: ChatResponse = chat(
59
+ model=self.client,
60
+ messages=[
61
+ {
62
+ "role": "user",
63
+ "content": message,
64
+ },
65
+ ],
66
+ )
67
+ return response.message.content
68
+
69
+ def generate_text(self, messages, additional_instructions=""):
70
+ message = messages + additional_instructions
71
+ response: ChatResponse = chat(
72
+ model=self.client,
73
+ messages=[
74
+ {
75
+ "role": "user",
76
+ "content": message,
77
+ },
78
+ ],
79
+ )
80
+ return response.message.content
81
+
82
+ def generate_audio(self, prompt, **kwargs):
83
+ raise NotImplementedError
84
+
85
+ def generate_image(self, prompt, **kwargs):
86
+ raise NotImplementedError
87
+
88
+ def summarize_text(self, text, primer=""):
89
+ response: ChatResponse = chat(
90
+ model=self.client,
91
+ messages=[
92
+ {
93
+ "role": "system",
94
+ "content": f"You are a highly skilled AI trained in language comprehension and summarization.{primer}",
95
+ },
96
+ {"role": "user", "content": text},
97
+ ],
98
+ )
99
+ return response.message.content