gnarly 0.0.0.dev5__py3-none-any.whl → 0.0.0.dev6__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,103 @@
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
+ logger: logging.Logger
45
+ is_persistent: bool
46
+ root_path: PathLike
47
+ dependencies: dict[str, list]
48
+
49
+
50
+ @dataclass
51
+ class GnarlyPythonProject(GnarlyProject):
52
+ project_type = GnarlyProjectType.PYTHON
53
+
54
+
55
+ @dataclass
56
+ class GnarlyCppProject(GnarlyProject):
57
+ project_Type = GnarlyProjectType.CPP
58
+
59
+
60
+ @dataclass
61
+ class GnarlyHaskellProject(GnarlyProject):
62
+ project_type = GnarlyProjectType.HASKELL
63
+
64
+
65
+ @dataclass
66
+ class GnarlyJavaScriptProject(GnarlyProject):
67
+ project_type = GnarlyProjectType.JAVASCRIPT
68
+
69
+
70
+ @dataclass
71
+ class GnarlyRProject(GnarlyProject):
72
+ project_type = GnarlyProjectType.R
73
+
74
+
75
+ @dataclass
76
+ class GnarlyRustProject(GnarlyProject):
77
+ project_type = GnarlyProjectType.RUST
78
+
79
+
80
+ @dataclass
81
+ class GnarlySwiftProject(GnarlyProject):
82
+ project_type = GnarlyProjectType.SWIFT
83
+
84
+
85
+ class GnarlyNamespace(ABC):
86
+ """
87
+ Base class for non-instantiable types that serve to encapsulate.
88
+
89
+ Subclasses of this ABC provide no constructors. Instead, attempts
90
+ to instantiate raise `NamespaceError`.
91
+ """
92
+ context_key: str
93
+
94
+ def __new__(cls) -> NamespaceError:
95
+ logger.error("`Project` is not intended for direct instantiation.")
96
+ raise NamespaceError(
97
+ f"`{cls.__name__}` is a namespace, which means that it "
98
+ "has no constructors. Instead, you should call one of the "
99
+ "static factory methods provided in one of its inner classes, "
100
+ "all of which return instances of the `GnarlyProject` base "
101
+ "class's concrete implementations."
102
+ )
103
+
@@ -6,116 +6,126 @@ 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
+
41
+
52
42
  class Python:
53
43
  """
54
44
  A namespace for Gnarly's Python project management utilities.
55
45
 
56
- Use the static functions defined in the `Project.Python` namespace to
57
- manage your Python project's code base.
46
+ Use the static functions defined in the ``Project.Python`` namespace
47
+ to manage your Python project's code base.
58
48
 
59
49
  Examples
60
50
  --------
61
51
  Basic usage:
62
52
 
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
- )
53
+ >>> from pprint import pprint
54
+ >>> from gnarly import Project
55
+ >>>
56
+ >>> mgr = Project.Python()
57
+ >>>
58
+ >>> pr: GnarlyPythonProject = mgr.create("my_python_project")
59
+ >>> pprint(pr)
60
+ GnarlyPythonProject(name='my_python_project',
61
+ project_type=<GnarlyProjectType.PYTHON: 8>,
62
+ logger=<RootLogger root (INFO)>,
63
+ is_persistent=True,
64
+ root_path=PosixPath('/Users/u/gnarly/gnarly_project'),
65
+ dependencies={'dev': [], 'optional': [], 'required': []})
66
+
95
67
  """
68
+ def __init__(
69
+ self,
70
+ context_key: str = "python_project_namespace"
71
+ ) -> None:
72
+ self._context_key = context_key
73
+
74
+
75
+ @property
76
+ def context_key(self) -> str:
77
+ return self._context_key
78
+
79
+ @context_key.setter
80
+ def context_key(self, value: str) -> None:
81
+ self._context_key = value
82
+
83
+ @context_key.deleter
84
+ def context_key(self) -> None:
85
+ del self._context_key
86
+
87
+
88
+ @staticmethod
96
89
  def create(
97
- cls,
98
- logger: logging.Logger = logging.getLogger(__name__),
99
- name: str = __package__,
90
+ name: str = "gnarly_python_project",
100
91
  project_type = GnarlyProjectType.PYTHON,
101
92
  is_persistent: bool = True,
102
- root_path: PathLike = GNARLY_PROJECT_ROOT_PATH / f"{__package__}/",
103
- dependencies: dict[str, list] = {
93
+ root_path: PathLike = GNARLY_PROJECT_ROOT_PATH / "gnarly_project",
94
+ dependencies: dict[str, list[str]] = {
104
95
  "dev": [],
105
96
  "optional": [],
106
97
  "required": []
107
98
  }
108
99
  ) -> "GnarlyPythonProject":
100
+ """
101
+ Create a Python project.
102
+
103
+ Rather than instantiating ``GnarlyPythonProject`` directly, you
104
+ call this static method on your ``Project.Python`` manager.
105
+
106
+ Parameters
107
+ ----------
108
+ name : str
109
+ The Python project's name.
110
+ project_type : GnarlyProjectType
111
+ The project's type, as characterized by its target
112
+ language configuration.
113
+ is_persistent : bool
114
+ The project's persistence state. Defaults to ``True``.
115
+ root_path : PathLike
116
+ The project's root path.
117
+ dependencies : dict[str, list[str]]
118
+ A dictionary that represents the project's dependencies.
119
+
120
+ Returns
121
+ -------
122
+ A new instance of ``GnarlyPythonProject``.
123
+
124
+ """
125
+
109
126
  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
- ),
127
+ name=name,
128
+ project_type=project_type,
119
129
  is_persistent=is_persistent,
120
130
  root_path=root_path,
121
131
  dependencies=dependencies
@@ -126,7 +136,6 @@ class Project:
126
136
  def create(
127
137
  name: str,
128
138
  project_type: GnarlyProjectType,
129
- logger: logging.Logger = logger,
130
139
  is_persistent: bool = True,
131
140
  root_path: PathLike = GNARLY_PROJECT_ROOT_PATH,
132
141
  dependencies: dict[str, list] = {
@@ -136,70 +145,61 @@ class Project:
136
145
  }
137
146
  ) -> "GnarlyProject":
138
147
  match project_type:
148
+ case project_type.CPP:
149
+ return GnarlyCppProject(
150
+ name=name,
151
+ project_type=project_type,
152
+ is_persistent=is_persistent,
153
+ root_path=root_path,
154
+ dependencies=dependencies
155
+ )
139
156
  case project_type.HASKELL:
140
157
  return GnarlyHaskellProject(
141
158
  name=name,
142
159
  project_type=project_type,
143
- logger=logger,
160
+ is_persistent=is_persistent,
161
+ root_path=root_path,
162
+ dependencies=dependencies
163
+ )
164
+ case project_type.JAVASCRIPT:
165
+ return GnarlyJavaScriptProject(
166
+ name=name,
167
+ project_type=project_type,
144
168
  is_persistent=is_persistent,
145
169
  root_path=root_path,
146
170
  dependencies=dependencies
147
171
  )
148
172
  case project_type.PYTHON:
149
- return GnarlyPythonProject
173
+ return GnarlyPythonProject(
174
+ name=name,
175
+ project_type=project_type,
176
+ is_persistent=is_persistent,
177
+ root_path=root_path,
178
+ dependencies=dependencies
179
+ )
150
180
  case project_type.R:
151
- return GnarlyRProject
181
+ return GnarlyRProject(
182
+ name=name,
183
+ project_type=project_type,
184
+ is_persistent=is_persistent,
185
+ root_path=root_path,
186
+ dependencies=dependencies
187
+ )
152
188
  case project_type.RUST:
153
- return GnarlyRustProject
189
+ return GnarlyRustProject(
190
+ name=name,
191
+ project_type=project_type,
192
+ is_persistent=is_persistent,
193
+ root_path=root_path,
194
+ dependencies=dependencies
195
+ )
154
196
  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
-
197
+ return GnarlySwiftProject(
198
+ name=name,
199
+ project_type=project_type,
200
+ is_persistent=is_persistent,
201
+ root_path=root_path,
202
+ dependencies=dependencies
203
+ )
200
204
 
201
- @dataclass
202
- class GnarlySwiftProject(GnarlyProject):
203
- project_type = GnarlyProjectType.SWIFT
204
- pass
205
205
 
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.dev6
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=kgUuhTo1CAho_vKlzNRISR4Gp24Pc33epAXJt5eR1p0,2661
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=URI1Nq3lYbfVPFtygAKi350ToM0ohDb4A7RHXbgLK_A,6470
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.dev6.dist-info/METADATA,sha256=oc2CudoWqDwdS2295nDaFyEssyVP0FuDX02EUl6iwCM,217
15
+ gnarly-0.0.0.dev6.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
16
+ gnarly-0.0.0.dev6.dist-info/entry_points.txt,sha256=u6QA852MMLgzBBI9pNUz8GUPNSAydvD3m8IXWzFTe50,39
17
+ gnarly-0.0.0.dev6.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,,