machine-thinking 0.0.1__tar.gz → 0.0.2__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: machine-thinking
3
- Version: 0.0.1
3
+ Version: 0.0.2
4
4
  Summary: Package description
5
5
  Author-email: Machina Ratiocinatrix <machina.ratio@gmail.com>, Alexander Fedotov <alex.fedotov@aol.com>
6
6
  Project-URL: Homepage, https://github.com/machina-ratiocinatrix/machine-thinking
@@ -3,7 +3,7 @@ requires = ["setuptools>=67.0"]
3
3
  build-backend = "setuptools.build_meta"
4
4
  [project]
5
5
  name = "machine-thinking"
6
- version = "0.0.1"
6
+ version = "0.0.2"
7
7
  authors = [
8
8
  {name="Machina Ratiocinatrix", email="machina.ratio@gmail.com"},
9
9
  {name="Alexander Fedotov", email="alex.fedotov@aol.com"}
@@ -0,0 +1,88 @@
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
+ from .utils import (query,
9
+ default_model,
10
+ get_function,
11
+ get_func_args,
12
+ call_function)
13
+
14
+
15
+ def get_weather(location):
16
+ # print(f"Executing weather tool for location: {location}")
17
+ return {"temperature": "72F", "condition": "Sunny"}
18
+
19
+
20
+ def chat_complete(messages=None, instructions=None, tools=None, **kwargs):
21
+ """A continuation of text with a given context and instruction.
22
+ kwargs:
23
+ temperature = 0 to 1.0
24
+ top_p = 0.0 to 1.0
25
+ top_k = The maximum number of tokens to consider when sampling.
26
+ n = 1 is mandatory for this method continuationS have n > 1
27
+ max_tokens = number of tokens
28
+ stop = ['stop'] array of up to 4 sequences
29
+ """
30
+ instruction = kwargs.get('system_instruction', instructions)
31
+ first_message = [dict(role='system', content=instruction)] if instruction else []
32
+
33
+ # contents can come in kwards or as an argument
34
+ messages = kwargs.get('messages', messages)
35
+
36
+ first_message.extend(messages)
37
+ instruction_and_contents = first_message
38
+
39
+ payload = {
40
+ 'model': kwargs.get('model', default_model),
41
+ 'messages': instruction_and_contents,
42
+ # 'response_format': kwargs.get('response_format',{'type': 'text'}),
43
+ 'temperature': kwargs.get('temperature', 1), # 0.0 to 2.0
44
+ 'max_tokens': kwargs.get('max_tokens', 4096),
45
+ 'n': kwargs.get('n', 1),
46
+ 'top_p': kwargs.get('top_p', 0.9),
47
+ 'reasoning_effort': kwargs.get('reasoning_effort', 'high'), # 'low', 'medium', 'high'
48
+ 'stream': False
49
+ }
50
+ if tools:
51
+ payload['tools'] = tools
52
+ payload['parallel_tool_calls'] = True
53
+ payload['tool_choice'] = 'auto'
54
+
55
+ while True:
56
+ result = query(payload, '/chat/completions')
57
+ completion_message = result['choices'][0]['message']
58
+ instruction_and_contents.append(completion_message)
59
+ thoughts = completion_message.get('reasoning_content', '')
60
+ text = completion_message.get('content', '')
61
+ function_calls = completion_message.get('tool_calls', [])
62
+
63
+ if function_calls:
64
+ # Call all requested functions and create response messages.
65
+ for function_call in function_calls:
66
+ call_id = function_call.get('id')
67
+ func_def = function_call.get('function')
68
+ func_name = func_def.get('name', '')
69
+
70
+ # Look up tool by name in globals and caller frames
71
+ func = get_function(func_name)
72
+ func_args = get_func_args(func_def)
73
+ result = call_function(func, func_args)
74
+
75
+ tool_message = {
76
+ "role": "tool",
77
+ "tool_call_id": call_id,
78
+ "content": result
79
+ }
80
+ instruction_and_contents.append(tool_message)
81
+ else:
82
+ break
83
+
84
+ return thoughts, text
85
+
86
+
87
+ if __name__ == '__main__':
88
+ ...
@@ -0,0 +1,102 @@
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
+ api_key = environ.get("TINKER_API_KEY", '')
15
+ default_model = environ.get("TINKER_DEFAULT_MODEL", 'thinkingmachines/Inkling')
16
+ api_base = environ.get("TINKER_API_BASE", 'https://tinker.thinkingmachines.dev/services/tinker-prod/oai/api/v1')
17
+
18
+
19
+ # Set the mandatory headers
20
+ headers = {
21
+ "Content-Type": "application/json",
22
+ "Authorization": f"Bearer {api_key}",
23
+ "User-Agent": "machine-thinking"
24
+ }
25
+
26
+
27
+ def get_function(func_name):
28
+ # Look up tool by name in globals
29
+ func = globals().get(func_name)
30
+ # Look up in the caller frames
31
+ if not func:
32
+ import inspect
33
+ frame = inspect.currentframe().f_back
34
+ while frame:
35
+ if func_name in frame.f_globals:
36
+ func = frame.f_globals[func_name]
37
+ break
38
+ frame = frame.f_back
39
+
40
+ return func
41
+
42
+
43
+ def get_func_args(func_def):
44
+ try:
45
+ func_args_str = func_def.get('arguments')
46
+ if isinstance(func_args_str, str):
47
+ func_args = json.loads(func_args_str)
48
+ else:
49
+ func_args = func_args_str
50
+ except Exception as e:
51
+ func_args = {}
52
+ print(f"Error parsing tool arguments: {e}")
53
+
54
+ return func_args
55
+
56
+
57
+ def call_function(func, func_args):
58
+ if func and callable(func):
59
+ try:
60
+ tool_result = func(**func_args)
61
+ if isinstance(tool_result, (dict, list)):
62
+ result = json.dumps(tool_result)
63
+ else:
64
+ result = str(tool_result)
65
+ except Exception as e:
66
+ result = f"Error executing tool: {str(e)}"
67
+ print(result)
68
+ else:
69
+ result = f"Error: Tool function not callable."
70
+ print(result)
71
+
72
+ return result
73
+
74
+
75
+ def query(payload, url_suffix):
76
+ # Convert data dictionary to JSON and encode it to bytes
77
+ data_bytes = json.dumps(payload).encode('utf-8')
78
+ # Create the Request object
79
+ req = urllib.request.Request(
80
+ f'{api_base}{url_suffix}',
81
+ data=data_bytes,
82
+ headers=headers,
83
+ method="POST")
84
+ # Try to query
85
+ try:
86
+ # Execute the request
87
+ with urllib.request.urlopen(req, timeout=3000) as response:
88
+ response_data = response.read().decode('utf-8')
89
+ output = json.loads(response_data)
90
+ return output
91
+
92
+ except urllib.error.HTTPError as e:
93
+ # Handle HTTP errors (e.g., 401 Unauthorized, 400 Bad Request)
94
+ error_info = e.read().decode('utf-8', errors='ignore')
95
+ print(f"HTTP Error {e.code}: {e.reason}")
96
+ print(f"Error Details: {error_info}")
97
+ return {}
98
+
99
+ except urllib.error.URLError as e:
100
+ # Handle network/connection errors
101
+ print(f"Failed to reach the server: {e.reason}")
102
+ return {}
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: machine-thinking
3
- Version: 0.0.1
3
+ Version: 0.0.2
4
4
  Summary: Package description
5
5
  Author-email: Machina Ratiocinatrix <machina.ratio@gmail.com>, Alexander Fedotov <alex.fedotov@aol.com>
6
6
  Project-URL: Homepage, https://github.com/machina-ratiocinatrix/machine-thinking
@@ -2,8 +2,10 @@ LICENSE
2
2
  README.md
3
3
  pyproject.toml
4
4
  src/machine_thinking/__init__.py
5
+ src/machine_thinking/chat.py
5
6
  src/machine_thinking/cli.py
6
7
  src/machine_thinking/main.py
8
+ src/machine_thinking/utils.py
7
9
  src/machine_thinking.egg-info/PKG-INFO
8
10
  src/machine_thinking.egg-info/SOURCES.txt
9
11
  src/machine_thinking.egg-info/dependency_links.txt