cognitrix 0.2.2__tar.gz → 0.2.4__tar.gz

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.
Files changed (38) hide show
  1. cognitrix-0.2.4/PKG-INFO +162 -0
  2. cognitrix-0.2.4/README.md +110 -0
  3. {cognitrix-0.2.2 → cognitrix-0.2.4}/cognitrix/agents/base.py +18 -13
  4. {cognitrix-0.2.2 → cognitrix-0.2.4}/cognitrix/agents/templates.py +2 -0
  5. {cognitrix-0.2.2 → cognitrix-0.2.4}/cognitrix/cli.py +76 -20
  6. {cognitrix-0.2.2 → cognitrix-0.2.4}/cognitrix/config.py +1 -1
  7. {cognitrix-0.2.2 → cognitrix-0.2.4}/cognitrix/llms/__init__.py +2 -1
  8. {cognitrix-0.2.2 → cognitrix-0.2.4}/cognitrix/llms/google_llm.py +1 -1
  9. cognitrix-0.2.4/cognitrix/llms/ollama_llm.py +115 -0
  10. {cognitrix-0.2.2 → cognitrix-0.2.4}/cognitrix/llms/openai_llm.py +4 -6
  11. {cognitrix-0.2.2 → cognitrix-0.2.4}/cognitrix/llms/session.py +2 -2
  12. {cognitrix-0.2.2 → cognitrix-0.2.4}/cognitrix/tools/base.py +16 -0
  13. {cognitrix-0.2.2 → cognitrix-0.2.4}/cognitrix/tools/misc.py +14 -11
  14. {cognitrix-0.2.2 → cognitrix-0.2.4}/cognitrix/tools/python.py +1 -0
  15. cognitrix-0.2.4/cognitrix/tools/tool.py +32 -0
  16. {cognitrix-0.2.2 → cognitrix-0.2.4}/cognitrix/transcriber.py +25 -13
  17. {cognitrix-0.2.2 → cognitrix-0.2.4}/cognitrix/utils/__init__.py +61 -13
  18. {cognitrix-0.2.2 → cognitrix-0.2.4}/pyproject.toml +4 -2
  19. cognitrix-0.2.2/PKG-INFO +0 -127
  20. cognitrix-0.2.2/README.md +0 -77
  21. cognitrix-0.2.2/cognitrix/tools/tool.py +0 -26
  22. {cognitrix-0.2.2 → cognitrix-0.2.4}/LICENSE +0 -0
  23. {cognitrix-0.2.2 → cognitrix-0.2.4}/cognitrix/__init__.py +0 -0
  24. {cognitrix-0.2.2 → cognitrix-0.2.4}/cognitrix/agents/__init__.py +0 -0
  25. {cognitrix-0.2.2 → cognitrix-0.2.4}/cognitrix/agents/assistant.py +0 -0
  26. {cognitrix-0.2.2 → cognitrix-0.2.4}/cognitrix/agents/core.py +0 -0
  27. {cognitrix-0.2.2 → cognitrix-0.2.4}/cognitrix/app.py +0 -0
  28. {cognitrix-0.2.2 → cognitrix-0.2.4}/cognitrix/llms/anthropic_llm.py +0 -0
  29. {cognitrix-0.2.2 → cognitrix-0.2.4}/cognitrix/llms/base.py +0 -0
  30. {cognitrix-0.2.2 → cognitrix-0.2.4}/cognitrix/llms/clarifai_llm.py +0 -0
  31. {cognitrix-0.2.2 → cognitrix-0.2.4}/cognitrix/llms/cohere_llm.py +0 -0
  32. {cognitrix-0.2.2 → cognitrix-0.2.4}/cognitrix/llms/groq_llm.py +0 -0
  33. {cognitrix-0.2.2 → cognitrix-0.2.4}/cognitrix/llms/local_llm.py +0 -0
  34. {cognitrix-0.2.2 → cognitrix-0.2.4}/cognitrix/llms/mindsdb_llm.py +0 -0
  35. {cognitrix-0.2.2 → cognitrix-0.2.4}/cognitrix/llms/together_llm.py +0 -0
  36. {cognitrix-0.2.2 → cognitrix-0.2.4}/cognitrix/tasks/__init__.py +0 -0
  37. {cognitrix-0.2.2 → cognitrix-0.2.4}/cognitrix/tasks/base.py +0 -0
  38. {cognitrix-0.2.2 → cognitrix-0.2.4}/cognitrix/tools/__init__.py +0 -0
@@ -0,0 +1,162 @@
1
+ Metadata-Version: 2.1
2
+ Name: cognitrix
3
+ Version: 0.2.4
4
+ Summary: Package for creating AI Agents using llms
5
+ Home-page: https://github.com/theonlyamos/cognitrix
6
+ License: Apache2
7
+ Keywords: cognitrix,ai,agents,ai agents,ai-agents,llms,autonomous agents
8
+ Author: theonlyamos
9
+ Author-email: theonlyamos@gmail.com
10
+ Requires-Python: >=3.12,<4.0
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Classifier: License :: Other/Proprietary License
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.6
21
+ Classifier: Programming Language :: Python :: 3.7
22
+ Classifier: Programming Language :: Python :: 3.8
23
+ Classifier: Programming Language :: Python :: 3.9
24
+ Classifier: Topic :: Software Development :: Build Tools
25
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
26
+ Requires-Dist: aiofiles (>=23.2.1,<24.0.0)
27
+ Requires-Dist: aiohttp (>=3.9.3,<4.0.0)
28
+ Requires-Dist: anthropic (>=0.17.0,<0.18.0)
29
+ Requires-Dist: beautifulsoup4 (>=4.12.3,<5.0.0)
30
+ Requires-Dist: clarifai (>=10.1.0,<11.0.0)
31
+ Requires-Dist: cohere (>=4.50,<5.0)
32
+ Requires-Dist: deepgram-sdk (==3.*)
33
+ Requires-Dist: google-generativeai (>=0.4.0,<0.5.0)
34
+ Requires-Dist: google-search-results (>=2.4.2,<3.0.0)
35
+ Requires-Dist: groq (>=0.4.1,<0.5.0)
36
+ Requires-Dist: ollama (>=0.2.0,<0.3.0)
37
+ Requires-Dist: openai (>=1.12.0,<2.0.0)
38
+ Requires-Dist: pillow (>=10.2.0,<11.0.0)
39
+ Requires-Dist: pyaudio (>=0.2.14,<0.3.0)
40
+ Requires-Dist: pyautogui (>=0.9.54,<0.10.0)
41
+ Requires-Dist: pydantic (>=2.6.2,<3.0.0)
42
+ Requires-Dist: pydub (>=0.25.1,<0.26.0)
43
+ Requires-Dist: python-dotenv (>=1.0.1,<2.0.0)
44
+ Requires-Dist: requests (>=2.31.0,<3.0.0)
45
+ Requires-Dist: serpapi (>=0.1.5,<0.2.0)
46
+ Requires-Dist: together (>=0.2.11,<0.3.0)
47
+ Requires-Dist: uuid (>=1.30,<2.0)
48
+ Requires-Dist: xmltodict (>=0.13.0,<0.14.0)
49
+ Project-URL: Bug Tracker, https://github.com/theonlyamos/cognitrix/issues
50
+ Project-URL: Repository, https://github.com/theonlyamos/cognitrix
51
+ Description-Content-Type: text/markdown
52
+
53
+ # Cognitrix
54
+
55
+ Cognitrix is an open-source autonomous AI agents orchestrator built in Python. It allows you to create and manage AI agents with ease and integrates seamlessly with large language models (LLMs) from various providers.
56
+
57
+ ## Features
58
+
59
+ - **Agent Creation and Management:** Create, list, and load AI agents with customizable names, tasks, and configurations.
60
+ - **LLM Integration:** Integrates with multiple LLM providers, including Anthropic (Claude), Cohere, Groq, Google, OpenAI, and Together.
61
+ - **Modular Architecture:** Easily extensible, allowing the addition of new tools, agents, and LLM integrations.
62
+ - **Conversational Interface:** Interact with AI agents through a command-line interface, providing queries and receiving responses.
63
+ - **Tool Integration:** Agents can utilize a variety of tools, including calculators, web searches, file system browsers, and more.
64
+ - **Autonomous Agent Mode:** Agents can operate autonomously, visually perceiving the screen, interacting with UI elements, and performing tasks.
65
+ - **Multimodal Support:** Handles both text and image inputs/outputs, enabling multimodal interactions.
66
+
67
+ ## Architecture
68
+
69
+ Cognitrix's architecture is designed to be highly modular and extensible:
70
+
71
+ - **Agents:** The base `Agent` class and specialized classes like `AIAssistant` for creating and managing AI agents.
72
+ - **LLMs:** A collection of classes for integrating with various LLM providers (Cohere, OpenAI, Claude, etc.).
73
+ - **Tools:** A set of tools that agents can utilize. Each tool has a `category` attribute for grouping and management.
74
+ - **Templates:** Customizable prompt templates guide the behavior and output formats of LLMs.
75
+
76
+ More tools can be added by creating new classes that inherit from the `Tool` base class and specifying a unique `category`.
77
+
78
+ ## Installation
79
+
80
+ ```bash
81
+ pip install cognitrix
82
+ ```
83
+
84
+ Alternatively, you can install directly from GitHub:
85
+
86
+ ```bash
87
+ pip install https://github.com/theonlyamos/cognitrix/archive/main.zip
88
+ ```
89
+
90
+ ## Usage
91
+
92
+ To run Cognitrix with default settings:
93
+
94
+ ```bash
95
+ cognitrix
96
+ ```
97
+
98
+ To list supported LLM providers:
99
+
100
+ ```bash
101
+ cognitrix --providers
102
+ ```
103
+
104
+ To list created agents:
105
+
106
+ ```bash
107
+ cognitrix agents
108
+ ```
109
+
110
+ To list available tools:
111
+
112
+ ```bash
113
+ cognitrix --tools
114
+ ```
115
+
116
+ To run Cognitrix with a specific provider:
117
+
118
+ ```bash
119
+ cognitrix --provider <provider_name>
120
+ ```
121
+
122
+ To run Cognitrix with a specific agent:
123
+
124
+ ```bash
125
+ cognitrix --agent <agent_name>
126
+ ```
127
+
128
+ To run Cognitrix with a category of tools:
129
+
130
+ ```bash
131
+ cognitrix --load-tools "web"
132
+ ```
133
+
134
+ To run Cognitrix with categories of tools:
135
+
136
+ ```bash
137
+ cognitrix --load-tools "web,general"
138
+ ```
139
+
140
+ To create a new agent:
141
+
142
+ ```bash
143
+ cognitrix agents --new
144
+ ```
145
+
146
+ For more options and usage details, use the help command:
147
+
148
+ ```bash
149
+ cognitrix --help
150
+ ```
151
+
152
+ ## Contributing
153
+
154
+ Cognitrix is open source and contributions are welcome! Please refer to [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines on how to contribute.
155
+
156
+ ## License
157
+
158
+ This project is licensed under the MIT license. See [LICENSE.md](LICENSE.md) for more information.
159
+
160
+ ## Acknowledgments
161
+
162
+ Cognitrix was created by [Amos Amissah](https://github.com/theonlyamos) and is inspired by projects like AutoGPT and GPT Engineer. Special thanks to the open-source community and AI companies providing LLM APIs.
@@ -0,0 +1,110 @@
1
+ # Cognitrix
2
+
3
+ Cognitrix is an open-source autonomous AI agents orchestrator built in Python. It allows you to create and manage AI agents with ease and integrates seamlessly with large language models (LLMs) from various providers.
4
+
5
+ ## Features
6
+
7
+ - **Agent Creation and Management:** Create, list, and load AI agents with customizable names, tasks, and configurations.
8
+ - **LLM Integration:** Integrates with multiple LLM providers, including Anthropic (Claude), Cohere, Groq, Google, OpenAI, and Together.
9
+ - **Modular Architecture:** Easily extensible, allowing the addition of new tools, agents, and LLM integrations.
10
+ - **Conversational Interface:** Interact with AI agents through a command-line interface, providing queries and receiving responses.
11
+ - **Tool Integration:** Agents can utilize a variety of tools, including calculators, web searches, file system browsers, and more.
12
+ - **Autonomous Agent Mode:** Agents can operate autonomously, visually perceiving the screen, interacting with UI elements, and performing tasks.
13
+ - **Multimodal Support:** Handles both text and image inputs/outputs, enabling multimodal interactions.
14
+
15
+ ## Architecture
16
+
17
+ Cognitrix's architecture is designed to be highly modular and extensible:
18
+
19
+ - **Agents:** The base `Agent` class and specialized classes like `AIAssistant` for creating and managing AI agents.
20
+ - **LLMs:** A collection of classes for integrating with various LLM providers (Cohere, OpenAI, Claude, etc.).
21
+ - **Tools:** A set of tools that agents can utilize. Each tool has a `category` attribute for grouping and management.
22
+ - **Templates:** Customizable prompt templates guide the behavior and output formats of LLMs.
23
+
24
+ More tools can be added by creating new classes that inherit from the `Tool` base class and specifying a unique `category`.
25
+
26
+ ## Installation
27
+
28
+ ```bash
29
+ pip install cognitrix
30
+ ```
31
+
32
+ Alternatively, you can install directly from GitHub:
33
+
34
+ ```bash
35
+ pip install https://github.com/theonlyamos/cognitrix/archive/main.zip
36
+ ```
37
+
38
+ ## Usage
39
+
40
+ To run Cognitrix with default settings:
41
+
42
+ ```bash
43
+ cognitrix
44
+ ```
45
+
46
+ To list supported LLM providers:
47
+
48
+ ```bash
49
+ cognitrix --providers
50
+ ```
51
+
52
+ To list created agents:
53
+
54
+ ```bash
55
+ cognitrix agents
56
+ ```
57
+
58
+ To list available tools:
59
+
60
+ ```bash
61
+ cognitrix --tools
62
+ ```
63
+
64
+ To run Cognitrix with a specific provider:
65
+
66
+ ```bash
67
+ cognitrix --provider <provider_name>
68
+ ```
69
+
70
+ To run Cognitrix with a specific agent:
71
+
72
+ ```bash
73
+ cognitrix --agent <agent_name>
74
+ ```
75
+
76
+ To run Cognitrix with a category of tools:
77
+
78
+ ```bash
79
+ cognitrix --load-tools "web"
80
+ ```
81
+
82
+ To run Cognitrix with categories of tools:
83
+
84
+ ```bash
85
+ cognitrix --load-tools "web,general"
86
+ ```
87
+
88
+ To create a new agent:
89
+
90
+ ```bash
91
+ cognitrix agents --new
92
+ ```
93
+
94
+ For more options and usage details, use the help command:
95
+
96
+ ```bash
97
+ cognitrix --help
98
+ ```
99
+
100
+ ## Contributing
101
+
102
+ Cognitrix is open source and contributions are welcome! Please refer to [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines on how to contribute.
103
+
104
+ ## License
105
+
106
+ This project is licensed under the MIT license. See [LICENSE.md](LICENSE.md) for more information.
107
+
108
+ ## Acknowledgments
109
+
110
+ Cognitrix was created by [Amos Amissah](https://github.com/theonlyamos) and is inspired by projects like AutoGPT and GPT Engineer. Special thanks to the open-source community and AI companies providing LLM APIs.
@@ -115,19 +115,21 @@ class Agent(BaseModel):
115
115
  def get_tool_by_name(self, name: str) -> Optional[Tool]:
116
116
  return next((tool for tool in self.tools if tool.name.lower() == name.lower()), None)
117
117
 
118
- async def process_response(self, response: str) -> Union[dict, str]:
118
+ async def process_response(self, response: str|dict) -> Union[dict, str]:
119
119
  # response = response.replace("'", '"')
120
- response = response.replace('\\n', '')
121
- response = response.replace("'", "\"")
122
- # response = response.replace('"', '\\"')
123
- response_data = extract_json(response)
120
+ response_data = response
121
+ if isinstance(response, str):
122
+ response = response.replace('\\n', '')
123
+ response = response.replace("'", "\"")
124
+ # response = response.replace('"', '\\"')
125
+ response_data = extract_json(response)
124
126
 
125
127
 
126
128
  try:
127
129
  if isinstance(response_data, dict):
128
- final_result_keys = ['final_answer', 'function_call_result', 'respons']
130
+ # final_result_keys = ['final_answer', 'function_call_result', 'respons']
129
131
 
130
- if response_data['type'].replace('\\', '') in final_result_keys:
132
+ if response_data['type'].replace('\\', '') != 'function_call':
131
133
  return response_data['result']
132
134
 
133
135
  tool = self.get_tool_by_name(response_data['function'])
@@ -228,8 +230,11 @@ class Agent(BaseModel):
228
230
  logger.exception(e)
229
231
  break
230
232
 
231
- def start(self, session_id: Optional[str] = None):
232
- self.initialize(session_id)
233
+ def start(self, session_id: Optional[str] = None, audio: bool = False):
234
+ if audio:
235
+ self.start_audio()
236
+ else:
237
+ self.initialize(session_id)
233
238
 
234
239
  def handle_transcription(self, sentence: str, transcriber: Transcriber):
235
240
  if sentence:
@@ -248,16 +253,16 @@ class Agent(BaseModel):
248
253
  if isinstance(processsed_response, dict) and processsed_response['type'] == 'function_call_result':
249
254
  query = processsed_response
250
255
  else:
251
- print(f"\n{self.name}: {processsed_response}")
252
256
  if isinstance(processsed_response, str):
253
257
  transcriber.text_to_speech(processsed_response)
258
+ print(f"\n{self.name}: {processsed_response}")
254
259
 
255
260
 
256
261
  def start_audio(self, **kwargs):
257
262
  transcriber = Transcriber(on_message_callback=self.handle_transcription) # Pass callback to Transcriber
258
263
  if transcriber.start_transcription():
259
264
  print("Audio transcription started.")
260
- input("\n\nPress Enter to stop recording...\n\n")
265
+ input("\n\nPress Enter to quit...\n\n")
261
266
  transcriber.stop_transcription()
262
267
  else:
263
268
  print("Failed to start audio transcription.")
@@ -340,7 +345,7 @@ class Agent(BaseModel):
340
345
  async with aiofiles.open(AGENTS_FILE, 'r') as file:
341
346
  content = await file.read()
342
347
  agents = json.loads(content) if content else []
343
- agents.append(new_agent.model_dump())
348
+ agents.append(new_agent.dict())
344
349
 
345
350
  async with aiofiles.open(AGENTS_FILE, 'w') as file:
346
351
  await file.write(json.dumps(agents, indent=4))
@@ -406,7 +411,7 @@ class Agent(BaseModel):
406
411
  if agent.id == self.id:
407
412
  agents[index] = self
408
413
 
409
- updated_agents.append(agent.model_dump())
414
+ updated_agents.append(agent.dict())
410
415
 
411
416
  async with aiofiles.open(AGENTS_FILE, 'w') as file:
412
417
  await file.write(json.dumps(updated_agents, indent=4))
@@ -346,6 +346,8 @@ Example 5 (Final Answer with Chain of Thought):
346
346
  "type": "final_answer",
347
347
  "result": "25 degrees Celsius is equivalent to 77 degrees Fahrenheit."
348
348
  }
349
+
350
+ The only keys allowed in the json response are ["observervation", "tought", "type", "function", "arguments", "result"].
349
351
  """
350
352
 
351
353
  AUTONOMOUSE_AGENT_2_JSON_REMINDER = """
@@ -29,20 +29,58 @@ def add_agent():
29
29
  sys.exit()
30
30
 
31
31
  def list_agents():
32
- agents_str = "\nAvailable Agents:"
33
- for index, agent in enumerate(asyncio.run(Agent.list_agents())):
34
- agents_str += (f"\n[{index}] {agent.name}") #type: ignore
35
- print(agents_str)
32
+ agents = asyncio.run(Agent.list_agents())
33
+ agent_names = [agent.name for agent in agents]
34
+ max_col = len(max(agent_names, key=len))
35
+ max_width = 10
36
+ max_col = max_col if max_col >= max_width else max_width
37
+
38
+ print(max_col)
39
+ print("\nAvailable Agents:")
40
+ print(f" {'_'*((int(len(agents)/10)+5)+max_width+1)}")
41
+ print(f"| #{' '*(int(len(agents)/10))} | {'Agent Name'+' '*(max_col-max_width)} |")
42
+ print(f"|{'-'*(int(len(agents)/10)+3)}|-{'-'*(max_col)}-|")
43
+ for index, a in enumerate(agents):
44
+ padding = (len(str(index)))-int(len(agents)/10)
45
+ padding = padding if padding else padding + 2
46
+ print(f"| {str(index) + ' '*padding}| {a.name + ' '*(max_col-len(a.name))} |")
36
47
 
37
48
  def list_providers():
38
- print("\nAvailable providers:")
39
- for index, l in enumerate(LLM.list_llms()):
40
- print(f"[{index}] {l}")
49
+ providers = LLM.list_llms()
50
+ provider_names = [p for p in providers]
51
+ max_col = len(max(provider_names, key=len))
52
+ max_width = 9
53
+ max_col = max_col if max_col >= max_width else max_width
54
+
55
+ print("\nAvailable Providers:")
56
+ print(f" {'_'*((int(len(providers)/10)+5)+max_width+1)}")
57
+ print(f"| #{' '*(int(len(providers)/10))} | {'Provider'+' '*(max_col-7)}|")
58
+ print(f"|{'-'*(int(len(providers)/10)+3)}|-{'-'*(max_col)}-|")
59
+ for index, p in enumerate(providers):
60
+ padding = (len(str(index)))-int(len(providers)/10)
61
+ padding = padding if padding else padding + 2
62
+ print(f"| {str(index) + ' '*padding}| {p + ' '*(max_col-len(p))} |")
63
+
41
64
 
42
- def list_tools():
65
+ def list_tools(category='all'):
66
+ tools = []
67
+ if category == 'all':
68
+ tools = Tool.list_all_tools()
69
+ else:
70
+ tools = Tool.get_tools_by_category(category)
71
+ tool_names = [t.name for t in tools]
72
+ max_col = len(max(tool_names, key=len))
73
+ max_width = 13
74
+ max_col = max_col if max_col >= max_width else max_width
75
+
43
76
  print("\nAvailable Tools:")
44
- for index, l in enumerate(Tool.list_all_tools()):
45
- print(f"[{index}] {l.name}")
77
+ print(f" {'_'*((int(len(tools)/10)+5)+max_col+max_width+4)}")
78
+ print(f"| #{' '*(int(len(tools)/10))} | {'Tool Name'+' '*(max_col-9)} | {'Tool category'+' '*(max_width-13)} |")
79
+ print(f"|{'-'*(int(len(tools)/10)+3)}|-{'-'*(max_col)}-|-{'-'*(max_width)}-|")
80
+ for index, t in enumerate(tools):
81
+ padding = (len(str(index)))-int(len(tools)/10)
82
+ padding = padding if padding else padding + 2
83
+ print(f"| {str(index) + ' '*padding}| {t.name + ' '*(max_col-len(t.name))} | {t.category + ' '*(max_width-len(t.category))} |")
46
84
 
47
85
  def list_sessions():
48
86
  print("\nSaved Sessions:")
@@ -54,7 +92,7 @@ def manage_agents(args: Namespace):
54
92
  try:
55
93
  if args.new:
56
94
  add_agent()
57
- elif args.list:
95
+ if args.list:
58
96
  list_agents()
59
97
  except KeyboardInterrupt:
60
98
  print()
@@ -62,6 +100,17 @@ def manage_agents(args: Namespace):
62
100
  except Exception as e:
63
101
  logging.exception(e)
64
102
  sys.exit(1)
103
+
104
+ def manage_tools(args: Namespace):
105
+ try:
106
+ if args.list:
107
+ list_tools(args.list)
108
+ except KeyboardInterrupt:
109
+ print()
110
+ sys.exit()
111
+ except Exception as e:
112
+ logging.exception(e)
113
+ sys.exit(1)
65
114
 
66
115
  def str_or_file(string):
67
116
  if len(string) > 100:
@@ -118,16 +167,21 @@ def start(args: Namespace):
118
167
  if args.provider:
119
168
  assistant.llm = provider
120
169
  assistant.name = args.name
121
- if args.load_all_tools:
170
+ if 'all' in args.load_tools:
122
171
  assistant.tools = Tool.list_all_tools()
172
+ else:
173
+ tools = []
174
+ for cat in args.load_tools:
175
+ loaded_tools = Tool.get_tools_by_category(cat.lower())
176
+ tools.extend(loaded_tools)
177
+
178
+ assistant.tools = tools
179
+
123
180
 
124
181
  assistant.format_system_prompt()
125
182
  asyncio.run(assistant.save())
126
183
 
127
- if args.audio:
128
- assistant.start_audio()
129
- else:
130
- assistant.start(args.session)
184
+ assistant.start(args.session, audio=args.audio)
131
185
  except Exception as e:
132
186
  logging.exception(e)
133
187
  parser.print_help()
@@ -140,19 +194,21 @@ def get_arguments():
140
194
  agents_parser = subparsers.add_parser('agents', help="Manage agents")
141
195
  agents_parser.add_argument("name", type=str, nargs="?", help="Name of an agent to manage (details|update|remove)")
142
196
  agents_parser.add_argument('--new', action='store_true', help='Create a new agent')
143
- agents_parser.add_argument('--list', action='store_false', help='List all saved agents')
197
+ agents_parser.add_argument('-l', '--list', action='store_false', help='List all saved agents')
144
198
  agents_parser.add_argument('--update', action='store_true', help='Update an agent')
145
199
  agents_parser.add_argument('--remove', action='store_true', help='Delete an agent')
146
-
147
200
  agents_parser.set_defaults(func=manage_agents)
201
+
202
+ agents_parser = subparsers.add_parser('tools', help="Manage tools")
203
+ agents_parser.add_argument('-l', '--list', type=str, default='all', nargs='?', choices=['all', 'general', 'system', 'web'], help='List tools by category')
204
+ agents_parser.set_defaults(func=manage_tools)
148
205
 
149
206
  parser.add_argument('--name', type=str, default='Assistant', help='Set name of agent')
150
207
  parser.add_argument('--provider', default='', help='Set llm provider to use')
151
208
  parser.add_argument('--providers', action='store_true', help='Get a list of all supported providers')
152
209
  parser.add_argument('--agents', action='store_true', help='List all saved agents')
153
210
  parser.add_argument('--agent', type=str, default='Assistant', help='Set which saved agent to use')
154
- parser.add_argument('--tools', action='store_true', help='List all available tools')
155
- parser.add_argument('--load-all-tools', action='store_true', help='Add all available tools to agent')
211
+ parser.add_argument('--load-tools', type=lambda s: [i for i in s.split(',')], default='general', help='Add tools by categories to agent')
156
212
  parser.add_argument('--model', type=str, default='', help='Specify model or model_url to use')
157
213
  parser.add_argument('--api-key', type=str, default='', help='Set api key of selected llm')
158
214
  parser.add_argument('--api-base', type=str, default='', help='Set api base of selected llm. Set if using local llm.')
@@ -3,7 +3,7 @@ import asyncio
3
3
  import aiofiles
4
4
  import json
5
5
 
6
- VERSION = '0.2.2'
6
+ VERSION = '0.2.4'
7
7
  SPIRAL_WORKDIR = Path('~').expanduser() / '.cognitrix'
8
8
 
9
9
  AGENTS_FILE = SPIRAL_WORKDIR / 'agents.json'
@@ -7,4 +7,5 @@ from cognitrix.llms.google_llm import Google
7
7
  from cognitrix.llms.anthropic_llm import Anthropic
8
8
  from cognitrix.llms.together_llm import Together
9
9
  from cognitrix.llms.clarifai_llm import Clarifai
10
- from cognitrix.llms.mindsdb_llm import MindsDB
10
+ from cognitrix.llms.mindsdb_llm import MindsDB
11
+ from cognitrix.llms.ollama_llm import Ollama
@@ -31,7 +31,7 @@ class Google(LLM):
31
31
  supports_system_prompt (bool): Flag to indicate if system prompt should be supported
32
32
  system_prompt (str): System prompt to prepend to queries
33
33
  """
34
- model: str = 'gemini-1.5-pro-latest'
34
+ model: str = 'gemini-1.5-flash'
35
35
  """model endpoint to use"""
36
36
 
37
37
  temperature: float = 0.0
@@ -0,0 +1,115 @@
1
+ from cognitrix.llms.base import LLM
2
+ from cognitrix.utils import image_to_base64
3
+ from typing import Any, Optional
4
+ from dotenv import load_dotenv
5
+ from ollama import Client
6
+ import logging
7
+ import sys
8
+ import os
9
+
10
+ logging.basicConfig(
11
+ format='%(asctime)s - %(levelname)s - [%(filename)s:%(lineno)d] - %(message)s',
12
+ datefmt='%d-%b-%y %H:%M:%S',
13
+ level=logging.WARNING
14
+ )
15
+ logger = logging.getLogger('cognitrix.log')
16
+ load_dotenv()
17
+
18
+
19
+ class Ollama(LLM):
20
+ """A class for interacting with the Ollama API.
21
+
22
+ Args:
23
+ model (str): The name of the Local model to use
24
+ temperature (float): The temperature to use when generating text
25
+ base_url (str): Base url of local llm server
26
+ chat_history (list): Chat history
27
+ max_tokens (int): The maximum number of tokens to generate in the completion
28
+ supports_system_prompt (bool): Flag to indicate if system prompt should be supported
29
+ system_prompt (str): System prompt to prepend to queries
30
+ """
31
+
32
+ model: str = 'llama3'
33
+ """model endpoint to use"""
34
+
35
+ vision_model: str = 'llava-phi3'
36
+ """vision model endpoint to use"""
37
+
38
+ temperature: float = 0.1
39
+ """What sampling temperature to use."""
40
+
41
+ api_key: str = 'not-needed'
42
+ """API key"""
43
+
44
+ base_url: str = 'http://localhost:11434'
45
+ """Base url of local llm server"""
46
+
47
+ max_tokens: int = 4048
48
+ """The maximum number of tokens to generate in the completion."""
49
+
50
+ chat_history: list[str] = []
51
+ """Chat history"""
52
+
53
+ supports_system_prompt: bool = True
54
+ """Flag to indicate if system prompt should be supported"""
55
+
56
+ system_prompt: str = ""
57
+ """System prompt to prepend to queries"""
58
+
59
+ def format_query(self, message: dict[str, str]) -> list:
60
+ """Formats a message for the Claude API.
61
+
62
+ Args:
63
+ message (dict[str, str]): The message to be formatted for the Claude API.
64
+
65
+ Returns:
66
+ list: A list of formatted messages for the Claude API.
67
+ """
68
+
69
+ formatted_message = [*self.chat_history, message]
70
+
71
+ messages = []
72
+
73
+ for fm in formatted_message:
74
+ if fm['type'] == 'text':
75
+ messages.append({
76
+ "role": fm['role'].lower(),
77
+ "content": fm['message']
78
+ })
79
+ else:
80
+ base64_image = image_to_base64(fm['image'])
81
+ self.model = self.vision_model
82
+ new_message = {
83
+ "role": fm['role'].lower(),
84
+ "content": "This is the result of the latest screenshot",
85
+ "images": [base64_image]
86
+ }
87
+ messages.append(new_message)
88
+
89
+ return messages
90
+
91
+ def __call__(self, query: dict, **kwds: dict)->Optional[str]:
92
+ """Generates a response to a query using the OpenAI API.
93
+
94
+ Args:
95
+ query (dict): The query to generate a response to.
96
+ kwds (dict): Additional keyword arguments to pass to the OpenAI API.
97
+
98
+ Returns:
99
+ A string containing the generated response.
100
+ """
101
+
102
+ client = Client('http://localhost:11434')
103
+
104
+ formatted_messages = self.format_query(query)
105
+
106
+ response = client.chat(
107
+ model=self.model,
108
+ messages=[
109
+ {"role": "user", "content": self.system_prompt},
110
+ *formatted_messages
111
+ ],
112
+ stream=False,
113
+ )
114
+ print(response)
115
+ return response['message']['content'] #type: ignore