gnarly 0.0.0.dev5__py3-none-any.whl → 0.0.0.dev7__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.

Potentially problematic release.


This version of gnarly might be problematic. Click here for more details.

gnarly/types.py ADDED
@@ -0,0 +1,102 @@
1
+ """
2
+ Types
3
+ =====
4
+
5
+ Gnarly's custom typing framework. This is an implementation detail.
6
+
7
+ """
8
+
9
+ import logging
10
+ from abc import ABC
11
+ from dataclasses import dataclass
12
+ from enum import Flag, auto
13
+ from os import PathLike
14
+
15
+ from gnarly.errors import NamespaceError
16
+
17
+
18
+ logger: logging.Logger = logging.getLogger()
19
+ logger.setLevel(logging.INFO)
20
+
21
+
22
+ class GnarlyProjectType(Flag):
23
+ """
24
+ An enumeration of the languages that Gnarly currenetly supports
25
+
26
+ Reference members of this class directly whenever you want to specify
27
+ a language constraint. Avoid hard-coding comparisons to their `values`,
28
+ since their integer data types are semantically insignificant.
29
+ """
30
+ CPP: int = auto()
31
+ HASKELL: int = auto()
32
+ JAVASCRIPT: int = auto()
33
+ PYTHON: int = auto()
34
+ R: int = auto()
35
+ RUST: int = auto()
36
+ SWIFT: int = auto()
37
+
38
+
39
+ # ─── Interfaces ────────────────────────────────────────────────────────── ✦ ─
40
+ @dataclass
41
+ class GnarlyProject:
42
+ name: str
43
+ project_type: GnarlyProjectType
44
+ is_persistent: bool
45
+ root_path: PathLike
46
+ dependencies: dict[str, list]
47
+
48
+
49
+ @dataclass
50
+ class GnarlyPythonProject(GnarlyProject):
51
+ project_type = GnarlyProjectType.PYTHON
52
+
53
+
54
+ @dataclass
55
+ class GnarlyCppProject(GnarlyProject):
56
+ project_Type = GnarlyProjectType.CPP
57
+
58
+
59
+ @dataclass
60
+ class GnarlyHaskellProject(GnarlyProject):
61
+ project_type = GnarlyProjectType.HASKELL
62
+
63
+
64
+ @dataclass
65
+ class GnarlyJavaScriptProject(GnarlyProject):
66
+ project_type = GnarlyProjectType.JAVASCRIPT
67
+
68
+
69
+ @dataclass
70
+ class GnarlyRProject(GnarlyProject):
71
+ project_type = GnarlyProjectType.R
72
+
73
+
74
+ @dataclass
75
+ class GnarlyRustProject(GnarlyProject):
76
+ project_type = GnarlyProjectType.RUST
77
+
78
+
79
+ @dataclass
80
+ class GnarlySwiftProject(GnarlyProject):
81
+ project_type = GnarlyProjectType.SWIFT
82
+
83
+
84
+ class GnarlyNamespace(ABC):
85
+ """
86
+ Base class for non-instantiable types that serve to encapsulate.
87
+
88
+ Subclasses of this ABC provide no constructors. Instead, attempts
89
+ to instantiate raise `NamespaceError`.
90
+ """
91
+ context_key: str
92
+
93
+ def __new__(cls) -> NamespaceError:
94
+ logger.error("`Project` is not intended for direct instantiation.")
95
+ raise NamespaceError(
96
+ f"`{cls.__name__}` is a namespace, which means that it "
97
+ "has no constructors. Instead, you should call one of the "
98
+ "static factory methods provided in one of its inner classes, "
99
+ "all of which return instances of the `GnarlyProject` base "
100
+ "class's concrete implementations."
101
+ )
102
+
@@ -6,116 +6,125 @@ This module defines and implements various facilities useful for
6
6
  project management.
7
7
 
8
8
  """
9
- from dataclasses import dataclass
10
- from enum import Enum, auto
11
9
  import logging
12
10
  from os import PathLike
13
11
 
14
12
  from ...constants import GNARLY_PROJECT_ROOT_PATH
15
- from ...errors import NamespaceError
13
+ # from ...errors import NamespaceError
14
+ from ...types import (
15
+ GnarlyCppProject,
16
+ GnarlyHaskellProject,
17
+ GnarlyJavaScriptProject,
18
+ GnarlyNamespace,
19
+ GnarlyProject,
20
+ GnarlyProjectType,
21
+ GnarlyPythonProject,
22
+ GnarlyRProject,
23
+ GnarlyRustProject,
24
+ GnarlySwiftProject
25
+ )
16
26
 
17
27
  logger: logging.Logger = logging.getLogger()
18
28
  logging.basicConfig(level=logging.DEBUG, format=logging.BASIC_FORMAT)
19
29
 
20
- class GnarlyProjectType(Enum):
21
- """
22
- An enumeration of currently supported languages.
23
-
24
- Reference members of this class directly whenever you want to specify
25
- a language constraint. Avoid hard-coding comparisons to their `values`,
26
- since their integer data types are semantically insignificant.
27
- """
28
- CPP: int = auto()
29
- HASKELL: int = auto()
30
- JAVASCRIPT: int = auto()
31
- PYTHON: int = auto()
32
- R: int = auto()
33
- RUST: int = auto()
34
- SWIFT: int = auto()
35
-
36
30
 
37
- class Project:
31
+ class Project(GnarlyNamespace):
38
32
  """
39
33
  A namespace for Gnarly Code's project management utility suite.
40
34
 
41
35
  This is a Gnarly implementation detail. It is not intended for direct
42
36
  instantiation. Attempts to instantiate this class will raise a
43
- `NamespaceError`.
37
+ ``NamespaceError``.
44
38
  """
45
- def __new__(cls) -> None:
46
- logger.error("`Project` is not intended for direct instantiation.")
47
- raise NamespaceError(
48
- f"Canot instantiate namespace class {cls.__name__}"
49
- )
50
39
 
51
- # ─── Utility Groups ──────────────────────────────────────────────────────
40
+
52
41
  class Python:
53
42
  """
54
43
  A namespace for Gnarly's Python project management utilities.
55
44
 
56
- Use the static functions defined in the `Project.Python` namespace to
57
- manage your Python project's code base.
45
+ Use the static functions defined in the ``Project.Python`` namespace
46
+ to manage your Python project's code base.
58
47
 
59
48
  Examples
60
49
  --------
61
50
  Basic usage:
62
51
 
63
- >>> from gnarly.utils.code import Project
64
- >>> p = Project.Python # Alias for convenience.
65
- >>> p.create("my_project")
66
- GnarlyPythonProject(
67
- name="my_project",
68
- project_type=GnarlyProjectType.PYTHON,
69
- logger=None,
70
- is_persistent=True,
71
- root_path=Path(
72
- "/users/gnarly-user/gnarly/projects/python/my_project/"
73
- ),
74
- dependencies={"dev": [], "optional": [], "required": []}
75
- )
76
-
77
- With custom options:
78
-
79
- >>> from gnarly.utils.code import Project
80
- >>> p = Project.Python
81
- >>> p.create(
82
- ... name="My Project",
83
- ... project_type=
84
- ... )
85
- GnarlyPythonProject(
86
- name="my_project",
87
- project_type=GnarlyProjectType.PYTHON,
88
- logger=None,
89
- is_persistent=True,
90
- root_path=Path(
91
- "/users/gnarly-user/gnarly/projects/python/my_project/"
92
- ),
93
- dependencies={"dev": [], "optional": [], "required": []}
94
- )
52
+ >>> from pprint import pprint
53
+ >>> from gnarly import Project
54
+ >>>
55
+ >>> mgr = Project.Python()
56
+ >>>
57
+ >>> pr: GnarlyPythonProject = mgr.create("my_python_project")
58
+ >>> pprint(pr)
59
+ GnarlyPythonProject(name='my_python_project',
60
+ project_type=<GnarlyProjectType.PYTHON: 8>,
61
+ logger=<RootLogger root (INFO)>,
62
+ is_persistent=True,
63
+ root_path=PosixPath('/Users/u/gnarly/gnarly_project'),
64
+ dependencies={'dev': [], 'optional': [], 'required': []})
65
+
95
66
  """
67
+ def __init__(
68
+ self,
69
+ context_key: str = "python_project_namespace"
70
+ ) -> None:
71
+ self._context_key = context_key
72
+
73
+
74
+ @property
75
+ def context_key(self) -> str:
76
+ return self._context_key
77
+
78
+ @context_key.setter
79
+ def context_key(self, value: str) -> None:
80
+ self._context_key = value
81
+
82
+ @context_key.deleter
83
+ def context_key(self) -> None:
84
+ del self._context_key
85
+
86
+
87
+ @staticmethod
96
88
  def create(
97
- cls,
98
- logger: logging.Logger = logging.getLogger(__name__),
99
- name: str = __package__,
89
+ name: str = "gnarly_python_project",
100
90
  project_type = GnarlyProjectType.PYTHON,
101
91
  is_persistent: bool = True,
102
- root_path: PathLike = GNARLY_PROJECT_ROOT_PATH / f"{__package__}/",
103
- dependencies: dict[str, list] = {
92
+ root_path: PathLike = GNARLY_PROJECT_ROOT_PATH / "gnarly_project",
93
+ dependencies: dict[str, list[str]] = {
104
94
  "dev": [],
105
95
  "optional": [],
106
96
  "required": []
107
97
  }
108
98
  ) -> "GnarlyPythonProject":
99
+ """
100
+ Create a Python project.
101
+
102
+ Rather than instantiating ``GnarlyPythonProject`` directly, you
103
+ call this static method on your ``Project.Python`` manager.
104
+
105
+ Parameters
106
+ ----------
107
+ name : str
108
+ The Python project's name.
109
+ project_type : GnarlyProjectType
110
+ The project's type, as characterized by its target
111
+ language configuration.
112
+ is_persistent : bool
113
+ The project's persistence state. Defaults to ``True``.
114
+ root_path : PathLike
115
+ The project's root path.
116
+ dependencies : dict[str, list[str]]
117
+ A dictionary that represents the project's dependencies.
118
+
119
+ Returns
120
+ -------
121
+ A new instance of ``GnarlyPythonProject``.
122
+
123
+ """
124
+
109
125
  return Project.create(
110
- name=__package__,
111
- project_type=GnarlyProjectType.PYTHON,
112
- logger=(
113
- logging.getLogger(__class__)
114
- .basicConfig(
115
- level=logging.ERROR,
116
- format=logging.BASIC_FORMAT
117
- )
118
- ),
126
+ name=name,
127
+ project_type=project_type,
119
128
  is_persistent=is_persistent,
120
129
  root_path=root_path,
121
130
  dependencies=dependencies
@@ -126,7 +135,6 @@ class Project:
126
135
  def create(
127
136
  name: str,
128
137
  project_type: GnarlyProjectType,
129
- logger: logging.Logger = logger,
130
138
  is_persistent: bool = True,
131
139
  root_path: PathLike = GNARLY_PROJECT_ROOT_PATH,
132
140
  dependencies: dict[str, list] = {
@@ -136,70 +144,61 @@ class Project:
136
144
  }
137
145
  ) -> "GnarlyProject":
138
146
  match project_type:
147
+ case project_type.CPP:
148
+ return GnarlyCppProject(
149
+ name=name,
150
+ project_type=project_type,
151
+ is_persistent=is_persistent,
152
+ root_path=root_path,
153
+ dependencies=dependencies
154
+ )
139
155
  case project_type.HASKELL:
140
156
  return GnarlyHaskellProject(
141
157
  name=name,
142
158
  project_type=project_type,
143
- logger=logger,
159
+ is_persistent=is_persistent,
160
+ root_path=root_path,
161
+ dependencies=dependencies
162
+ )
163
+ case project_type.JAVASCRIPT:
164
+ return GnarlyJavaScriptProject(
165
+ name=name,
166
+ project_type=project_type,
144
167
  is_persistent=is_persistent,
145
168
  root_path=root_path,
146
169
  dependencies=dependencies
147
170
  )
148
171
  case project_type.PYTHON:
149
- return GnarlyPythonProject
172
+ return GnarlyPythonProject(
173
+ name=name,
174
+ project_type=project_type,
175
+ is_persistent=is_persistent,
176
+ root_path=root_path,
177
+ dependencies=dependencies
178
+ )
150
179
  case project_type.R:
151
- return GnarlyRProject
180
+ return GnarlyRProject(
181
+ name=name,
182
+ project_type=project_type,
183
+ is_persistent=is_persistent,
184
+ root_path=root_path,
185
+ dependencies=dependencies
186
+ )
152
187
  case project_type.RUST:
153
- return GnarlyRustProject
188
+ return GnarlyRustProject(
189
+ name=name,
190
+ project_type=project_type,
191
+ is_persistent=is_persistent,
192
+ root_path=root_path,
193
+ dependencies=dependencies
194
+ )
154
195
  case project_type.SWIFT:
155
- return GnarlySwiftProject
156
-
157
-
158
- @dataclass
159
- class GnarlyProject:
160
- name: str
161
- project_type: GnarlyProjectType
162
- logger: logging.Logger
163
- is_persistent: bool
164
- root_path: PathLike
165
- dependencies: dict[str, list]
166
-
167
-
168
- @dataclass
169
- class GnarlyPythonProject(GnarlyProject):
170
- project_type = GnarlyProjectType.PYTHON
171
-
172
-
173
- @dataclass
174
- class GnarlyCppProject(GnarlyProject):
175
- project_Type = GnarlyProjectType.CPP
176
-
177
-
178
- @dataclass
179
- class GnarlyHaskellProject(GnarlyProject):
180
- project_type = GnarlyProjectType.HASKELL
181
- pass
182
-
183
-
184
- @dataclass
185
- class GnarlyJavaScriptProject(GnarlyProject):
186
- project_type = GnarlyProjectType.JAVASCRIPT
187
- pass
188
-
189
-
190
- @dataclass
191
- class GnarlyRProject(GnarlyProject):
192
- project_type = GnarlyProjectType.R
193
-
194
-
195
- @dataclass
196
- class GnarlyRustProject(GnarlyProject):
197
- project_type = GnarlyProjectType.RUST
198
- pass
199
-
196
+ return GnarlySwiftProject(
197
+ name=name,
198
+ project_type=project_type,
199
+ is_persistent=is_persistent,
200
+ root_path=root_path,
201
+ dependencies=dependencies
202
+ )
200
203
 
201
- @dataclass
202
- class GnarlySwiftProject(GnarlyProject):
203
- project_type = GnarlyProjectType.SWIFT
204
- pass
205
204
 
gnarly/utils/io.py CHANGED
@@ -56,19 +56,41 @@ def stream(
56
56
  -------
57
57
  Nothing.
58
58
  """
59
+ # Input validation
60
+ if not isinstance(s, str):
61
+ raise TypeError("Input 's' must be a string")
62
+
63
+ if not isinstance(cps, int) or cps <= 0:
64
+ raise ValueError("cps must be a positive integer")
65
+
66
+ if charlim is not None and (not isinstance(charlim, int) or charlim <= 0):
67
+ raise ValueError("charlim must be a positive integer or None")
68
+
69
+ # Handle empty string
70
+ if not s:
71
+ return None
72
+
73
+ # Get terminal width with silent fallback
59
74
  try:
60
75
  term_width: int = os.get_terminal_size().columns
61
- charlim: int = charlim or term_width - 12
62
- except OSError as e:
63
- logger.error(f"Failed to get terminal width: {e}")
64
- charlim: int = charlim or 40
76
+ charlim: int = charlim or max(20, term_width - 12) # Ensure minimum width
77
+ except (OSError, AttributeError):
78
+ # Log to file only (DEBUG level), not console
79
+ logger.debug("Failed to get terminal width, using default charlim")
80
+ charlim: int = charlim or 80 # Standard terminal width fallback
81
+
82
+ # Ensure charlim is reasonable
83
+ if charlim < 10:
84
+ charlim = 10
85
+ elif charlim > 200:
86
+ charlim = 200
65
87
 
66
88
  lines = s.splitlines()
67
89
  wsp = string.whitespace
68
- counter: int = 0
69
-
90
+ break_chars = ["-", "–", "—", "─"] # Extended dash characters
91
+
70
92
  try:
71
- delay: int | float = 1 / cps
93
+ delay: float = 1.0 / cps
72
94
  except ZeroDivisionError as e:
73
95
  logger.error(
74
96
  "User attempted to specify a value of zero characters per second, "
@@ -76,50 +98,79 @@ def stream(
76
98
  "utilities.io.stream` calculates the system sleep duration as the "
77
99
  "reciprocal of `cps`."
78
100
  )
79
- raise UserWarning from e
101
+ raise ValueError("cps cannot be zero") from e
80
102
 
81
- if not charlim:
103
+ # Handle case where charlim is not set or is very large
104
+ if not charlim or charlim >= max(len(line) for line in lines) if lines else True:
82
105
  for line in lines:
83
106
  for c in line:
84
107
  print(c, end="", flush=True)
85
108
  sleep(delay)
86
- print("\n", end="", flush=True)
87
- else:
88
- for line in lines:
89
- chars = enumerate(line)
90
- for i, c in chars:
91
- if (i % charlim != 0) or i == 0:
92
- print(c, end="", flush=True)
93
- sleep(delay)
94
- elif (i % charlim) == 0 and (str(c) in wsp or str(c) in ["-", "–", "─"]):
109
+ print() # Simplified newline
110
+ return None
111
+
112
+ # Process with character limit
113
+ for line in lines:
114
+ if not line: # Handle empty lines
115
+ print()
116
+ continue
117
+
118
+ chars = list(enumerate(line)) # Convert to list to avoid iterator issues
119
+ i = 0
120
+
121
+ while i < len(chars):
122
+ char_index, c = chars[i]
123
+
124
+ # Normal character printing (not at line limit)
125
+ if (char_index % charlim != 0) or char_index == 0:
126
+ print(c, end="", flush=True)
127
+ sleep(delay)
128
+ i += 1
129
+
130
+ # At character limit - check for good break point
131
+ elif char_index % charlim == 0:
132
+ # If current character is a good break point
133
+ if c in wsp or c in break_chars:
95
134
  print(c + "\n", end="", flush=True)
96
135
  sleep(delay)
97
- elif (i % charlim == 0) and (str(c) not in wsp):
98
- print(c, end="", flush=True)
99
- try:
100
- while True:
101
- _, next_c = next(chars)
102
- if str(next_c) in wsp or str(next_c) in ["-", "–", "─"]:
103
- print(next_c + "\n", end="", flush=True)
104
- break
105
- else:
106
- print(next_c, end="", flush=True)
107
- except StopIteration:
108
- logger.info(
109
- f"Reached end of line after {counter} iterations."
110
- )
111
- break
112
-
136
+ i += 1
137
+
138
+ # Look ahead for a good break point
113
139
  else:
114
- logger.warning(
115
- f"Unexpected conditions encountered:\n"
116
- f"Iterating over: {str(chars)}\n"
117
- f"Current index: {i} \n"
118
- f"Character at current index: {c}\n"
119
- f"Character limit: {charlim}\n"
120
-
121
- f"\n{i} % {charlim} = {i % charlim}"
122
- )
123
- counter +=1
124
- print()
140
+ print(c, end="", flush=True)
141
+ sleep(delay)
142
+ i += 1
143
+
144
+ # Look for next whitespace or break character
145
+ lookahead_limit = min(20, len(chars) - i) # Don't look too far ahead
146
+ found_break = False
147
+
148
+ for j in range(lookahead_limit):
149
+ if i + j >= len(chars):
150
+ break
151
+
152
+ _, next_c = chars[i + j]
153
+ print(next_c, end="", flush=True)
154
+ sleep(delay)
155
+
156
+ if next_c in wsp or next_c in break_chars:
157
+ print("\n", end="", flush=True)
158
+ found_break = True
159
+ i += j + 1
160
+ break
161
+
162
+ # If no break found within lookahead, force break
163
+ if not found_break:
164
+ print("\n", end="", flush=True)
165
+ i += lookahead_limit
166
+
167
+ else:
168
+ # This shouldn't happen, but handle it gracefully
169
+ logger.debug(f"Unexpected condition at index {char_index}, character '{c}'")
170
+ print(c, end="", flush=True)
171
+ sleep(delay)
172
+ i += 1
173
+
174
+ print() # End of line
125
175
 
176
+ return None
@@ -2,7 +2,6 @@
2
2
 
3
3
  Entry point for the ChatGPT REPL.
4
4
  """
5
- import json
6
5
  from datetime import datetime as dt
7
6
  from pathlib import Path
8
7
 
@@ -3,7 +3,6 @@
3
3
  Entry point for the Claude REPL.
4
4
  """
5
5
  import logging
6
- import json
7
6
  from datetime import datetime as dt
8
7
  from pathlib import Path
9
8
 
@@ -8,6 +8,8 @@ Classes for interfacing with LLMs as defined in the `models` module.
8
8
  import json
9
9
  import logging
10
10
  import os
11
+ import urllib.request
12
+ import urllib.parse
11
13
  from datetime import datetime as dt
12
14
  from pathlib import Path
13
15
  from typing import Dict, List, Tuple, TYPE_CHECKING, Union
@@ -15,10 +17,7 @@ if TYPE_CHECKING:
15
17
  from _typeshed import SupportsWrite
16
18
 
17
19
  # third-party imports
18
- from anthropic import Anthropic
19
- from anthropic.types import Message
20
20
  from dotenv import load_dotenv
21
- from openai import OpenAI
22
21
  from platformdirs import user_config_path
23
22
 
24
23
  # local imports
@@ -32,7 +31,7 @@ logger = logging.getLogger(__name__)
32
31
  logging.basicConfig(level=logging.INFO)
33
32
 
34
33
  # ─── constants ─────────────────────────────────────────────────────────── ✦ ─
35
- APP_NAME = "cleft"
34
+ APP_NAME = "gnarly"
36
35
  APP_AUTHOR = "k.lebryce"
37
36
  APP_CONFIG_DIR: Path = user_config_path(
38
37
  APP_NAME, APP_AUTHOR, ensure_exists=True
@@ -57,7 +56,10 @@ class Claude(ClaudeModel):
57
56
  system_prompt: str = "You are Claude, a friendly AI assistant."
58
57
  ):
59
58
  super().__init__()
60
- self.client: Anthropic = Anthropic()
59
+ self.api_key: str = self.api_key or os.getenv("ANTHROPIC_API_KEY")
60
+ if not self.api_key:
61
+ raise ValueError("ANTHROPIC_API_KEY environment variable is required")
62
+
61
63
  self.conversation: List[Dict] = []
62
64
  self.max_tokens: int = 4096
63
65
  self.system_prompt = system_prompt
@@ -70,23 +72,51 @@ class Claude(ClaudeModel):
70
72
  self.save_to.parent.mkdir(parents=True, exist_ok=True)
71
73
  logger.info(f"Conversation will be saved to {self.save_to}")
72
74
 
73
- def message(self, msg: str) -> Tuple[Dict, Message]:
75
+ def message(self, msg: str) -> Tuple[Dict, Dict]:
74
76
  """
75
77
  Creates a payload using the `msg` string and returns Claude's
76
78
  response as a string.
77
79
  """
78
80
  self.conversation.append({"role": "user", "content": msg})
79
81
 
80
- # Call the Anthropic API.
81
- result = self.client.messages.create(
82
- model=self.model,
83
- max_tokens=self.max_tokens,
84
- system=self.system_prompt,
85
- temperature=self.temperature,
86
- messages=self.conversation
82
+ # Prepare the API request
83
+ url = "https://api.anthropic.com/v1/messages"
84
+
85
+ data = {
86
+ "model": self.model,
87
+ "max_tokens": self.max_tokens,
88
+ "system": self.system_prompt,
89
+ "temperature": self.temperature,
90
+ "messages": self.conversation
91
+ }
92
+
93
+ headers = {
94
+ "x-api-key": self.api_key,
95
+ "Content-Type": "application/json",
96
+ "anthropic-version": "2023-06-01"
97
+ }
98
+
99
+ # Make the HTTP request
100
+ req = urllib.request.Request(
101
+ url,
102
+ data=json.dumps(data).encode("utf-8"),
103
+ headers=headers
87
104
  )
105
+
106
+ try:
107
+ with urllib.request.urlopen(req) as response:
108
+ result = json.loads(response.read().decode("utf-8"))
109
+ except urllib.error.HTTPError as e:
110
+ error_body = e.read().decode("utf-8")
111
+ logger.error(f"API request failed: {e.code} {e.reason} - {error_body}")
112
+ raise Exception(f"Claude API error: {e.code} {e.reason}")
113
+ except Exception as e:
114
+ logger.error(f"Request failed: {str(e)}")
115
+ raise
88
116
 
89
- response = {"role": "assistant", "content": result.content[0].text}
117
+ # Extract response content
118
+ response_content = result["content"][0]["text"]
119
+ response = {"role": "assistant", "content": response_content}
90
120
  self.conversation.append(response)
91
121
 
92
122
  return response, result
@@ -119,13 +149,13 @@ class Claude(ClaudeModel):
119
149
  return 1
120
150
 
121
151
  class ChatGPT(ChatGPTModel):
122
- """A turn-based, chat-like interface for the OpenAI Python SDK.
152
+ """A turn-based, chat-like interface for the OpenAI API via HTTP requests.
123
153
 
124
154
  This class's attributes are automatically defined on instantiation.
125
155
 
126
156
  Attributes:
127
- client:
128
- An `openai.OpenAI` instance.
157
+ api_key:
158
+ A string representing the OpenAI API key.
129
159
  conversation:
130
160
  A list of dictionaries representing each message exchanged
131
161
  with ChatGPT over the course of the instance's lifetime.
@@ -139,13 +169,13 @@ class ChatGPT(ChatGPTModel):
139
169
  A `Path` object representing the directory to which the
140
170
  contents of the `conversation` attribute should be written.
141
171
  temperature:
142
- A float representing the degree of 'randomness' that the model
172
+ A float representing the degree of "randomness" that the model
143
173
  should leverage in generating its response.
144
174
  """
145
175
 
146
176
  def __init__(
147
177
  self,
148
- model: str = "gpt-4.1",
178
+ model: str = "gpt-4",
149
179
  instructions: str = "You are ChatGPT, a helpful AI assistant."
150
180
  ) -> None:
151
181
  """Initialize a `ChatGPT` instance.
@@ -153,15 +183,19 @@ class ChatGPT(ChatGPTModel):
153
183
  Args:
154
184
  model (str):
155
185
  A string representing the ChatGPT model to be called.
156
- Defaults to "gpt-4.1".
157
- system_prompt (str):
186
+ Defaults to "gpt-4".
187
+ instructions (str):
158
188
  A string representing the system prompt to be used.
159
- Defaults to 'You are ChatGPT, a helpful AI assistant.'.
189
+ Defaults to "You are ChatGPT, a helpful AI assistant.".
160
190
 
161
191
  Returns:
162
192
  `None`.
163
193
  """
164
- self.client = OpenAI()
194
+ super().__init__()
195
+ self.api_key: str = self.api_key or os.getenv("OPENAI_API_KEY")
196
+ if not self.api_key:
197
+ raise ValueError("OPENAI_API_KEY environment variable is required")
198
+
165
199
  self.conversation: List[Dict] = []
166
200
  self.model: str = model
167
201
  self.instructions: str = instructions
@@ -172,66 +206,88 @@ class ChatGPT(ChatGPTModel):
172
206
  # Ensure that the conversations directory exists.
173
207
  self.save_to.parent.mkdir(parents=True, exist_ok=True)
174
208
 
175
- def message(self, msg: str):
209
+ def message(self, msg: str) -> str:
176
210
  """Send a message to ChatGPT.
177
211
 
178
- This method calls OpenAI's `Responses` API, passing either
179
- `msg` or the text output of the last response received as the
180
- `OpenAI.responses.create` method's `input` parameter. Upon
181
- receipt, the resulting `Response` object is appended to
182
- `self.conversation`.
212
+ This method calls OpenAI's Chat Completions API via HTTP request.
183
213
 
184
214
  Args:
185
215
  msg: A string representing the message to be sent.
186
216
 
187
217
  Returns:
188
- Nothing.
218
+ The response text from ChatGPT.
189
219
  """
190
220
  self.conversation.append({"role": "user", "content": msg})
191
221
 
192
- # Call the OpenAI API.
193
- if hasattr(self, "response"):
194
- self.response = self.client.responses.create(
195
- model=self.model,
196
- previous_response_id=self.response.id,
197
- instructions=self.instructions,
198
- max_output_tokens=self.max_tokens,
199
- temperature=self.temperature,
200
- input=msg
201
- )
202
- else:
203
- self.response = self.client.responses.create(
204
- model=self.model,
205
- instructions=self.instructions,
206
- max_output_tokens=self.max_tokens,
207
- temperature=self.temperature,
208
- input=msg
209
- )
210
-
211
- response_text = {"role": "assistant", "content": self.response.output_text}
212
-
213
- self.conversation.append(response_text)
214
-
215
- return self.response.output_text
216
-
217
- # noinspection DuplicatedCode
222
+ # Prepare messages for API call
223
+ messages = [{"role": "system", "content": self.instructions}] + self.conversation
224
+
225
+ # Prepare the API request
226
+ url = "https://api.openai.com/v1/chat/completions"
227
+
228
+ data = {
229
+ "model": self.model,
230
+ "messages": messages,
231
+ "max_tokens": self.max_tokens,
232
+ "temperature": self.temperature
233
+ }
234
+
235
+ headers = {
236
+ "Authorization": f"Bearer {self.api_key}",
237
+ "Content-Type": "application/json"
238
+ }
239
+
240
+ # Make the HTTP request
241
+ req = urllib.request.Request(
242
+ url,
243
+ data=json.dumps(data).encode("utf-8"),
244
+ headers=headers
245
+ )
246
+
247
+ try:
248
+ with urllib.request.urlopen(req) as response:
249
+ result = json.loads(response.read().decode("utf-8"))
250
+ except urllib.error.HTTPError as e:
251
+ error_body = e.read().decode("utf-8")
252
+ logger.error(f"API request failed: {e.code} {e.reason} - {error_body}")
253
+ raise Exception(f"OpenAI API error: {e.code} {e.reason}")
254
+ except Exception as e:
255
+ logger.error(f"Request failed: {str(e)}")
256
+ raise
257
+
258
+ # Extract response content
259
+ response_text = result["choices"][0]["message"]["content"]
260
+ response = {"role": "assistant", "content": response_text}
261
+ self.conversation.append(response)
262
+
263
+ return response_text
264
+
218
265
  def save(
219
266
  self,
220
- save_as: Union[str, Path] = (
221
- Path(
222
- f"~/.llm/chatgpt/conversations/\
223
- {dt.now().strftime('%Y-%m-%d_%H-%M-%S')}.json"
224
- ).expanduser()
225
- )
267
+ save_as: Union[str, Path] = None
226
268
  ) -> int:
227
- with open(save_as, "w") as f:
228
- f: SupportsWrite[str]
229
- logger.info(f"Saving conversation to {self.save_to}")
230
-
231
- try:
269
+ """Save the current conversation to a file.
270
+
271
+ Args:
272
+ save_as: Optional path to save the conversation.
273
+
274
+ Returns:
275
+ 0 on success, 1 on failure
276
+ """
277
+ if save_as is None:
278
+ save_as = Path(
279
+ f"~/.llm/chatgpt/conversations/{dt.now().strftime('%Y-%m-%d_%H-%M-%S')}.json"
280
+ ).expanduser()
281
+
282
+ try:
283
+ target_path = Path(save_as)
284
+ target_path.parent.mkdir(parents=True, exist_ok=True)
285
+
286
+ with open(target_path, "w") as f:
287
+ logger.info(f"Saving conversation to {target_path}")
232
288
  json.dump(self.conversation, f, indent=4)
233
289
  logger.info("Success.")
234
290
  return 0
235
- except Exception as e:
236
- raise Exception("Error: Failed to save conversation.") from e
237
- return 1
291
+ except Exception as e:
292
+ logger.error(f"Error: Failed to save conversation: {str(e)}")
293
+ return 1
@@ -16,7 +16,6 @@ from pathlib import Path
16
16
  from typing import Any, Dict, List, Protocol, Union
17
17
 
18
18
  # Third-party imports: Module-level
19
- from anthropic import Anthropic
20
19
  from dotenv import load_dotenv
21
20
 
22
21
 
@@ -26,11 +25,11 @@ logging.basicConfig(level=logging.INFO)
26
25
 
27
26
 
28
27
  # Create LLM data directories as needed.
29
- cleft_dir = Path("~/Library/Mobile Documents/com~apple~CloudDocs/cleft").expanduser()
30
- llm_directory = cleft_dir / "llm"
31
- dotenv_path = cleft_dir / ".env"
32
- if not cleft_dir.exists:
33
- cleft_dir.mkdir(parents=True, exist_ok=True)
28
+ gnarly_dir = Path("~/Library/Mobile Documents/com~apple~CloudDocs/gnarly").expanduser()
29
+ llm_directory = gnarly_dir / "llm"
30
+ dotenv_path = gnarly_dir / ".env"
31
+ if not gnarly_dir.exists():
32
+ gnarly_dir.mkdir(parents=True, exist_ok=True)
34
33
  if not llm_directory.exists():
35
34
  llm_directory.mkdir(parents=True, exist_ok=True)
36
35
  if not dotenv_path.exists():
@@ -57,17 +56,17 @@ CHATGPT_CONVERSATIONS_DIR = os.getenv(
57
56
 
58
57
  if not Path(CLAUDE_CONVERSATIONS_DIR).exists():
59
58
  try:
60
- Path(CLAUDE_CONVERSATIONS_DIR).mkdir()
59
+ Path(CLAUDE_CONVERSATIONS_DIR).mkdir(parents=True, exist_ok=True)
61
60
  except FileExistsError as e:
62
- raise (f"ERROR: The file `{CLAUDE_CONVERSATIONS_DIR}` already exists.")
61
+ raise Exception(f"ERROR: The file `{CLAUDE_CONVERSATIONS_DIR}` already exists.")
63
62
  else:
64
63
  logger.info(f"Successfully created `{CLAUDE_CONVERSATIONS_DIR}`.")
65
64
 
66
65
  if not Path(CHATGPT_CONVERSATIONS_DIR).exists():
67
66
  try:
68
- Path(CHATGPT_CONVERSATIONS_DIR).mkdir()
67
+ Path(CHATGPT_CONVERSATIONS_DIR).mkdir(parents=True, exist_ok=True)
69
68
  except FileExistsError as e:
70
- raise (f"ERROR: The file `{CHATGPT_CONVERSATIONS_DIR}` already exists.")
69
+ raise Exception(f"ERROR: The file `{CHATGPT_CONVERSATIONS_DIR}` already exists.")
71
70
  else:
72
71
  logger.info(f"Successfully created `{CHATGPT_CONVERSATIONS_DIR}`.")
73
72
 
@@ -84,7 +83,7 @@ class LLM(Protocol):
84
83
  @dataclass
85
84
  class ClaudeModel:
86
85
  api_key: str = ANTHROPIC_API_KEY
87
- model: str = "claude-3-7-sonnet-latest"
86
+ model: str = "claude-3-5-sonnet-20241022"
88
87
  name: str = "Claude"
89
88
 
90
89
  @staticmethod
@@ -107,11 +106,15 @@ class ClaudeModel:
107
106
  filepath = Path(CLAUDE_CONVERSATIONS_DIR) / filepath
108
107
 
109
108
  if not filepath.exists():
109
+ filepath.parent.mkdir(parents=True, exist_ok=True)
110
110
  filepath.touch(exist_ok=True)
111
111
 
112
112
  try:
113
113
  with open(filepath, "r") as f:
114
- conversation = json.load(f)
114
+ content = f.read().strip()
115
+ if not content:
116
+ return []
117
+ conversation = json.loads(content)
115
118
 
116
119
  # Validate conversation format
117
120
  if not isinstance(conversation, list):
@@ -141,7 +144,7 @@ class ClaudeModel:
141
144
  @dataclass
142
145
  class ChatGPTModel:
143
146
  api_key: str = OPENAI_API_KEY
144
- model: str = "gpt-4.1"
147
+ model: str = "gpt-4"
145
148
  name: str = "ChatGPT"
146
149
 
147
150
  @staticmethod
@@ -164,11 +167,15 @@ class ChatGPTModel:
164
167
  filepath = Path(CHATGPT_CONVERSATIONS_DIR) / filepath
165
168
 
166
169
  if not filepath.exists():
170
+ filepath.parent.mkdir(parents=True, exist_ok=True)
167
171
  filepath.touch(exist_ok=True)
168
172
 
169
173
  try:
170
174
  with open(filepath, "r") as f:
171
- conversation = json.load(f)
175
+ content = f.read().strip()
176
+ if not content:
177
+ return []
178
+ conversation = json.loads(content)
172
179
 
173
180
  # Validate conversation format
174
181
  if not isinstance(conversation, list):
@@ -0,0 +1,8 @@
1
+ Metadata-Version: 2.4
2
+ Name: gnarly
3
+ Version: 0.0.0.dev7
4
+ Summary: Add your description here
5
+ Author-email: "K. LeBryce" <k.lebryce@pm.me>
6
+ Requires-Python: >=3.10
7
+ Requires-Dist: python-dotenv>=1.1.0
8
+ Requires-Dist: starch
@@ -0,0 +1,17 @@
1
+ gnarly/__init__.py,sha256=_FM523OC7wDz24IfJ-a_M41p9Ynt5LudIRStXBKJGa8,1864
2
+ gnarly/constants.py,sha256=i5y1ms5lv48lybL_jAoZYmnD5EBvNcjqO77N600m1Wg,2344
3
+ gnarly/errors.py,sha256=s7YUYWdsNi_9EUwOdeSShYM7EzjqBWVbXtx-6mM_xfs,587
4
+ gnarly/types.py,sha256=bRDlESombVKmw8QrGHgTkwkOWguJZMbX6SiriG1LTyA,2634
5
+ gnarly/utils/__init__.py,sha256=aQgCNp67E4RCnaHfdWZvCi1fcHaLp6CKsQspc1A4t6Q,1285
6
+ gnarly/utils/io.py,sha256=ppkHZJ-n14cN0v9pwNtGVDnB5v7lJgg_C1vpv3bFfd4,6046
7
+ gnarly/utils/code/__init__.py,sha256=j8pQrFwSkzCKklnMlW5QaPbVahMev_AVySyWNSm36n4,553
8
+ gnarly/utils/code/projects.py,sha256=WHTSV0PB4GyoxY2jRgMxu_bq5u2NLLQevWwheXIsaSw,6469
9
+ gnarly/utils/llm/__init__.py,sha256=P51F2pqPeoO_qZpyz9-5TUFPjFm5MYyH4iCqS0RxZ2g,364
10
+ gnarly/utils/llm/chatgpt.py,sha256=v11e76LabKfcOLqb9pKNyvAuo-ra9BjyWw1uIWqZyAE,2781
11
+ gnarly/utils/llm/claude.py,sha256=AaEdgg1tzdj7gmL8LKE9T98VYhZ5jCCkEmsj-_v2LWI,2864
12
+ gnarly/utils/llm/interfaces.py,sha256=Q9vkqtUNXAj79PV9DTr8jdPSZbGM8NCEq2NTjxBHvWo,10437
13
+ gnarly/utils/llm/models.py,sha256=IlYV_lmb83373ZCVnPxDEsWWuV55cNy2IZfHCA4sq9w,6215
14
+ gnarly-0.0.0.dev7.dist-info/METADATA,sha256=ECQDMIoryyXGLBgOxawFRGibB2qd2y1GIoTOCefb9Go,217
15
+ gnarly-0.0.0.dev7.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
16
+ gnarly-0.0.0.dev7.dist-info/entry_points.txt,sha256=u6QA852MMLgzBBI9pNUz8GUPNSAydvD3m8IXWzFTe50,39
17
+ gnarly-0.0.0.dev7.dist-info/RECORD,,
@@ -1,15 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: gnarly
3
- Version: 0.0.0.dev5
4
- Summary: Add your description here
5
- Author-email: "K. LeBryce" <k.lebryce@pm.me>
6
- Requires-Python: >=3.10
7
- Requires-Dist: anthropic>=0.54.0
8
- Requires-Dist: linkify>=1.4
9
- Requires-Dist: myst-parser>=4.0.1
10
- Requires-Dist: openai>=1.86.0
11
- Requires-Dist: pytest>=8.4.0
12
- Requires-Dist: python-dotenv>=1.1.0
13
- Requires-Dist: sphinx-autobuild>=2024.10.3
14
- Requires-Dist: sphinx>=8.1.3
15
- Requires-Dist: starch
@@ -1,16 +0,0 @@
1
- gnarly/__init__.py,sha256=_FM523OC7wDz24IfJ-a_M41p9Ynt5LudIRStXBKJGa8,1864
2
- gnarly/constants.py,sha256=i5y1ms5lv48lybL_jAoZYmnD5EBvNcjqO77N600m1Wg,2344
3
- gnarly/errors.py,sha256=s7YUYWdsNi_9EUwOdeSShYM7EzjqBWVbXtx-6mM_xfs,587
4
- gnarly/utils/__init__.py,sha256=aQgCNp67E4RCnaHfdWZvCi1fcHaLp6CKsQspc1A4t6Q,1285
5
- gnarly/utils/io.py,sha256=0e8SeJkbLgH_dHhmYqBlbKzgANh_xhO25F-Uc42YOq0,4179
6
- gnarly/utils/code/__init__.py,sha256=j8pQrFwSkzCKklnMlW5QaPbVahMev_AVySyWNSm36n4,553
7
- gnarly/utils/code/projects.py,sha256=13peTYUB6LYV2C_WxKPqESDCOzD1hKDH5ti89Wh2RNs,5973
8
- gnarly/utils/llm/__init__.py,sha256=P51F2pqPeoO_qZpyz9-5TUFPjFm5MYyH4iCqS0RxZ2g,364
9
- gnarly/utils/llm/chatgpt.py,sha256=7C4cq9-eiEHF8XxgcRNJMaFBFDdFJiCsaySw9CtJ1cg,2793
10
- gnarly/utils/llm/claude.py,sha256=HYYzFJRZa74aALk1KI_P5qUaCTFIrAlQ4P9Bj6EEZEw,2876
11
- gnarly/utils/llm/interfaces.py,sha256=d3OUGUNjjdp8Rr8Ulkx_OIQO8tfBYsx-a-vk8q51y_c,8422
12
- gnarly/utils/llm/models.py,sha256=9i4ws_baGo-vaZtfvpNNvGYY4oxuDhK6bcdrqilV-I4,5817
13
- gnarly-0.0.0.dev5.dist-info/METADATA,sha256=xaqGhR3BU69QkmhWAvosBkPQn066rBdU4ffNeZUjCZk,443
14
- gnarly-0.0.0.dev5.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
15
- gnarly-0.0.0.dev5.dist-info/entry_points.txt,sha256=u6QA852MMLgzBBI9pNUz8GUPNSAydvD3m8IXWzFTe50,39
16
- gnarly-0.0.0.dev5.dist-info/RECORD,,