AGofficial commited on
Commit
c9d2e01
·
verified ·
1 Parent(s): 803ef15

Upload 10 files

Browse files
.gitattributes CHANGED
@@ -33,3 +33,7 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ agi/assets/AGI.png filter=lfs diff=lfs merge=lfs -text
37
+ agi/assets/ArtificialGeneralIntelligence.pdf filter=lfs diff=lfs merge=lfs -text
38
+ agi/assets/sophos.png filter=lfs diff=lfs merge=lfs -text
39
+ agi/Qwen3-4B-Instruct-2507-Q3_K_S.gguf filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -1,3 +1,52 @@
1
- ---
2
- license: mit
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ language:
4
+ - en
5
+ base_model:
6
+ - Qwen/Qwen3-4B-Instruct-2507
7
+ ---
8
+
9
+ # AGI-3
10
+ ## Artificial General Intelligence
11
+
12
+ <img src="agi/assets/AGI.png">
13
+
14
+ ## Overview
15
+ This repository contains an implementation of a modular-agentic architecture for Artificial General Intelligence (AGI). The architecture is designed to facilitate the development of autonomous agents capable of complex reasoning, learning, and interaction with their environment.
16
+
17
+ # Example
18
+
19
+ ```python
20
+ from agi.sophos import Agent
21
+ from agi.sophos_tools import *
22
+
23
+ toolbox = all_tools()
24
+
25
+ agent = Agent(
26
+ name="Sophos Agent",
27
+ instructions="You are an AI Agent.",
28
+ model="Qwen3-4B-Instruct-2507-Q3_K_S.gguf",
29
+ tools=toolbox,
30
+ )
31
+
32
+ prompt = "Roll a dice, also whats the weather in Tokyo?"
33
+ response = agent.run(prompt)
34
+ print(response)
35
+ ```
36
+ ### Output:
37
+ ```python
38
+
39
+ """
40
+ You rolled a 4 on a 6-sided die. The weather in Tokyo is sunny with a temperature of 12°C during fall.
41
+ """
42
+
43
+ ```
44
+ ## Research Paper
45
+
46
+ [Read the research paper](agi/assets/ArtificialGeneralIntelligence.pdf)
47
+
48
+ This paper delineates a comprehensive architectural framework for the progressive realization of Artificial General Intelligence (AGI), predicated upon a modular-agentic paradigm. We present a system design that integrates sophisticated tool-use capabilities, hierarchical memory management, dynamic code execution, and nascent world-modeling functionalities. The proposed architecture, exemplified through a lightweight `Qwen3-4B-Instruct-2507-Q3_K_S.gguf` model, demonstrates a robust foundation for emergent cognitive properties such as autonomy, recursive self-improvement, and goal-oriented behavior. Furthermore, we explore the theoretical underpinnings of consciousness as an emergent property within complex neural architectures and postulate pathways towards super-intelligence through advanced computational and embodied interaction modalities. The exposition maintains a rigorous academic tone, employing advanced terminology to articulate the intricate conceptual and technical facets of AGI development.
49
+
50
+ ## Implementation
51
+
52
+ This is a more advanced implementation of the original AGI repository. It includes more tools, better memory management, and a more advanced agent structure.
agent_example.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from agi.sophos import Agent
2
+ from agi.sophos_tools import *
3
+
4
+ toolbox = all_tools()
5
+
6
+ agent = Agent(
7
+ name="Sophos Agent",
8
+ instructions="You are an AI Agent.",
9
+ model="agi/Qwen3-4B-Instruct-2507-Q3_K_S.gguf",
10
+ tools=toolbox,
11
+ )
12
+
13
+ prompt = "show me example html code, save it in a file named example.html"
14
+ response = agent.run(prompt)
15
+ print(response)
agi/Qwen3-4B-Instruct-2507-Q3_K_S.gguf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0ce20058cc0ed6b6c9213bb383589327e458c12ffce0842fc96867042d669c75
3
+ size 1886997600
agi/assets/AGI.png ADDED

Git LFS Details

  • SHA256: 4ec20d80d488743f729d04b5a30221a6d4892475ba9236ebec56fff172401257
  • Pointer size: 132 Bytes
  • Size of remote file: 6.45 MB
agi/assets/ArtificialGeneralIntelligence.pdf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7fb9e7d571936ff4cf2f36929eceedbfbfc0c88b601d50406a7e527472568549
3
+ size 785625
agi/assets/sophos.png ADDED

Git LFS Details

  • SHA256: 1709651f85da9b749053485351114e90803ab50d657d4606666091902ef708ce
  • Pointer size: 132 Bytes
  • Size of remote file: 2.72 MB
agi/sophos.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from agi.sophos_models import Sophos
2
+ from agi.sophos_tools import *
3
+
4
+ class Agent:
5
+ def __init__(self, name: str, instructions: str, model: str, tools: list):
6
+ self.name = name
7
+ self.instructions = instructions
8
+ self.model = model
9
+ self.tools = {tool.__name__: tool for tool in tools if hasattr(tool, "_is_tool")}
10
+ self.sophos = Sophos(model_path=model)
11
+
12
+ def process_tool_calls(self, response_content: str):
13
+ """Process tool calls from response content and return results"""
14
+ if "```tool" not in response_content:
15
+ return None
16
+
17
+ print("🔧 TOOL DETECTED - Processing...")
18
+ try:
19
+ tool_results = []
20
+
21
+ # Find all tool blocks in the response
22
+ parts = response_content.split("```tool")
23
+ for i in range(1, len(parts)): # Skip first part (before first ```tool)
24
+ tool_block = parts[i].split("```")[0].strip()
25
+ print(f"🔧 Tool block {i} found: {tool_block}")
26
+
27
+ tool_lines = [line.strip() for line in tool_block.split('\n') if line.strip()]
28
+
29
+ for tool_line in tool_lines:
30
+ if "(" in tool_line and ")" in tool_line:
31
+ tool_name = tool_line.split("(")[0].strip()
32
+ arg_part = tool_line.split("(", 1)[1].rsplit(")", 1)[0].strip()
33
+
34
+ if tool_name in self.tools:
35
+ print(f"🔧 CALLING TOOL: {tool_name}({arg_part})")
36
+
37
+ # Parse arguments more intelligently
38
+ if not arg_part:
39
+ # No arguments
40
+ tool_result = self.tools[tool_name]()
41
+ else:
42
+ # Try to parse multiple arguments
43
+ try:
44
+ # Try to evaluate the arguments as a tuple if there are commas
45
+ if ',' in arg_part:
46
+ # Multiple arguments - evaluate as tuple and unpack
47
+ args = eval(f"({arg_part})")
48
+ if isinstance(args, tuple):
49
+ tool_result = self.tools[tool_name](*args)
50
+ else:
51
+ tool_result = self.tools[tool_name](args)
52
+ else:
53
+ # Single argument
54
+ parsed_arg = eval(arg_part)
55
+ tool_result = self.tools[tool_name](parsed_arg)
56
+ except Exception as e:
57
+ print(f"Error parsing arguments: {e}")
58
+ # If eval fails completely, treat as single string argument
59
+ arg = arg_part.strip('"').strip("'")
60
+ tool_result = self.tools[tool_name](arg)
61
+
62
+ print(f"🔧 TOOL RESULT: {tool_result}")
63
+ tool_results.append(f"{tool_name}: {tool_result}")
64
+ else:
65
+ print(f"🔧 ERROR: Tool {tool_name} not found")
66
+ tool_results.append(f"Error: Tool {tool_name} not found")
67
+
68
+ return tool_results if tool_results else None
69
+
70
+ except Exception as e:
71
+ print(f"Error parsing tool: {e}")
72
+ return None
73
+
74
+ def get_tools_names_and_descriptions(self):
75
+ return {name: func.__doc__ for name, func in self.tools.items()}
76
+
77
+ def run(self, prompt: str):
78
+ system_prompt = f"""You are {self.name}. {self.instructions}
79
+
80
+ Available tools: {self.get_tools_names_and_descriptions()}
81
+
82
+ CRITICAL: To use a tool, respond with exactly this format:
83
+ ```tool
84
+ get_weather(Tokyo)
85
+ ```
86
+
87
+ You can use multiple tools:
88
+ ```tool
89
+ get_weather(Tokyo)
90
+ get_time()
91
+ ```
92
+
93
+ YOU MUST USE A BLOCK FOR TOOLS, or the system will not understand you are calling a tool.
94
+ CRITICAL:
95
+ ```tool
96
+ <tool_name>(<arg>)
97
+ ```
98
+ REMEMBER ALL TOOLS MUST BE INSIDE THE SAME BLOCK
99
+
100
+ IMPORTANT WORKFLOW:
101
+ 1. If you need live information, use the appropriate tool(s) first
102
+ 2. Once you have the information you need, provide your final response WITHOUT any tool calls
103
+ 3. Do NOT call the same tool repeatedly unless the user asks for updated information
104
+ 4. After calling a tool once and getting results, provide your answer to the user
105
+
106
+ user prompt: {prompt}
107
+ """
108
+ print(f"--- System Prompt ---\n{system_prompt}\n---------------------")
109
+
110
+ messages = [
111
+ {"role": "system", "content": system_prompt},
112
+ {"role": "user", "content": prompt}
113
+ ]
114
+
115
+ max_iterations = 99
116
+ iteration = 0
117
+ last_tool_calls = []
118
+
119
+ while iteration < max_iterations:
120
+ iteration += 1
121
+ print(f"\n--- Iteration {iteration} ---")
122
+
123
+ response = self.sophos.ask(str(messages))
124
+
125
+ current_response = response
126
+ print(f"AI Response: {current_response}")
127
+
128
+ tool_results = self.process_tool_calls(current_response)
129
+
130
+ if tool_results is None:
131
+ print("🏁 No tool calls detected - Agent finished!")
132
+ return current_response
133
+
134
+ all_results = "\n".join(tool_results)
135
+
136
+ # Check if we're repeating the same tool calls
137
+ current_tool_calls = [result.split(":")[0] for result in tool_results]
138
+ if current_tool_calls == last_tool_calls and iteration > 1:
139
+ print("⚠️ Detected repeated tool calls - forcing final response")
140
+ messages.append({"role": "assistant", "content": current_response})
141
+ messages.append({"role": "user", "content": f"Tool results:\n{all_results}\n\nYou have already called these tools. Now provide your final answer to the user without calling any more tools."})
142
+ else:
143
+ messages.append({"role": "assistant", "content": current_response})
144
+ messages.append({"role": "user", "content": f"Tool results:\n{all_results}\n\nNow provide your final response to the user. Do NOT call any more tools unless absolutely necessary."})
145
+
146
+ last_tool_calls = current_tool_calls
147
+
148
+ print(f"⚠️ Reached maximum iterations ({max_iterations})")
149
+ return current_response
agi/sophos_models.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from llama_cpp import Llama
2
+
3
+ class Sophos:
4
+ def __init__(self, model_path="agi/Qwen3-4B-Instruct-2507-Q3_K_S.gguf"):
5
+ self.model_path = model_path
6
+ self.model = Llama(model_path=model_path, n_ctx=2048, n_gpu_layers=35)
7
+
8
+ def ask(self, prompt):
9
+ """Ask Sophos a question and return the answer."""
10
+ messages = [
11
+ {"role": "user", "content": prompt}
12
+ ]
13
+
14
+ output = self.model.create_chat_completion(messages, max_tokens=1050, temperature=0.7)
15
+ return output["choices"][0]["message"]["content"]
16
+
17
+ if __name__ == "__main__":
18
+ sophos = Sophos()
19
+
20
+ while True:
21
+ prompt = input("\nEnter your prompt: ")
22
+ if prompt.lower() in ['exit', 'quit', 'q']:
23
+ break
24
+
25
+ response = sophos.ask(prompt)
26
+ print(response)
agi/sophos_tools.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datetime
2
+ import random
3
+ import string
4
+ import math
5
+ from typing import List, Dict
6
+ import os
7
+
8
+ def function_tool(func):
9
+ func._is_tool = True
10
+ return func
11
+
12
+ @function_tool
13
+ def get_weather(city: str) -> str:
14
+ '''fetches weather information for a given city.'''
15
+ now = datetime.datetime.now()
16
+ month = now.month
17
+
18
+ # Determine season and base temperature
19
+ if month in [12, 1, 2]: # Winter
20
+ season = "winter"
21
+ base_temp = 2
22
+ elif month in [3, 4, 5]: # Spring
23
+ season = "spring"
24
+ base_temp = 15
25
+ elif month in [6, 7, 8]: # Summer
26
+ season = "summer"
27
+ base_temp = 28
28
+ else: # Fall (9, 10, 11)
29
+ season = "fall"
30
+ base_temp = 12
31
+
32
+ # Add random variation of +/- 5 degrees
33
+ temp = base_temp + random.randint(-5, 5)
34
+
35
+ return f"The weather in {city} is sunny with {temp}°C during {season}"
36
+
37
+ @function_tool
38
+ def get_time() -> str:
39
+ '''fetches the current time.'''
40
+ return f"The current time is {datetime.datetime.now().strftime('%H:%M:%S')}"
41
+
42
+ @function_tool
43
+ def get_date() -> str:
44
+ '''fetches the current date.'''
45
+ return f"Today's date is {datetime.datetime.now().strftime('%Y-%m-%d')}"
46
+
47
+ @function_tool
48
+ def get_day() -> str:
49
+ '''fetches the current day of the week.'''
50
+ return f"Today is {datetime.datetime.now().strftime('%A')}"
51
+
52
+ @function_tool
53
+ def calculate(expression: str) -> str:
54
+ '''performs basic arithmetic calculations.'''
55
+ try:
56
+ # Safely evaluate the arithmetic expression
57
+ result = eval(expression, {"__builtins__": None}, {})
58
+ return f"The result of {expression} is {result}"
59
+ except Exception as e:
60
+ return f"Error in calculation: {str(e)}"
61
+
62
+ @function_tool
63
+ def generate_password(length: int = 12) -> str:
64
+ '''Generates a random password of specified length.'''
65
+ if length < 8:
66
+ return "Error: Password length must be at least 8 characters"
67
+
68
+ characters = string.ascii_letters + string.digits + string.punctuation
69
+ password = ''.join(random.choice(characters) for _ in range(length))
70
+ return f"Generated password: {password}"
71
+
72
+ @function_tool
73
+ def convert_temperature(value: float, from_unit: str, to_unit: str) -> str:
74
+ '''Converts temperature between Celsius, Fahrenheit, and Kelvin.'''
75
+ from_unit = from_unit.lower()
76
+ to_unit = to_unit.lower()
77
+
78
+ if from_unit == to_unit:
79
+ return f"{value}°{from_unit.upper()} is the same as {value}°{to_unit.upper()}"
80
+
81
+ try:
82
+ if from_unit == 'celsius':
83
+ if to_unit == 'fahrenheit':
84
+ result = (value * 9/5) + 32
85
+ return f"{value}°C is {result:.2f}°F"
86
+ elif to_unit == 'kelvin':
87
+ result = value + 273.15
88
+ return f"{value}°C is {result:.2f}K"
89
+ elif from_unit == 'fahrenheit':
90
+ if to_unit == 'celsius':
91
+ result = (value - 32) * 5/9
92
+ return f"{value}°F is {result:.2f}°C"
93
+ elif to_unit == 'kelvin':
94
+ result = (value - 32) * 5/9 + 273.15
95
+ return f"{value}°F is {result:.2f}K"
96
+ elif from_unit == 'kelvin':
97
+ if to_unit == 'celsius':
98
+ result = value - 273.15
99
+ return f"{value}K is {result:.2f}°C"
100
+ elif to_unit == 'fahrenheit':
101
+ result = (value - 273.15) * 9/5 + 32
102
+ return f"{value}K is {result:.2f}°F"
103
+ else:
104
+ return "Error: Invalid temperature units. Use 'celsius', 'fahrenheit', or 'kelvin'."
105
+ except Exception as e:
106
+ return f"Error in conversion: {str(e)}"
107
+
108
+ @function_tool
109
+ def roll_dice(sides: int, rolls: int = 1) -> str:
110
+ '''Rolls a dice with specified sides a given number of times.'''
111
+ if sides < 1 or rolls < 1:
112
+ return "Error: Sides and rolls must be positive integers"
113
+
114
+ results = [random.randint(1, sides) for _ in range(rolls)]
115
+ total = sum(results)
116
+ return f"Rolling {rolls} d{sides}: {results}, Total: {total}"
117
+
118
+ @function_tool
119
+ def word_count(text: str) -> str:
120
+ '''Counts the number of words in the given text.'''
121
+ if not text.strip():
122
+ return "Error: Empty text provided"
123
+
124
+ words = text.split()
125
+ return f"The text contains {len(words)} words"
126
+
127
+ @function_tool
128
+ def get_factorial(number: int) -> str:
129
+ '''Calculates the factorial of a given number.'''
130
+ if not isinstance(number, int):
131
+ return "Error: Input must be an integer"
132
+ if number < 0:
133
+ return "Error: Factorial is not defined for negative numbers"
134
+ try:
135
+ result = math.factorial(number)
136
+ return f"The factorial of {number} is {result}"
137
+ except Exception as e:
138
+ return f"Error in factorial calculation: {str(e)}"
139
+
140
+ @function_tool
141
+ def list_sort(numbers: List[float], ascending: bool = True) -> str:
142
+ '''Sorts a list of numbers in ascending or descending order.'''
143
+ try:
144
+ sorted_numbers = sorted(numbers, reverse=not ascending)
145
+ order = "ascending" if ascending else "descending"
146
+ return f"Sorted list in {order} order: {sorted_numbers}"
147
+ except Exception as e:
148
+ return f"Error in sorting: {str(e)}"
149
+
150
+ @function_tool
151
+ def generate_uuid() -> str:
152
+ '''Generates a random UUID.'''
153
+ return f"Generated UUID: {str(random.uuid4())}"
154
+
155
+ def all_tools():
156
+ """Returns a list of all functions decorated with @function_tool."""
157
+ tools = []
158
+ # Get all items in the current module's global namespace
159
+ current_module = globals()
160
+
161
+ for name, obj in current_module.items():
162
+ # Check if it's a function and has the _is_tool attribute
163
+ if callable(obj) and hasattr(obj, '_is_tool') and obj._is_tool:
164
+ tools.append(obj)
165
+
166
+ return tools
167
+
168
+ @function_tool
169
+ def save_file(file_path: str, content: str) -> str:
170
+ '''Saves content to a specified file path. use as save_file("filename.extension", "content") .for new lines use \\n'''
171
+ agent_sandbox_folder = "agi/sandbox/agent_sandbox/"
172
+ # make sure the folder exists
173
+ os.makedirs(agent_sandbox_folder, exist_ok=True)
174
+
175
+ try:
176
+ with open(agent_sandbox_folder + file_path, 'w') as file:
177
+ file.write(content)
178
+ return f"Content successfully saved to {agent_sandbox_folder + file_path}"
179
+ except Exception as e:
180
+ return f"Error saving file: {str(e)}"
main.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from agi.sophos import Agent
2
+ from agi.sophos_tools import *
3
+
4
+ toolbox = all_tools()
5
+
6
+ agent = Agent(
7
+ name="Sophos Agent",
8
+ instructions="You are an AI Agent.",
9
+ model="agi/Qwen3-4B-Instruct-2507-Q3_K_S.gguf",
10
+ tools=toolbox,
11
+ )
12
+
13
+ prompt = "Roll a dice, also whats the weather in Tokyo?"
14
+ response = agent.run(prompt)
15
+ print(response)