deconstructing-machine 0.0.1__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.
@@ -0,0 +1,164 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Python
3
+
4
+ """Copyright (c) Alexander Fedotov.
5
+ This source code is licensed under the license found in the
6
+ LICENSE file in the root directory of this source tree.
7
+ """
8
+ import urllib.request
9
+ import urllib.error
10
+ import json
11
+ from os import environ
12
+
13
+ api_key = environ.get("METAI_API_KEY", '')
14
+ default_model = environ.get("METAI_DEFAULT_MODEL", 'muse-spark-1.1')
15
+ api_base = environ.get("METAI_API_BASE", "https://api.meta.ai/v1")
16
+
17
+
18
+ # Set the mandatory headers
19
+ headers = {
20
+ "Content-Type": "application/json",
21
+ "Authorization": f"Bearer {api_key}",
22
+ "User-Agent": "Deconstructing-Machine"
23
+ }
24
+
25
+
26
+ def get_weather(location):
27
+ # print(f"Executing weather tool for location: {location}")
28
+ return {"temperature": "72F", "condition": "Sunny"}
29
+
30
+
31
+ def query(payload):
32
+ # Convert data dictionary to JSON and encode it to bytes
33
+ data_bytes = json.dumps(payload).encode('utf-8')
34
+ # Create the Request object
35
+ req = urllib.request.Request(
36
+ f'{api_base}/responses',
37
+ data=data_bytes,
38
+ headers=headers,
39
+ method="POST")
40
+ # Try to query
41
+ try:
42
+ # Execute the request
43
+ with urllib.request.urlopen(req, timeout=3000) as response:
44
+ response_data = response.read().decode('utf-8')
45
+ output = json.loads(response_data)
46
+ return output
47
+
48
+ except urllib.error.HTTPError as e:
49
+ # Handle HTTP errors (e.g., 401 Unauthorized, 400 Bad Request)
50
+ error_info = e.read().decode('utf-8', errors='ignore')
51
+ print(f"HTTP Error {e.code}: {e.reason}")
52
+ print(f"Error Details: {error_info}")
53
+ return {}
54
+
55
+ except urllib.error.URLError as e:
56
+ # Handle network/connection errors
57
+ print(f"Failed to reach the server: {e.reason}")
58
+ return {}
59
+
60
+
61
+ def decode_output(output):
62
+ # Parse the result
63
+ text = ''; thoughts = ''
64
+ for part in output:
65
+ part_type = part.get('type', None)
66
+ if part_type == 'message':
67
+ text = " ".join([chunk['text'] for chunk in part['content'] if chunk['type'] == 'output_text'])
68
+ elif part_type == 'reasoning':
69
+ thoughts = " ".join([chunk['text'] for chunk in part['summary'] if chunk['type'] == 'summary_text'])
70
+ function_calls = [part for part in output if part['type'] == 'function_call']
71
+ return thoughts, text, function_calls
72
+
73
+
74
+ def respond(messages=None, instructions=None, tools=None, **kwargs):
75
+ """ All parameters should be in kwargs, but they are optional
76
+ """
77
+ # Receive the instruction
78
+ instruction = kwargs.get('system_instruction', instructions)
79
+
80
+ # Define the initial payload
81
+ payload = {
82
+ "model": kwargs.get("model", default_model),
83
+ "instructions": instruction,
84
+ "input": messages,
85
+ "max_output_tokens": kwargs.get("max_tokens", 132000),
86
+ "prompt_cache_retention": "in_memory",
87
+ "include": ["reasoning.encrypted_content"],
88
+ "reasoning": {
89
+ "effort": "high",
90
+ "summary": "detailed"
91
+ }
92
+ }
93
+ # Tools if there are some
94
+ if tools:
95
+ payload['tools'] = tools
96
+ payload['tool_choice'] = 'auto'
97
+
98
+ while True:
99
+ # Query the API
100
+ result = query(payload)
101
+ # id of the response
102
+ response_id = result['id']
103
+ thoughts, text, function_calls = decode_output(result.get('output', {}))
104
+
105
+ if function_calls:
106
+ function_outputs_messages = []
107
+ for function_call in function_calls:
108
+ call_id = function_call.get('call_id')
109
+ func_name = function_call.get('name')
110
+ func_args_str = function_call.get('arguments', '{}')
111
+ try:
112
+ if isinstance(func_args_str, str):
113
+ func_args = json.loads(func_args_str)
114
+ else:
115
+ func_args = func_args_str
116
+ except Exception as e:
117
+ func_args = {}
118
+ print(f"Error parsing tool arguments for {func_name}: {e}")
119
+
120
+ # Look up tool by name in globals and caller frames
121
+ func = globals().get(func_name)
122
+ if not func:
123
+ import inspect
124
+ frame = inspect.currentframe().f_back
125
+ while frame:
126
+ if func_name in frame.f_globals:
127
+ func = frame.f_globals[func_name]
128
+ break
129
+ frame = frame.f_back
130
+
131
+ if func and callable(func):
132
+ try:
133
+ tool_result = func(**func_args)
134
+ if isinstance(tool_result, (dict, list)):
135
+ result = json.dumps(tool_result)
136
+ else:
137
+ result = str(tool_result)
138
+ except Exception as e:
139
+ result = f"Error executing tool {func_name}: {str(e)}"
140
+ print(result)
141
+ else:
142
+ result = f"Error: Tool function {func_name} not found."
143
+ print(result)
144
+
145
+ tool_message = {
146
+ "type": "function_call_output",
147
+ "call_id": call_id,
148
+ "output": result
149
+ }
150
+ function_outputs_messages.append(tool_message)
151
+
152
+ # Now that all responses have been gathered
153
+ # we can change the payload and send them back
154
+ payload['include'] = [] # must be removed if response_id
155
+ payload['previous_response_id'] = response_id
156
+ payload['input'] = function_outputs_messages
157
+ else:
158
+ break
159
+
160
+ return thoughts, text
161
+
162
+
163
+ if __name__ == "__main__":
164
+ ...
@@ -0,0 +1,82 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Python
3
+
4
+ """Copyright (c) Alexander Fedotov.
5
+ This source code is licensed under the license found in the
6
+ LICENSE file in the root directory of this source tree.
7
+ """
8
+ import urllib.request
9
+ import urllib.error
10
+ import json
11
+ from os import environ
12
+
13
+
14
+ def respond(messages=None, instructions=None, **kwargs):
15
+ """ All parameters should be in kwargs, but they are optional
16
+ """
17
+ api_key = environ.get("OPENAI_API_KEY", '')
18
+ default_model = environ.get("OPENAI_DEFAULT_MODEL", 'gpt-5.4')
19
+ api_base = environ.get("OPENAI_API_BASE", "https://api.openai.com/v1")
20
+
21
+ instruction = kwargs.get('system_instruction', instructions)
22
+
23
+ # Define the payload
24
+ payload = {
25
+ "model": kwargs.get("model", default_model),
26
+ "instructions": instruction,
27
+ "input": messages,
28
+ "max_output_tokens": kwargs.get("max_tokens", 64000),
29
+ "reasoning": {
30
+ "effort": "xhigh",
31
+ "summary": "detailed"
32
+ }
33
+ }
34
+
35
+ # Convert data dictionary to JSON and encode it to bytes
36
+ data_bytes = json.dumps(payload).encode('utf-8')
37
+
38
+ # Set the mandatory headers
39
+ headers = {
40
+ "Content-Type": "application/json",
41
+ "Authorization": f"Bearer {api_key}",
42
+ "User-Agent": "Deconstructing-Machine"
43
+ }
44
+
45
+ # Create the Request object
46
+ req = urllib.request.Request(
47
+ f'{api_base}/responses',
48
+ data=data_bytes,
49
+ headers=headers,
50
+ method="POST")
51
+
52
+ try:
53
+ # Execute the request
54
+ with urllib.request.urlopen(req, timeout=300) as response:
55
+ response_data = response.read().decode('utf-8')
56
+ output = json.loads(response_data)
57
+ text = ''
58
+ thoughts = ''
59
+ for part in output['output']:
60
+ if part['type'] == 'message':
61
+ for chunk in part['content']:
62
+ text += chunk['text']
63
+ elif part['type'] == 'reasoning':
64
+ for chunk in part['summary']:
65
+ thoughts += chunk['text']
66
+ return thoughts, text
67
+
68
+ except urllib.error.HTTPError as e:
69
+ # Handle HTTP errors (e.g., 401 Unauthorized, 400 Bad Request)
70
+ error_info = e.read().decode('utf-8', errors='ignore')
71
+ print(f"HTTP Error {e.code}: {e.reason}")
72
+ print(f"Error Details: {error_info}")
73
+ return '', ''
74
+
75
+ except urllib.error.URLError as e:
76
+ # Handle network/connection errors
77
+ print(f"Failed to reach the server: {e.reason}")
78
+ return '', ''
79
+
80
+
81
+ if __name__ == "__main__":
82
+ ...
@@ -0,0 +1,86 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Python
3
+
4
+ """Copyright (c) Alexander Fedotov.
5
+ This source code is licensed under the license found in the
6
+ LICENSE file in the root directory of this source tree.
7
+ """
8
+ import urllib.request
9
+ import urllib.error
10
+ import json
11
+ from os import environ
12
+
13
+
14
+ def respond(messages, instructions, **kwargs):
15
+ """
16
+ """
17
+ api_key = environ.get("OPENRO_API_KEY")
18
+ api_base = environ.get("OPENRO_API_BASE", "https://openrouter.ai/api/v1")
19
+ default_model = environ.get("OPENRO_DEFAULT_MODEL", "openai/gpt-6-luna")
20
+
21
+ instruction = kwargs.get('system_instruction', instructions)
22
+ first_message = [dict(role='system', content=instruction)] if instruction else []
23
+
24
+ # add contents and user text to the first (instruction) message
25
+ first_message.extend(messages)
26
+ instruction_and_contents = first_message
27
+
28
+ # Define the payload
29
+ payload = {
30
+ "model": kwargs.get("model", default_model),
31
+ "messages": instruction_and_contents,
32
+ "max_tokens": kwargs.get("max_tokens", 128000),
33
+ "temperature": kwargs.get("temperature", 1.0),
34
+ "reasoning_effort": kwargs.get("reasoning_effort", "high"),
35
+ "response_format": {
36
+ "type": "text"
37
+ },
38
+ "stream": False,
39
+ "reasoning": {
40
+ "enabled": True
41
+ }
42
+ }
43
+
44
+ # Convert data dictionary to JSON and encode it to bytes
45
+ data_bytes = json.dumps(payload).encode('utf-8')
46
+
47
+ # Set the mandatory headers
48
+ headers = {
49
+ "Content-Type": "application/json",
50
+ "Authorization": f"Bearer {api_key}",
51
+ "User-Agent": "Deconstructing-Machine"
52
+ }
53
+
54
+ # Create the Request object
55
+ req = urllib.request.Request(
56
+ f'{api_base}/chat/completions',
57
+ data=data_bytes,
58
+ headers=headers,
59
+ method="POST")
60
+
61
+ try:
62
+ # Execute the request
63
+ with urllib.request.urlopen(req, timeout=3000) as response:
64
+ response_data = response.read().decode('utf-8')
65
+ output = json.loads(response_data)
66
+ message = output['choices'][0]['message']
67
+ text = message.get('content', '')
68
+ thoughts = message.get('reasoning', '')
69
+
70
+ return thoughts, text
71
+
72
+ except urllib.error.HTTPError as e:
73
+ # Handle HTTP errors (e.g., 401 Unauthorized, 400 Bad Request)
74
+ error_info = e.read().decode('utf-8', errors='ignore')
75
+ print(f"HTTP Error {e.code}: {e.reason}")
76
+ print(f"Error Details: {error_info}")
77
+ return '', ''
78
+
79
+ except urllib.error.URLError as e:
80
+ # Handle network/connection errors
81
+ print(f"Failed to reach the server: {e.reason}")
82
+ return '', ''
83
+
84
+
85
+ if __name__ == '__main__':
86
+ ...
@@ -0,0 +1,82 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Python
3
+
4
+ """Copyright (c) Alexander Fedotov.
5
+ This source code is licensed under the license found in the
6
+ LICENSE file in the root directory of this source tree.
7
+ """
8
+ import urllib.request
9
+ import urllib.error
10
+ import json
11
+ from os import environ
12
+
13
+
14
+ def respond(messages=None, instructions=None, **kwargs):
15
+ """
16
+ Sends a request to the Groq Responses API using only Python's built-in urllib.
17
+ """
18
+ api_base = environ.get('GROQ_API_BASE', 'https://api.groq.com/openai/v1')
19
+ api_key = environ.get('GROQ_API_KEY', '')
20
+ default_model = environ.get('GROQ_DEFAULT_MODEL', 'openai/gpt-oss-120b')
21
+
22
+ instruction = kwargs.get('system_instruction', instructions)
23
+
24
+ # Define the payload
25
+ payload = {
26
+ "model": kwargs.get("model", default_model),
27
+ "instructions": instruction,
28
+ "input": messages,
29
+ "max_output_tokens": kwargs.get("max_tokens", 65536),
30
+ "reasoning": {
31
+ "effort": "high"
32
+ }
33
+ }
34
+
35
+ # Convert data dictionary to JSON and encode it to bytes
36
+ data_bytes = json.dumps(payload).encode('utf-8')
37
+
38
+ # Set the mandatory headers
39
+ headers = {
40
+ "Content-Type": "application/json",
41
+ "Authorization": f"Bearer {api_key}",
42
+ "User-Agent": "Deconstructing-Machine"
43
+ }
44
+
45
+ # Create the Request object
46
+ req = urllib.request.Request(
47
+ f'{api_base}/responses',
48
+ data=data_bytes,
49
+ headers=headers,
50
+ method="POST")
51
+
52
+ try:
53
+ # Execute the request
54
+ with urllib.request.urlopen(req, timeout=300) as response:
55
+ response_data = response.read().decode('utf-8')
56
+ output = json.loads(response_data)
57
+ text = ''
58
+ thoughts = ''
59
+ for part in output['output']:
60
+ if part['type'] == 'message':
61
+ for chunk in part['content']:
62
+ text += chunk['text']
63
+ elif part['type'] == 'reasoning':
64
+ for chunk in part['content']:
65
+ thoughts += chunk['text']
66
+ return thoughts, text
67
+
68
+ except urllib.error.HTTPError as e:
69
+ # Handle HTTP errors (e.g., 401 Unauthorized, 400 Bad Request)
70
+ error_info = e.read().decode('utf-8', errors='ignore')
71
+ print(f"HTTP Error {e.code}: {e.reason}")
72
+ print(f"Error Details: {error_info}")
73
+ return '', ''
74
+
75
+ except urllib.error.URLError as e:
76
+ # Handle network/connection errors
77
+ print(f"Failed to reach the server: {e.reason}")
78
+ return '', ''
79
+
80
+
81
+ if __name__ == "__main__":
82
+ ...
@@ -0,0 +1,81 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Python
3
+
4
+ """Copyright (c) Alexander Fedotov.
5
+ This source code is licensed under the license found in the
6
+ LICENSE file in the root directory of this source tree.
7
+ """
8
+ import urllib.request
9
+ import urllib.error
10
+ import json
11
+ from os import environ
12
+
13
+
14
+ def respond(messages, instructions, **kwargs):
15
+ """
16
+ """
17
+ api_key = environ.get("XAI_API_KEY")
18
+ api_base = environ.get("XAI_API_BASE", "https://api.x.ai/v1")
19
+ default_model = environ.get("XAI_DEFAULT_MODEL", "grok-4.20-reasoning")
20
+
21
+ instruction = kwargs.get('system_instruction', instructions)
22
+
23
+ # Define the payload
24
+ payload = {
25
+ "model": kwargs.get("model", default_model),
26
+ "instructions": instructions,
27
+ "input": messages,
28
+ "max_output_tokens": kwargs.get("max_tokens", 64000),
29
+ "reasoning": {
30
+ "summary": "detailed"
31
+ }
32
+ }
33
+
34
+ # Convert data dictionary to JSON and encode it to bytes
35
+ data_bytes = json.dumps(payload).encode('utf-8')
36
+
37
+ headers = {
38
+ "Content-Type": "application/json",
39
+ "Authorization": "Bearer " + api_key,
40
+ "User-Agent": "Deconstructing-Machine"
41
+ }
42
+
43
+ # Create the Request object
44
+ req = urllib.request.Request(
45
+ f'{api_base}/responses',
46
+ data=data_bytes,
47
+ headers=headers,
48
+ method="POST")
49
+
50
+ try:
51
+ # Execute the request
52
+ with urllib.request.urlopen(req, timeout=300) as response:
53
+ response_data = response.read().decode('utf-8')
54
+ output = json.loads(response_data)
55
+ text = ''
56
+ thoughts = ''
57
+ for part in output['output']:
58
+ if part['type'] == 'message':
59
+ for chunk in part['content']:
60
+ text += chunk['text']
61
+ elif part['type'] == 'reasoning_content':
62
+ for chunk in part['summary']:
63
+ thoughts += chunk['text']
64
+
65
+ return thoughts, text
66
+
67
+ except urllib.error.HTTPError as e:
68
+ # Handle HTTP errors (e.g., 401 Unauthorized, 400 Bad Request)
69
+ error_info = e.read().decode('utf-8', errors='ignore')
70
+ print(f"HTTP Error {e.code}: {e.reason}")
71
+ print(f"Error Details: {error_info}")
72
+ return '', ''
73
+
74
+ except urllib.error.URLError as e:
75
+ # Handle network/connection errors
76
+ print(f"Failed to reach the server: {e.reason}")
77
+ return '', ''
78
+
79
+
80
+ if __name__ == '__main__':
81
+ ...
@@ -0,0 +1,83 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Python
3
+
4
+ """Copyright (c) Alexander Fedotov.
5
+ This source code is licensed under the license found in the
6
+ LICENSE file in the root directory of this source tree.
7
+ """
8
+ import json
9
+ import urllib.request
10
+ import urllib.error
11
+ from os import environ
12
+
13
+
14
+ def respond(messages=None, instructions=None, tools=None, **kwargs):
15
+ """ They don't have responses, emulation through chat completions.
16
+ """
17
+ api_key = environ.get("TINKER_API_KEY", '')
18
+ default_model = environ.get("TINKER_DEFAULT_MODEL", 'thinkingmachines/Inkling')
19
+ api_base = environ.get("TINKER_OAI_API_BASE", 'https://tinker.thinkingmachines.dev/services/tinker-prod/oai/api/v1')
20
+
21
+ # Set the mandatory headers
22
+ headers = {
23
+ "Content-Type": "application/json",
24
+ "Authorization": f"Bearer {api_key}",
25
+ "User-Agent": "Deconstructing-Machine"
26
+ }
27
+
28
+ instruction = kwargs.get('system_instruction', instructions)
29
+ first_message = [dict(role='system', content=instruction)] if instruction else []
30
+
31
+ # contents can come in kwards or as an argument
32
+ messages = kwargs.get('messages', messages)
33
+
34
+ first_message.extend(messages)
35
+ instruction_and_contents = first_message
36
+
37
+ payload = {
38
+ 'model': kwargs.get('model', default_model),
39
+ 'messages': instruction_and_contents,
40
+ # 'response_format': kwargs.get('response_format',{'type': 'text'}),
41
+ 'temperature': kwargs.get('temperature', 1), # 0.0 to 2.0
42
+ 'max_tokens': kwargs.get('max_tokens', 4096),
43
+ 'n': kwargs.get('n', 1),
44
+ 'top_p': kwargs.get('top_p', 0.9),
45
+ 'separate_reasoning': True,
46
+ 'reasoning_effort': kwargs.get('reasoning_effort', 'high'), # 'low', 'medium', 'high'
47
+ 'stream': False
48
+ }
49
+
50
+ data_bytes = json.dumps(payload).encode('utf-8')
51
+ # Create the Request object
52
+ req = urllib.request.Request(
53
+ f'{api_base}/chat/completions',
54
+ data=data_bytes,
55
+ headers=headers,
56
+ method="POST")
57
+
58
+ # Try to query
59
+ try:
60
+ # Execute the request
61
+ with urllib.request.urlopen(req, timeout=3000) as response:
62
+ response_data = response.read().decode('utf-8')
63
+ output = json.loads(response_data)
64
+ completion_message = output['choices'][0]['message']
65
+ thoughts = completion_message.get('reasoning_content', '')
66
+ text = completion_message.get('content', '')
67
+ return thoughts, text
68
+
69
+ except urllib.error.HTTPError as e:
70
+ # Handle HTTP errors (e.g., 401 Unauthorized, 400 Bad Request)
71
+ error_info = e.read().decode('utf-8', errors='ignore')
72
+ print(f"HTTP Error {e.code}: {e.reason}")
73
+ print(f"Error Details: {error_info}")
74
+ return '',''
75
+
76
+ except urllib.error.URLError as e:
77
+ # Handle network/connection errors
78
+ print(f"Failed to reach the server: {e.reason}")
79
+ return '', ''
80
+
81
+
82
+ if __name__ == '__main__':
83
+ ...