gnarly 0.0.0.dev3__py3-none-any.whl → 0.0.0.dev5__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/__init__.py CHANGED
@@ -7,8 +7,23 @@ A general-use abstraction layer for the lazy.
7
7
  """
8
8
  import logging
9
9
 
10
- from . import constants, utilities
11
- from .utilities import io, stream
10
+ from . import errors, constants, utils
11
+ from .errors import NamespaceError
12
+ from .utils import code, io, llm
13
+ from .utils.code.projects import (
14
+ GnarlyProject,
15
+ GnarlyCppProject,
16
+ GnarlyHaskellProject,
17
+ GnarlyJavaScriptProject,
18
+ GnarlyPythonProject,
19
+ GnarlyRProject,
20
+ GnarlyRustProject,
21
+ GnarlySwiftProject,
22
+ GnarlyProjectType,
23
+ Project
24
+ )
25
+ from .utils.io import stream
26
+ from .utils.llm import claude, chatgpt, ChatGPT, Claude
12
27
 
13
28
  logging.basicConfig(level=logging.DEBUG)
14
29
  logger = logging.getLogger(__name__)
@@ -21,11 +36,18 @@ except ImportError as e:
21
36
 
22
37
  __all__ = [
23
38
  # ─── package-level exports ───────────────────────────────────────────────
24
- "utilities",
39
+ "code", "llm", "utils",
25
40
 
26
41
  # ─── module-level exports ────────────────────────────────────────────────
27
- "constants", "io",
42
+ "chatgpt", "claude", "errors", "constants", "io",
28
43
 
29
44
  # ─── function-level exports ──────────────────────────────────────────────
30
- "stream"
45
+ "stream",
46
+
47
+ # ─── class-level exports ─────────────────────────────────────────────────
48
+ "ChatGPT", "Claude",
49
+ "GnarlyProject", "GnarlyCppProject", "GnarlyHaskellProject",
50
+ "GnarlyJavaScriptProject", "GnarlyPythonProject", "GnarlyRustProject",
51
+ "GnarlyRProject", "GnarlyRustProject", "GnarlySwiftProject",
52
+ "GnarlyProjectType", "NamespaceError", "Project"
31
53
  ]
gnarly/constants.py CHANGED
@@ -22,9 +22,10 @@ logger.setLevel(logging.DEBUG)
22
22
 
23
23
 
24
24
  # ─── package metadata ─────────────────────────────────────────────────── ✦✦ ─
25
- __author__ = "K. LeBryce <kosmolebryce@gmail.com>"
26
- __package__ = "Gnarly"
27
- __version__ = "0.0.0"
25
+ __author__: str = "K. LeBryce <kosmolebryce@gmail.com>"
26
+ __package__: str = "Gnarly"
27
+ __version__: str = "0.0.0"
28
+ __description__: str = "A sophisticated abstraction layer for lazy developers."
28
29
 
29
30
  # ─── resource references ──────────────────────────────────────────────── ✦✦ ─
30
31
  GNARLY_DATA_DIR: Path = user_data_path(
@@ -55,6 +56,9 @@ GNARLY_LOG_DIR: Path = user_log_path(
55
56
  ensure_exists=True
56
57
  )
57
58
 
59
+ GNARLY_PROJECT_ROOT_PATH: Path = Path.home() / "gnarly/"
60
+ GNARLY_PROJECT_ROOT_PATH.mkdir(exist_ok=True)
61
+
58
62
  DOTENV_FILE_PATH: Path = GNARLY_CONFIG_DIR / "gnarly.env"
59
63
  DOTENV_FILE_PATH.touch()
60
64
 
@@ -75,3 +79,4 @@ except IOError as e:
75
79
  f"{GNARLY_CONFIG_DIR.resolve()}"
76
80
  )
77
81
  raise RuntimeError from e
82
+
gnarly/errors.py ADDED
@@ -0,0 +1,29 @@
1
+ """
2
+ Errors
3
+ ======
4
+
5
+ This module defines the custom exception types used throughout the
6
+ code base. This is a Gnarly implementation detail.
7
+ """
8
+
9
+ import logging
10
+
11
+ from .constants import GNARLY_LOG_DIR
12
+
13
+ logger = logging.getLogger(__name__)
14
+ logging.basicConfig(
15
+ level=logging.DEBUG,
16
+ filename=(GNARLY_LOG_DIR / "gnarly.log").resolve()
17
+ )
18
+ logger.info("Logger setup complete.")
19
+
20
+ class GnarlyError(Exception):
21
+ """Gnarly's base error class."""
22
+ pass
23
+
24
+
25
+ class NamespaceError(GnarlyError):
26
+ """
27
+ An error type that arises from an improper namespace access attempt.
28
+ """
29
+ pass
@@ -0,0 +1,44 @@
1
+ """
2
+ Utilities
3
+ =========
4
+
5
+ A convenient library comprising a collection of simple Python utilities.
6
+
7
+ """
8
+ from . import code, io, llm
9
+ from .code import (
10
+ GnarlyProject,
11
+ GnarlyCppProject,
12
+ GnarlyHaskellProject,
13
+ GnarlyJavaScriptProject,
14
+ GnarlyPythonProject,
15
+ GnarlyRProject,
16
+ GnarlyRustProject,
17
+ GnarlySwiftProject,
18
+ GnarlyProjectType,
19
+ Project
20
+ )
21
+ from .llm.interfaces import ChatGPT, Claude
22
+
23
+
24
+ __all__ = [
25
+ # ─── package-level exports ───────────────────────────────────────────────
26
+ "code", "llm",
27
+
28
+ # ─── module-level exports ────────────────────────────────────────────────
29
+ "io",
30
+
31
+ # ─── class-level exports ─────────────────────────────────────────────────
32
+ "ChatGPT",
33
+ "Claude",
34
+ "GnarlyProject",
35
+ "GnarlyCppProject",
36
+ "GnarlyHaskellProject",
37
+ "GnarlyJavaScriptProject",
38
+ "GnarlyPythonProject",
39
+ "GnarlyRProject",
40
+ "GnarlyRustProject",
41
+ "GnarlySwiftProject",
42
+ "GnarlyProjectType",
43
+ "Project"
44
+ ]
@@ -0,0 +1,33 @@
1
+ """
2
+ Gnarly Code
3
+
4
+ Developer utilities.
5
+
6
+ """
7
+
8
+ from . projects import (
9
+ GnarlyProject,
10
+ GnarlyCppProject,
11
+ GnarlyHaskellProject,
12
+ GnarlyJavaScriptProject,
13
+ GnarlyPythonProject,
14
+ GnarlyRProject,
15
+ GnarlyRustProject,
16
+ GnarlySwiftProject,
17
+ GnarlyProjectType,
18
+ Project
19
+ )
20
+
21
+
22
+ __all__ = [
23
+ "GnarlyProject",
24
+ "GnarlyCppProject",
25
+ "GnarlyHaskellProject",
26
+ "GnarlyJavaScriptProject",
27
+ "GnarlyPythonProject",
28
+ "GnarlyRProject",
29
+ "GnarlyRustProject",
30
+ "GnarlySwiftProject",
31
+ "GnarlyProjectType",
32
+ "Project"
33
+ ]
@@ -0,0 +1,205 @@
1
+ """
2
+ Projects
3
+ ========
4
+
5
+ This module defines and implements various facilities useful for
6
+ project management.
7
+
8
+ """
9
+ from dataclasses import dataclass
10
+ from enum import Enum, auto
11
+ import logging
12
+ from os import PathLike
13
+
14
+ from ...constants import GNARLY_PROJECT_ROOT_PATH
15
+ from ...errors import NamespaceError
16
+
17
+ logger: logging.Logger = logging.getLogger()
18
+ logging.basicConfig(level=logging.DEBUG, format=logging.BASIC_FORMAT)
19
+
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
+
37
+ class Project:
38
+ """
39
+ A namespace for Gnarly Code's project management utility suite.
40
+
41
+ This is a Gnarly implementation detail. It is not intended for direct
42
+ instantiation. Attempts to instantiate this class will raise a
43
+ `NamespaceError`.
44
+ """
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
+
51
+ # ─── Utility Groups ──────────────────────────────────────────────────────
52
+ class Python:
53
+ """
54
+ A namespace for Gnarly's Python project management utilities.
55
+
56
+ Use the static functions defined in the `Project.Python` namespace to
57
+ manage your Python project's code base.
58
+
59
+ Examples
60
+ --------
61
+ Basic usage:
62
+
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
+ )
95
+ """
96
+ def create(
97
+ cls,
98
+ logger: logging.Logger = logging.getLogger(__name__),
99
+ name: str = __package__,
100
+ project_type = GnarlyProjectType.PYTHON,
101
+ is_persistent: bool = True,
102
+ root_path: PathLike = GNARLY_PROJECT_ROOT_PATH / f"{__package__}/",
103
+ dependencies: dict[str, list] = {
104
+ "dev": [],
105
+ "optional": [],
106
+ "required": []
107
+ }
108
+ ) -> "GnarlyPythonProject":
109
+ 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
+ ),
119
+ is_persistent=is_persistent,
120
+ root_path=root_path,
121
+ dependencies=dependencies
122
+ )
123
+
124
+
125
+ @staticmethod
126
+ def create(
127
+ name: str,
128
+ project_type: GnarlyProjectType,
129
+ logger: logging.Logger = logger,
130
+ is_persistent: bool = True,
131
+ root_path: PathLike = GNARLY_PROJECT_ROOT_PATH,
132
+ dependencies: dict[str, list] = {
133
+ "dev": [],
134
+ "optional": [],
135
+ "required": []
136
+ }
137
+ ) -> "GnarlyProject":
138
+ match project_type:
139
+ case project_type.HASKELL:
140
+ return GnarlyHaskellProject(
141
+ name=name,
142
+ project_type=project_type,
143
+ logger=logger,
144
+ is_persistent=is_persistent,
145
+ root_path=root_path,
146
+ dependencies=dependencies
147
+ )
148
+ case project_type.PYTHON:
149
+ return GnarlyPythonProject
150
+ case project_type.R:
151
+ return GnarlyRProject
152
+ case project_type.RUST:
153
+ return GnarlyRustProject
154
+ 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
+
200
+
201
+ @dataclass
202
+ class GnarlySwiftProject(GnarlyProject):
203
+ project_type = GnarlyProjectType.SWIFT
204
+ pass
205
+
@@ -9,7 +9,7 @@ import os
9
9
  import string
10
10
  import sys
11
11
  from logging import (
12
- DEBUG, ERROR, FileHandler, Formatter, StreamHandler, getLogger
12
+ DEBUG, INFO, FileHandler, Formatter, StreamHandler, getLogger
13
13
  )
14
14
  from time import sleep
15
15
 
@@ -28,7 +28,7 @@ file_handler.setLevel(DEBUG)
28
28
 
29
29
  console_handler = StreamHandler(sys.stdout)
30
30
  console_handler.setFormatter(formatter)
31
- console_handler.setLevel(ERROR)
31
+ console_handler.setLevel(level=INFO)
32
32
 
33
33
  logger.addHandler(file_handler)
34
34
  logger.addHandler(console_handler)
@@ -56,7 +56,13 @@ def stream(
56
56
  -------
57
57
  Nothing.
58
58
  """
59
- charlim = charlim or min(72, os.get_terminal_size().columns - 12)
59
+ try:
60
+ 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
65
+
60
66
  lines = s.splitlines()
61
67
  wsp = string.whitespace
62
68
  counter: int = 0
@@ -73,42 +79,47 @@ def stream(
73
79
  raise UserWarning from e
74
80
 
75
81
  if not charlim:
76
- charlim = 73
77
-
78
- for line in lines:
79
- chars = enumerate(line)
80
- for i, c in chars:
81
- if (i % charlim != 0) or i == 0:
82
+ for line in lines:
83
+ for c in line:
82
84
  print(c, end="", flush=True)
83
85
  sleep(delay)
84
- elif (i % charlim) == 0 and (str(c) in wsp or str(c) in ["-", "–", "─"]):
85
- print(c + "\n", end="", flush=True)
86
- sleep(delay)
87
- elif (i % charlim == 0) and (str(c) not in wsp):
88
- print(c, end="", flush=True)
89
- try:
90
- while True:
91
- _, next_c = next(chars)
92
- if str(next_c) in wsp or str(next_c) in ["-", "–", "─"]:
93
- print(next_c + "\n", end="", flush=True)
94
- break
95
- else:
96
- print(next_c, end="", flush=True)
97
- except StopIteration:
98
- logger.info(
99
- f"Reached end of line after {counter} iterations."
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 ["-", "–", "─"]):
95
+ print(c + "\n", end="", flush=True)
96
+ 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
+
113
+ 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}"
100
122
  )
101
- break
102
-
103
- else:
104
- logger.warning(
105
- f"Unexpected conditions encountered:\n"
106
- f"Iterating over: {str(chars)}\n"
107
- f"Current index: {i} \n"
108
- f"Character at current index: {c}\n"
109
- f"Character limit: {charlim}\n"
110
-
111
- f"\n{i} % {charlim} = {i % charlim}"
112
- )
113
- counter +=1
114
- print("\n", end="", flush=True)
123
+ counter +=1
124
+ print()
125
+
@@ -0,0 +1,22 @@
1
+ """
2
+ Gnarly LLM Utilities
3
+ ====================
4
+
5
+ Interfaces for LLM interaction.
6
+
7
+ """
8
+ from . import chatgpt, claude, interfaces, models
9
+ from .interfaces import Claude, ChatGPT
10
+ from .models import ChatGPTModel, ClaudeModel
11
+
12
+
13
+ __all__ = [
14
+ "Claude",
15
+ "ClaudeModel",
16
+ "ChatGPT",
17
+ "ChatGPTModel",
18
+ "chatgpt",
19
+ "claude",
20
+ "interfaces",
21
+ "models"
22
+ ]
@@ -0,0 +1,94 @@
1
+ """ChatGPT REPL
2
+
3
+ Entry point for the ChatGPT REPL.
4
+ """
5
+ import json
6
+ from datetime import datetime as dt
7
+ from pathlib import Path
8
+
9
+ from ..io import stream
10
+ from .interfaces import ChatGPT
11
+ from ..llm.models import CHATGPT_CONVERSATIONS_DIR, ChatGPTModel
12
+
13
+ pp = stream
14
+
15
+ # Helper functions
16
+ def check_for_jupyter() -> bool:
17
+ """
18
+ check_for_jupyter
19
+
20
+ Evaluates whether the REPL is being invoked within a Jupyter environment.
21
+ """
22
+ try:
23
+ shell = get_ipython().__class__.__name__
24
+ if shell == 'ZMQInteractiveShell': # Jupyter notebook or qtconsole
25
+ return True
26
+ elif shell == 'TerminalInteractiveShell': # Terminal IPython
27
+ return False
28
+ else:
29
+ return False
30
+ except NameError: # Likely standard Python interpreter
31
+ return False
32
+
33
+ def main() -> bool:
34
+ """
35
+ main
36
+
37
+ Runloop for the ChatGPT REPL.
38
+ """
39
+ exit_commands: list = ["quit", "exit", "q", "e", "x"]
40
+ save_command: str = "save"
41
+ load_command: str = "load"
42
+ is_jupyter = check_for_jupyter()
43
+
44
+ # Instantiate the ChatGPT interface
45
+ chatgpt = ChatGPT()
46
+
47
+ try:
48
+ while True:
49
+ pp("[You]") # No newline after [You]
50
+ prompt = input() # Get input on same line
51
+
52
+ if is_jupyter:
53
+ pp("\n\n[You]")
54
+ pp(prompt)
55
+ pp("\n")
56
+
57
+ # Check for exit command
58
+ if prompt.lower() in exit_commands:
59
+ pp("Goodbye!")
60
+ return True
61
+
62
+ # Check for save command
63
+ if prompt.lower() == save_command:
64
+ chatgpt.save(save_as=Path(
65
+ f"{CHATGPT_CONVERSATIONS_DIR}/{dt.now().strftime('%Y-%m-%d_%H%M%S')}.json"
66
+ ))
67
+ pp("Conversation saved!\n")
68
+ continue
69
+
70
+ # Check for load command
71
+ if prompt.lower().startswith(load_command):
72
+ try:
73
+ # Extract the filepath from the command
74
+ filepath = prompt[len(load_command):].strip().strip("'\"")
75
+ if filepath:
76
+ # Load the conversation
77
+ chatgpt.conversation = ChatGPTModel.load_conversation(filepath)
78
+ pp(f"Loaded conversation from {filepath}")
79
+ continue
80
+ else:
81
+ pp("Please provide a filepath to load")
82
+ continue
83
+ except Exception as e:
84
+ pp(f"Error loading conversation: {e}")
85
+ continue
86
+
87
+ response = chatgpt.message(prompt)
88
+ pp("\n\n[ChatGPT]")
89
+ pp(response)
90
+ pp("\n")
91
+
92
+ except KeyboardInterrupt:
93
+ pp("\n\nGoodbye!\n\n")
94
+ return True
@@ -0,0 +1,99 @@
1
+ """Claude REPL
2
+
3
+ Entry point for the Claude REPL.
4
+ """
5
+ import logging
6
+ import json
7
+ from datetime import datetime as dt
8
+ from pathlib import Path
9
+
10
+ from ..io import stream
11
+ from .interfaces import Claude
12
+ from ..llm.models import CLAUDE_CONVERSATIONS_DIR, ClaudeModel
13
+
14
+
15
+ logger = logging.getLogger(__name__)
16
+ logging.basicConfig(level=logging.INFO)
17
+
18
+ pp = stream
19
+
20
+ # Helper functions
21
+ def check_for_jupyter() -> bool:
22
+ """
23
+ check_for_jupyter
24
+
25
+ Evaluates whether the REPL is being invoked within a Jupyter environment.
26
+ """
27
+ try:
28
+ shell = get_ipython().__class__.__name__
29
+ if shell == 'ZMQInteractiveShell': # Jupyter notebook or qtconsole
30
+ return True
31
+ elif shell == 'TerminalInteractiveShell': # Terminal IPython
32
+ return False
33
+ else:
34
+ return False
35
+ except NameError: # Likely standard Python interpreter
36
+ return False
37
+
38
+ def main() -> bool:
39
+ """
40
+ main
41
+
42
+ Runloop for the Claude REPL.
43
+ """
44
+ exit_commands: list = ["quit", "exit", "q", "e", "x"]
45
+ save_command: str = "save"
46
+ load_command: str = "load"
47
+ is_jupyter = check_for_jupyter()
48
+
49
+ # Instantiate the Claude interface
50
+ claude = Claude()
51
+
52
+ try:
53
+ while True:
54
+ pp("[You]") # No newline after [You]
55
+ prompt = input() # Get input on same line
56
+
57
+ if is_jupyter:
58
+ pp("\n\n[You]")
59
+ pp(prompt)
60
+ pp("\n")
61
+
62
+ # Check for exit command
63
+ if prompt.lower() in exit_commands:
64
+ pp("Goodbye!")
65
+ return True
66
+
67
+ # Check for save command
68
+ if prompt.lower() == save_command:
69
+ claude.save(save_as=Path(
70
+ f"{CLAUDE_CONVERSATIONS_DIR}/{dt.now().strftime('%Y-%m-%d_%H%M%S')}.json"
71
+ ))
72
+ pp("Conversation saved!")
73
+ continue
74
+
75
+ # Check for load command
76
+ if prompt.lower().startswith(load_command):
77
+ try:
78
+ # Extract the filepath from the command
79
+ filepath = prompt[len(load_command):].strip().strip("'\"")
80
+ if filepath:
81
+ # Load the conversation
82
+ claude.conversation = ClaudeModel.load_conversation(filepath)
83
+ pp(f"Loaded conversation from {filepath}")
84
+ continue
85
+ else:
86
+ pp("Please provide a filepath to load")
87
+ continue
88
+ except Exception as e:
89
+ pp(f"Error loading conversation: {e}")
90
+ continue
91
+
92
+ response = claude.message(prompt)[0]["content"]
93
+ pp("\n\n[Claude]")
94
+ pp(response)
95
+ pp("\n")
96
+
97
+ except KeyboardInterrupt:
98
+ pp("Goodbye!")
99
+ return True
@@ -0,0 +1,237 @@
1
+ """LLM Interfaces
2
+
3
+ Classes for interfacing with LLMs as defined in the `models` module.
4
+ """
5
+ # ─── import statements ───────────────────────────────────────────────── ✦✦ ──
6
+
7
+ # standard library imports
8
+ import json
9
+ import logging
10
+ import os
11
+ from datetime import datetime as dt
12
+ from pathlib import Path
13
+ from typing import Dict, List, Tuple, TYPE_CHECKING, Union
14
+ if TYPE_CHECKING:
15
+ from _typeshed import SupportsWrite
16
+
17
+ # third-party imports
18
+ from anthropic import Anthropic
19
+ from anthropic.types import Message
20
+ from dotenv import load_dotenv
21
+ from openai import OpenAI
22
+ from platformdirs import user_config_path
23
+
24
+ # local imports
25
+ from .models import (
26
+ CHATGPT_CONVERSATIONS_DIR, CLAUDE_CONVERSATIONS_DIR,
27
+ ClaudeModel, ChatGPTModel
28
+ )
29
+
30
+ # ─── logger setup ──────────────────────────────────────────────────────── ✦ ─
31
+ logger = logging.getLogger(__name__)
32
+ logging.basicConfig(level=logging.INFO)
33
+
34
+ # ─── constants ─────────────────────────────────────────────────────────── ✦ ─
35
+ APP_NAME = "cleft"
36
+ APP_AUTHOR = "k.lebryce"
37
+ APP_CONFIG_DIR: Path = user_config_path(
38
+ APP_NAME, APP_AUTHOR, ensure_exists=True
39
+ )
40
+
41
+ # load environment variables from .env file
42
+ try:
43
+ load_dotenv(Path(APP_CONFIG_DIR, ".env").resolve())
44
+ except FileNotFoundError:
45
+ APP_CONFIG_DIR.mkdir(parents=True, exist_ok=True)
46
+ Path(APP_CONFIG_DIR, ".env").touch()
47
+ except IOError as e:
48
+ raise IOError(
49
+ "Failed to load environment variables from .env file."
50
+ ) from e
51
+
52
+
53
+ # ─── interfaces ──────────────────────────────────────────────────────── ✦✦ ──
54
+ class Claude(ClaudeModel):
55
+ def __init__(
56
+ self,
57
+ system_prompt: str = "You are Claude, a friendly AI assistant."
58
+ ):
59
+ super().__init__()
60
+ self.client: Anthropic = Anthropic()
61
+ self.conversation: List[Dict] = []
62
+ self.max_tokens: int = 4096
63
+ self.system_prompt = system_prompt
64
+ self.temperature: float = 0.2
65
+
66
+ # Ensure save_to is a Path object
67
+ self.save_to = Path(CLAUDE_CONVERSATIONS_DIR)
68
+
69
+ # Create directory if it doesn't exist
70
+ self.save_to.parent.mkdir(parents=True, exist_ok=True)
71
+ logger.info(f"Conversation will be saved to {self.save_to}")
72
+
73
+ def message(self, msg: str) -> Tuple[Dict, Message]:
74
+ """
75
+ Creates a payload using the `msg` string and returns Claude's
76
+ response as a string.
77
+ """
78
+ self.conversation.append({"role": "user", "content": msg})
79
+
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
87
+ )
88
+
89
+ response = {"role": "assistant", "content": result.content[0].text}
90
+ self.conversation.append(response)
91
+
92
+ return response, result
93
+
94
+ def save(self, save_as: Union[str, Path] = None) -> int:
95
+ """
96
+ Save the current conversation to a file.
97
+
98
+ Args:
99
+ save_as: Optional path to save the conversation. If not provided,
100
+ uses the default path from initialization.
101
+
102
+ Returns:
103
+ 0 on success, 1 on failure
104
+ """
105
+ try:
106
+ target_path = Path(save_as) if save_as else self.save_to
107
+ if not target_path.is_absolute():
108
+ target_path = Path(CLAUDE_CONVERSATIONS_DIR) / target_path
109
+
110
+ target_path.parent.mkdir(parents=True, exist_ok=True)
111
+
112
+ with open(target_path, "w") as f:
113
+ json.dump(self.conversation, f, indent=4)
114
+ logger.info(f"Successfully saved conversation to {target_path}")
115
+ return 0
116
+
117
+ except Exception as e:
118
+ logger.error(f"Failed to save conversation: {str(e)}")
119
+ return 1
120
+
121
+ class ChatGPT(ChatGPTModel):
122
+ """A turn-based, chat-like interface for the OpenAI Python SDK.
123
+
124
+ This class's attributes are automatically defined on instantiation.
125
+
126
+ Attributes:
127
+ client:
128
+ An `openai.OpenAI` instance.
129
+ conversation:
130
+ A list of dictionaries representing each message exchanged
131
+ with ChatGPT over the course of the instance's lifetime.
132
+ model:
133
+ A string representing the ChatGPT model to be called on
134
+ invocation of the `message` method.
135
+ max_tokens:
136
+ An integer representing the maximum number of tokens that
137
+ the model should output.
138
+ save_to:
139
+ A `Path` object representing the directory to which the
140
+ contents of the `conversation` attribute should be written.
141
+ temperature:
142
+ A float representing the degree of 'randomness' that the model
143
+ should leverage in generating its response.
144
+ """
145
+
146
+ def __init__(
147
+ self,
148
+ model: str = "gpt-4.1",
149
+ instructions: str = "You are ChatGPT, a helpful AI assistant."
150
+ ) -> None:
151
+ """Initialize a `ChatGPT` instance.
152
+
153
+ Args:
154
+ model (str):
155
+ A string representing the ChatGPT model to be called.
156
+ Defaults to "gpt-4.1".
157
+ system_prompt (str):
158
+ A string representing the system prompt to be used.
159
+ Defaults to 'You are ChatGPT, a helpful AI assistant.'.
160
+
161
+ Returns:
162
+ `None`.
163
+ """
164
+ self.client = OpenAI()
165
+ self.conversation: List[Dict] = []
166
+ self.model: str = model
167
+ self.instructions: str = instructions
168
+ self.max_tokens: int = 4096
169
+ self.save_to: Path = Path(CHATGPT_CONVERSATIONS_DIR)
170
+ self.temperature: float = 0.2
171
+
172
+ # Ensure that the conversations directory exists.
173
+ self.save_to.parent.mkdir(parents=True, exist_ok=True)
174
+
175
+ def message(self, msg: str):
176
+ """Send a message to ChatGPT.
177
+
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`.
183
+
184
+ Args:
185
+ msg: A string representing the message to be sent.
186
+
187
+ Returns:
188
+ Nothing.
189
+ """
190
+ self.conversation.append({"role": "user", "content": msg})
191
+
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
218
+ def save(
219
+ 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
+ )
226
+ ) -> 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:
232
+ json.dump(self.conversation, f, indent=4)
233
+ logger.info("Success.")
234
+ return 0
235
+ except Exception as e:
236
+ raise Exception("Error: Failed to save conversation.") from e
237
+ return 1
@@ -0,0 +1,195 @@
1
+ """
2
+ LLM Models
3
+ ==========
4
+
5
+ Classes for representing LLM models and their characteristic attributes.
6
+
7
+ """
8
+
9
+ # Standard library imports: Package-level
10
+ import json
11
+ import logging
12
+ import os
13
+ from dataclasses import dataclass
14
+ from enum import Enum
15
+ from pathlib import Path
16
+ from typing import Any, Dict, List, Protocol, Union
17
+
18
+ # Third-party imports: Module-level
19
+ from anthropic import Anthropic
20
+ from dotenv import load_dotenv
21
+
22
+
23
+ # Set up logging.
24
+ logger = logging.getLogger(__name__)
25
+ logging.basicConfig(level=logging.INFO)
26
+
27
+
28
+ # 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)
34
+ if not llm_directory.exists():
35
+ llm_directory.mkdir(parents=True, exist_ok=True)
36
+ if not dotenv_path.exists():
37
+ dotenv_path.touch(exist_ok=True)
38
+
39
+
40
+ # Load environment variables.
41
+ load_dotenv(dotenv_path)
42
+
43
+
44
+ # Getting API keys from environment
45
+ ANTHROPIC_API_KEY = os.getenv("ANTHROPIC_API_KEY")
46
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
47
+
48
+
49
+ # Get LLM conversation directories.
50
+ CLAUDE_CONVERSATIONS_DIR = os.getenv(
51
+ "CLAUDE_CONVERSATIONS_DIR", str(llm_directory / "claude/conversations")
52
+ )
53
+ CHATGPT_CONVERSATIONS_DIR = os.getenv(
54
+ "CHATGPT_CONVERSATIONS_DIR", str(llm_directory / "chatgpt/conversations")
55
+ )
56
+
57
+
58
+ if not Path(CLAUDE_CONVERSATIONS_DIR).exists():
59
+ try:
60
+ Path(CLAUDE_CONVERSATIONS_DIR).mkdir()
61
+ except FileExistsError as e:
62
+ raise (f"ERROR: The file `{CLAUDE_CONVERSATIONS_DIR}` already exists.")
63
+ else:
64
+ logger.info(f"Successfully created `{CLAUDE_CONVERSATIONS_DIR}`.")
65
+
66
+ if not Path(CHATGPT_CONVERSATIONS_DIR).exists():
67
+ try:
68
+ Path(CHATGPT_CONVERSATIONS_DIR).mkdir()
69
+ except FileExistsError as e:
70
+ raise (f"ERROR: The file `{CHATGPT_CONVERSATIONS_DIR}` already exists.")
71
+ else:
72
+ logger.info(f"Successfully created `{CHATGPT_CONVERSATIONS_DIR}`.")
73
+
74
+
75
+ class LLM(Protocol):
76
+ """
77
+ Defines the attributes required for conformance to the LLM protocol.
78
+ """
79
+
80
+ api_key: str
81
+ name: str
82
+
83
+
84
+ @dataclass
85
+ class ClaudeModel:
86
+ api_key: str = ANTHROPIC_API_KEY
87
+ model: str = "claude-3-7-sonnet-latest"
88
+ name: str = "Claude"
89
+
90
+ @staticmethod
91
+ def load_conversation(filepath: Union[str, Path]) -> List[Dict[str, str]]:
92
+ """
93
+ Load a previous conversation from a JSON file in the conversations directory.
94
+
95
+ Args:
96
+ filepath: Path to the conversation JSON file
97
+
98
+ Returns:
99
+ List of message dictionaries containing the conversation history
100
+
101
+ Raises:
102
+ FileNotFoundError: If the specified file doesn't exist
103
+ JSONDecodeError: If the file contains invalid JSON
104
+ """
105
+ filepath = Path(filepath)
106
+ if not filepath.is_absolute():
107
+ filepath = Path(CLAUDE_CONVERSATIONS_DIR) / filepath
108
+
109
+ if not filepath.exists():
110
+ filepath.touch(exist_ok=True)
111
+
112
+ try:
113
+ with open(filepath, "r") as f:
114
+ conversation = json.load(f)
115
+
116
+ # Validate conversation format
117
+ if not isinstance(conversation, list):
118
+ raise ValueError("Conversation must be a list of messages")
119
+
120
+ for msg in conversation:
121
+ if (
122
+ not isinstance(msg, dict)
123
+ or "role" not in msg
124
+ or "content" not in msg
125
+ ):
126
+ raise ValueError("Invalid message format in conversation")
127
+
128
+ return conversation
129
+
130
+ except FileNotFoundError:
131
+ logger.error(f"Conversation file not found: {filepath}")
132
+ raise
133
+ except json.JSONDecodeError as e:
134
+ logger.error(f"Invalid JSON in conversation file: {filepath}")
135
+ raise
136
+ except Exception as e:
137
+ logger.error(f"Error loading conversation: {str(e)}")
138
+ raise
139
+
140
+
141
+ @dataclass
142
+ class ChatGPTModel:
143
+ api_key: str = OPENAI_API_KEY
144
+ model: str = "gpt-4.1"
145
+ name: str = "ChatGPT"
146
+
147
+ @staticmethod
148
+ def load_conversation(filepath: Union[str, Path]) -> List[Dict[str, str]]:
149
+ """
150
+ Load a previous conversation from a JSON file in the conversations directory.
151
+
152
+ Args:
153
+ filepath: Path to the conversation JSON file
154
+
155
+ Returns:
156
+ List of message dictionaries containing the conversation history
157
+
158
+ Raises:
159
+ FileNotFoundError: If the specified file doesn't exist
160
+ JSONDecodeError: If the file contains invalid JSON
161
+ """
162
+ filepath = Path(filepath)
163
+ if not filepath.is_absolute():
164
+ filepath = Path(CHATGPT_CONVERSATIONS_DIR) / filepath
165
+
166
+ if not filepath.exists():
167
+ filepath.touch(exist_ok=True)
168
+
169
+ try:
170
+ with open(filepath, "r") as f:
171
+ conversation = json.load(f)
172
+
173
+ # Validate conversation format
174
+ if not isinstance(conversation, list):
175
+ raise ValueError("Conversation must be a list of messages")
176
+
177
+ for msg in conversation:
178
+ if (
179
+ not isinstance(msg, dict)
180
+ or "role" not in msg
181
+ or "content" not in msg
182
+ ):
183
+ raise ValueError("Invalid message format in conversation")
184
+
185
+ return conversation
186
+
187
+ except FileNotFoundError:
188
+ logger.error(f"Conversation file not found: {filepath}")
189
+ raise
190
+ except json.JSONDecodeError as e:
191
+ logger.error(f"Invalid JSON in conversation file: {filepath}")
192
+ raise
193
+ except Exception as e:
194
+ logger.error(f"Error loading conversation: {str(e)}")
195
+ raise
@@ -1,9 +1,15 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: gnarly
3
- Version: 0.0.0.dev3
3
+ Version: 0.0.0.dev5
4
4
  Summary: Add your description here
5
5
  Author-email: "K. LeBryce" <k.lebryce@pm.me>
6
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
7
11
  Requires-Dist: pytest>=8.4.0
8
12
  Requires-Dist: python-dotenv>=1.1.0
13
+ Requires-Dist: sphinx-autobuild>=2024.10.3
14
+ Requires-Dist: sphinx>=8.1.3
9
15
  Requires-Dist: starch
@@ -0,0 +1,16 @@
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,,
@@ -1,18 +0,0 @@
1
- """
2
- Utilities
3
- =========
4
-
5
- A convenient library comprising a collection of simple Python utilities.
6
-
7
- """
8
- from . import io
9
- from .io import stream
10
-
11
-
12
- __all__ = [
13
- # ─── module-level exports ────────────────────────────────────────────────
14
- "io",
15
-
16
- # ─── function-level exports ──────────────────────────────────────────────
17
- "stream"
18
- ]
@@ -1,8 +0,0 @@
1
- gnarly/__init__.py,sha256=tN97EsPLJ6KBKshGJNk4En2sKCWIEpD7bF0k566Md1o,970
2
- gnarly/constants.py,sha256=3tfl2wJ3SmbyL6m355YqEZPfGe-fPZONpoOhwkoIF1Q,2144
3
- gnarly/utilities/__init__.py,sha256=0ElvaTN3irWmzCipE4yJtwFE0EkRGKInff_LUZ8vnl8,543
4
- gnarly/utilities/io.py,sha256=ACUqdsafnZdS9wwm35nUDZfxKOYn8JQDz-GW6sSxUTo,3725
5
- gnarly-0.0.0.dev3.dist-info/METADATA,sha256=bQs58E4Zkpy8Q7vk8E4w0KjGGWNIv0J6ZrP8yOtEI5M,246
6
- gnarly-0.0.0.dev3.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
7
- gnarly-0.0.0.dev3.dist-info/entry_points.txt,sha256=u6QA852MMLgzBBI9pNUz8GUPNSAydvD3m8IXWzFTe50,39
8
- gnarly-0.0.0.dev3.dist-info/RECORD,,