gnarly 0.0.0.dev8__py3-none-any.whl → 0.0.0.dev9__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/utils/code/projects.py +16 -1
- {gnarly-0.0.0.dev8.dist-info → gnarly-0.0.0.dev9.dist-info}/METADATA +1 -1
- {gnarly-0.0.0.dev8.dist-info → gnarly-0.0.0.dev9.dist-info}/RECORD +5 -8
- gnarly/utils/llm/.ipynb_checkpoints/claude-checkpoint.py +0 -98
- gnarly/utils/llm/.ipynb_checkpoints/interfaces-checkpoint.py +0 -293
- gnarly/utils/llm/.ipynb_checkpoints/models-checkpoint.py +0 -192
- {gnarly-0.0.0.dev8.dist-info → gnarly-0.0.0.dev9.dist-info}/WHEEL +0 -0
- {gnarly-0.0.0.dev8.dist-info → gnarly-0.0.0.dev9.dist-info}/entry_points.txt +0 -0
gnarly/utils/code/projects.py
CHANGED
|
@@ -8,6 +8,7 @@ project management.
|
|
|
8
8
|
"""
|
|
9
9
|
import logging
|
|
10
10
|
from os import PathLike
|
|
11
|
+
from pathlib import Path
|
|
11
12
|
|
|
12
13
|
from ...constants import GNARLY_PROJECT_ROOT_PATH
|
|
13
14
|
# from ...errors import NamespaceError
|
|
@@ -89,7 +90,6 @@ class Project(GnarlyNamespace):
|
|
|
89
90
|
name: str = "gnarly_python_project",
|
|
90
91
|
project_type = GnarlyProjectType.PYTHON,
|
|
91
92
|
is_persistent: bool = True,
|
|
92
|
-
root_path: PathLike = GNARLY_PROJECT_ROOT_PATH / "gnarly_project",
|
|
93
93
|
dependencies: dict[str, list[str]] = {
|
|
94
94
|
"dev": [],
|
|
95
95
|
"optional": [],
|
|
@@ -121,6 +121,21 @@ class Project(GnarlyNamespace):
|
|
|
121
121
|
A new instance of ``GnarlyPythonProject``.
|
|
122
122
|
|
|
123
123
|
"""
|
|
124
|
+
root_path = GNARLY_PROJECT_ROOT_PATH / name
|
|
125
|
+
root_path.mkdir(parents=True, exist_ok=True)
|
|
126
|
+
|
|
127
|
+
root_path_filenames: list[str] = [
|
|
128
|
+
"README.md",
|
|
129
|
+
"LICENSE.txt",
|
|
130
|
+
"pyproject.toml"
|
|
131
|
+
]
|
|
132
|
+
for p in root_path_filenames:
|
|
133
|
+
Path(root_path, p).touch(exist_ok=True)
|
|
134
|
+
logger.info(f"Created {p}")
|
|
135
|
+
|
|
136
|
+
core_package_dir: Path = root_path / f"src/{name}"
|
|
137
|
+
core_package_dir.mkdiir(parents=True, exist_ok=True)
|
|
138
|
+
|
|
124
139
|
|
|
125
140
|
return Project.create(
|
|
126
141
|
name=name,
|
|
@@ -5,16 +5,13 @@ gnarly/types.py,sha256=VRw0_ZbEb0HjCzQ5iGsgrbWjeFBDoJPxMwmD2muMYXo,2485
|
|
|
5
5
|
gnarly/utils/__init__.py,sha256=aQgCNp67E4RCnaHfdWZvCi1fcHaLp6CKsQspc1A4t6Q,1285
|
|
6
6
|
gnarly/utils/io.py,sha256=ppkHZJ-n14cN0v9pwNtGVDnB5v7lJgg_C1vpv3bFfd4,6046
|
|
7
7
|
gnarly/utils/code/__init__.py,sha256=j8pQrFwSkzCKklnMlW5QaPbVahMev_AVySyWNSm36n4,553
|
|
8
|
-
gnarly/utils/code/projects.py,sha256=
|
|
8
|
+
gnarly/utils/code/projects.py,sha256=Dp--TKKgyLUhIRZ51gJLzty2ktfXf03sh1sL0uHtOEM,6982
|
|
9
9
|
gnarly/utils/llm/__init__.py,sha256=P51F2pqPeoO_qZpyz9-5TUFPjFm5MYyH4iCqS0RxZ2g,364
|
|
10
10
|
gnarly/utils/llm/chatgpt.py,sha256=v11e76LabKfcOLqb9pKNyvAuo-ra9BjyWw1uIWqZyAE,2781
|
|
11
11
|
gnarly/utils/llm/claude.py,sha256=AaEdgg1tzdj7gmL8LKE9T98VYhZ5jCCkEmsj-_v2LWI,2864
|
|
12
12
|
gnarly/utils/llm/interfaces.py,sha256=Q9vkqtUNXAj79PV9DTr8jdPSZbGM8NCEq2NTjxBHvWo,10437
|
|
13
13
|
gnarly/utils/llm/models.py,sha256=nvAQecw9W9PHoWKeiLG108Hyl-7AG94GbEgBOHgtrcw,5589
|
|
14
|
-
gnarly
|
|
15
|
-
gnarly
|
|
16
|
-
gnarly
|
|
17
|
-
gnarly-0.0.0.
|
|
18
|
-
gnarly-0.0.0.dev8.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
|
|
19
|
-
gnarly-0.0.0.dev8.dist-info/entry_points.txt,sha256=u6QA852MMLgzBBI9pNUz8GUPNSAydvD3m8IXWzFTe50,39
|
|
20
|
-
gnarly-0.0.0.dev8.dist-info/RECORD,,
|
|
14
|
+
gnarly-0.0.0.dev9.dist-info/METADATA,sha256=hPilReY2gWaQNMnlhAWcslysD0fX1URwDQLJoiBUYY0,252
|
|
15
|
+
gnarly-0.0.0.dev9.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
|
|
16
|
+
gnarly-0.0.0.dev9.dist-info/entry_points.txt,sha256=u6QA852MMLgzBBI9pNUz8GUPNSAydvD3m8IXWzFTe50,39
|
|
17
|
+
gnarly-0.0.0.dev9.dist-info/RECORD,,
|
|
@@ -1,98 +0,0 @@
|
|
|
1
|
-
"""Claude REPL
|
|
2
|
-
|
|
3
|
-
Entry point for the Claude REPL.
|
|
4
|
-
"""
|
|
5
|
-
import logging
|
|
6
|
-
from datetime import datetime as dt
|
|
7
|
-
from pathlib import Path
|
|
8
|
-
|
|
9
|
-
from ..io import stream
|
|
10
|
-
from .interfaces import Claude
|
|
11
|
-
from ..llm.models import CLAUDE_CONVERSATIONS_DIR, ClaudeModel
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
logger = logging.getLogger(__name__)
|
|
15
|
-
logging.basicConfig(level=logging.INFO)
|
|
16
|
-
|
|
17
|
-
pp = stream
|
|
18
|
-
|
|
19
|
-
# Helper functions
|
|
20
|
-
def check_for_jupyter() -> bool:
|
|
21
|
-
"""
|
|
22
|
-
check_for_jupyter
|
|
23
|
-
|
|
24
|
-
Evaluates whether the REPL is being invoked within a Jupyter environment.
|
|
25
|
-
"""
|
|
26
|
-
try:
|
|
27
|
-
shell = get_ipython().__class__.__name__
|
|
28
|
-
if shell == 'ZMQInteractiveShell': # Jupyter notebook or qtconsole
|
|
29
|
-
return True
|
|
30
|
-
elif shell == 'TerminalInteractiveShell': # Terminal IPython
|
|
31
|
-
return False
|
|
32
|
-
else:
|
|
33
|
-
return False
|
|
34
|
-
except NameError: # Likely standard Python interpreter
|
|
35
|
-
return False
|
|
36
|
-
|
|
37
|
-
def main() -> bool:
|
|
38
|
-
"""
|
|
39
|
-
main
|
|
40
|
-
|
|
41
|
-
Runloop for the Claude REPL.
|
|
42
|
-
"""
|
|
43
|
-
exit_commands: list = ["quit", "exit", "q", "e", "x"]
|
|
44
|
-
save_command: str = "save"
|
|
45
|
-
load_command: str = "load"
|
|
46
|
-
is_jupyter = check_for_jupyter()
|
|
47
|
-
|
|
48
|
-
# Instantiate the Claude interface
|
|
49
|
-
claude = Claude()
|
|
50
|
-
|
|
51
|
-
try:
|
|
52
|
-
while True:
|
|
53
|
-
pp("[You]") # No newline after [You]
|
|
54
|
-
prompt = input() # Get input on same line
|
|
55
|
-
|
|
56
|
-
if is_jupyter:
|
|
57
|
-
pp("\n\n[You]")
|
|
58
|
-
pp(prompt)
|
|
59
|
-
pp("\n")
|
|
60
|
-
|
|
61
|
-
# Check for exit command
|
|
62
|
-
if prompt.lower() in exit_commands:
|
|
63
|
-
pp("Goodbye!")
|
|
64
|
-
return True
|
|
65
|
-
|
|
66
|
-
# Check for save command
|
|
67
|
-
if prompt.lower() == save_command:
|
|
68
|
-
claude.save(save_as=Path(
|
|
69
|
-
f"{CLAUDE_CONVERSATIONS_DIR}/{dt.now().strftime('%Y-%m-%d_%H%M%S')}.json"
|
|
70
|
-
))
|
|
71
|
-
pp("Conversation saved!")
|
|
72
|
-
continue
|
|
73
|
-
|
|
74
|
-
# Check for load command
|
|
75
|
-
if prompt.lower().startswith(load_command):
|
|
76
|
-
try:
|
|
77
|
-
# Extract the filepath from the command
|
|
78
|
-
filepath = prompt[len(load_command):].strip().strip("'\"")
|
|
79
|
-
if filepath:
|
|
80
|
-
# Load the conversation
|
|
81
|
-
claude.conversation = ClaudeModel.load_conversation(filepath)
|
|
82
|
-
pp(f"Loaded conversation from {filepath}")
|
|
83
|
-
continue
|
|
84
|
-
else:
|
|
85
|
-
pp("Please provide a filepath to load")
|
|
86
|
-
continue
|
|
87
|
-
except Exception as e:
|
|
88
|
-
pp(f"Error loading conversation: {e}")
|
|
89
|
-
continue
|
|
90
|
-
|
|
91
|
-
response = claude.message(prompt)[0]["content"]
|
|
92
|
-
pp("\n\n[Claude]")
|
|
93
|
-
pp(response)
|
|
94
|
-
pp("\n")
|
|
95
|
-
|
|
96
|
-
except KeyboardInterrupt:
|
|
97
|
-
pp("Goodbye!")
|
|
98
|
-
return True
|
|
@@ -1,293 +0,0 @@
|
|
|
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
|
-
import urllib.request
|
|
12
|
-
import urllib.parse
|
|
13
|
-
from datetime import datetime as dt
|
|
14
|
-
from pathlib import Path
|
|
15
|
-
from typing import Dict, List, Tuple, TYPE_CHECKING, Union
|
|
16
|
-
if TYPE_CHECKING:
|
|
17
|
-
from _typeshed import SupportsWrite
|
|
18
|
-
|
|
19
|
-
# third-party imports
|
|
20
|
-
from dotenv import load_dotenv
|
|
21
|
-
from platformdirs import user_config_path
|
|
22
|
-
|
|
23
|
-
# local imports
|
|
24
|
-
from .models import (
|
|
25
|
-
CHATGPT_CONVERSATIONS_DIR, CLAUDE_CONVERSATIONS_DIR,
|
|
26
|
-
ClaudeModel, ChatGPTModel
|
|
27
|
-
)
|
|
28
|
-
|
|
29
|
-
# ─── logger setup ──────────────────────────────────────────────────────── ✦ ─
|
|
30
|
-
logger = logging.getLogger(__name__)
|
|
31
|
-
logging.basicConfig(level=logging.INFO)
|
|
32
|
-
|
|
33
|
-
# ─── constants ─────────────────────────────────────────────────────────── ✦ ─
|
|
34
|
-
APP_NAME = "gnarly"
|
|
35
|
-
APP_AUTHOR = "k.lebryce"
|
|
36
|
-
APP_CONFIG_DIR: Path = user_config_path(
|
|
37
|
-
APP_NAME, APP_AUTHOR, ensure_exists=True
|
|
38
|
-
)
|
|
39
|
-
|
|
40
|
-
# load environment variables from .env file
|
|
41
|
-
try:
|
|
42
|
-
load_dotenv(Path(APP_CONFIG_DIR, ".env").resolve())
|
|
43
|
-
except FileNotFoundError:
|
|
44
|
-
APP_CONFIG_DIR.mkdir(parents=True, exist_ok=True)
|
|
45
|
-
Path(APP_CONFIG_DIR, ".env").touch()
|
|
46
|
-
except IOError as e:
|
|
47
|
-
raise IOError(
|
|
48
|
-
"Failed to load environment variables from .env file."
|
|
49
|
-
) from e
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
# ─── interfaces ──────────────────────────────────────────────────────── ✦✦ ──
|
|
53
|
-
class Claude(ClaudeModel):
|
|
54
|
-
def __init__(
|
|
55
|
-
self,
|
|
56
|
-
system_prompt: str = "You are Claude, a friendly AI assistant."
|
|
57
|
-
):
|
|
58
|
-
super().__init__()
|
|
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
|
-
|
|
63
|
-
self.conversation: List[Dict] = []
|
|
64
|
-
self.max_tokens: int = 4096
|
|
65
|
-
self.system_prompt = system_prompt
|
|
66
|
-
self.temperature: float = 0.2
|
|
67
|
-
|
|
68
|
-
# Ensure save_to is a Path object
|
|
69
|
-
self.save_to = Path(CLAUDE_CONVERSATIONS_DIR)
|
|
70
|
-
|
|
71
|
-
# Create directory if it doesn't exist
|
|
72
|
-
self.save_to.parent.mkdir(parents=True, exist_ok=True)
|
|
73
|
-
logger.info(f"Conversation will be saved to {self.save_to}")
|
|
74
|
-
|
|
75
|
-
def message(self, msg: str) -> Tuple[Dict, Dict]:
|
|
76
|
-
"""
|
|
77
|
-
Creates a payload using the `msg` string and returns Claude's
|
|
78
|
-
response as a string.
|
|
79
|
-
"""
|
|
80
|
-
self.conversation.append({"role": "user", "content": msg})
|
|
81
|
-
|
|
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
|
|
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
|
|
116
|
-
|
|
117
|
-
# Extract response content
|
|
118
|
-
response_content = result["content"][0]["text"]
|
|
119
|
-
response = {"role": "assistant", "content": response_content}
|
|
120
|
-
self.conversation.append(response)
|
|
121
|
-
|
|
122
|
-
return response, result
|
|
123
|
-
|
|
124
|
-
def save(self, save_as: Union[str, Path] = None) -> int:
|
|
125
|
-
"""
|
|
126
|
-
Save the current conversation to a file.
|
|
127
|
-
|
|
128
|
-
Args:
|
|
129
|
-
save_as: Optional path to save the conversation. If not provided,
|
|
130
|
-
uses the default path from initialization.
|
|
131
|
-
|
|
132
|
-
Returns:
|
|
133
|
-
0 on success, 1 on failure
|
|
134
|
-
"""
|
|
135
|
-
try:
|
|
136
|
-
target_path = Path(save_as) if save_as else self.save_to
|
|
137
|
-
if not target_path.is_absolute():
|
|
138
|
-
target_path = Path(CLAUDE_CONVERSATIONS_DIR) / target_path
|
|
139
|
-
|
|
140
|
-
target_path.parent.mkdir(parents=True, exist_ok=True)
|
|
141
|
-
|
|
142
|
-
with open(target_path, "w") as f:
|
|
143
|
-
json.dump(self.conversation, f, indent=4)
|
|
144
|
-
logger.info(f"Successfully saved conversation to {target_path}")
|
|
145
|
-
return 0
|
|
146
|
-
|
|
147
|
-
except Exception as e:
|
|
148
|
-
logger.error(f"Failed to save conversation: {str(e)}")
|
|
149
|
-
return 1
|
|
150
|
-
|
|
151
|
-
class ChatGPT(ChatGPTModel):
|
|
152
|
-
"""A turn-based, chat-like interface for the OpenAI API via HTTP requests.
|
|
153
|
-
|
|
154
|
-
This class's attributes are automatically defined on instantiation.
|
|
155
|
-
|
|
156
|
-
Attributes:
|
|
157
|
-
api_key:
|
|
158
|
-
A string representing the OpenAI API key.
|
|
159
|
-
conversation:
|
|
160
|
-
A list of dictionaries representing each message exchanged
|
|
161
|
-
with ChatGPT over the course of the instance's lifetime.
|
|
162
|
-
model:
|
|
163
|
-
A string representing the ChatGPT model to be called on
|
|
164
|
-
invocation of the `message` method.
|
|
165
|
-
max_tokens:
|
|
166
|
-
An integer representing the maximum number of tokens that
|
|
167
|
-
the model should output.
|
|
168
|
-
save_to:
|
|
169
|
-
A `Path` object representing the directory to which the
|
|
170
|
-
contents of the `conversation` attribute should be written.
|
|
171
|
-
temperature:
|
|
172
|
-
A float representing the degree of "randomness" that the model
|
|
173
|
-
should leverage in generating its response.
|
|
174
|
-
"""
|
|
175
|
-
|
|
176
|
-
def __init__(
|
|
177
|
-
self,
|
|
178
|
-
model: str = "gpt-4",
|
|
179
|
-
instructions: str = "You are ChatGPT, a helpful AI assistant."
|
|
180
|
-
) -> None:
|
|
181
|
-
"""Initialize a `ChatGPT` instance.
|
|
182
|
-
|
|
183
|
-
Args:
|
|
184
|
-
model (str):
|
|
185
|
-
A string representing the ChatGPT model to be called.
|
|
186
|
-
Defaults to "gpt-4".
|
|
187
|
-
instructions (str):
|
|
188
|
-
A string representing the system prompt to be used.
|
|
189
|
-
Defaults to "You are ChatGPT, a helpful AI assistant.".
|
|
190
|
-
|
|
191
|
-
Returns:
|
|
192
|
-
`None`.
|
|
193
|
-
"""
|
|
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
|
-
|
|
199
|
-
self.conversation: List[Dict] = []
|
|
200
|
-
self.model: str = model
|
|
201
|
-
self.instructions: str = instructions
|
|
202
|
-
self.max_tokens: int = 4096
|
|
203
|
-
self.save_to: Path = Path(CHATGPT_CONVERSATIONS_DIR)
|
|
204
|
-
self.temperature: float = 0.2
|
|
205
|
-
|
|
206
|
-
# Ensure that the conversations directory exists.
|
|
207
|
-
self.save_to.parent.mkdir(parents=True, exist_ok=True)
|
|
208
|
-
|
|
209
|
-
def message(self, msg: str) -> str:
|
|
210
|
-
"""Send a message to ChatGPT.
|
|
211
|
-
|
|
212
|
-
This method calls OpenAI's Chat Completions API via HTTP request.
|
|
213
|
-
|
|
214
|
-
Args:
|
|
215
|
-
msg: A string representing the message to be sent.
|
|
216
|
-
|
|
217
|
-
Returns:
|
|
218
|
-
The response text from ChatGPT.
|
|
219
|
-
"""
|
|
220
|
-
self.conversation.append({"role": "user", "content": msg})
|
|
221
|
-
|
|
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
|
-
|
|
265
|
-
def save(
|
|
266
|
-
self,
|
|
267
|
-
save_as: Union[str, Path] = None
|
|
268
|
-
) -> int:
|
|
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}")
|
|
288
|
-
json.dump(self.conversation, f, indent=4)
|
|
289
|
-
logger.info("Success.")
|
|
290
|
-
return 0
|
|
291
|
-
except Exception as e:
|
|
292
|
-
logger.error(f"Error: Failed to save conversation: {str(e)}")
|
|
293
|
-
return 1
|
|
@@ -1,192 +0,0 @@
|
|
|
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 dotenv import load_dotenv
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
# Set up logging.
|
|
23
|
-
logger = logging.getLogger(__name__)
|
|
24
|
-
logging.basicConfig(level=logging.INFO)
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
# Create LLM data directories as needed.
|
|
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)
|
|
33
|
-
if not llm_directory.exists():
|
|
34
|
-
llm_directory.mkdir(parents=True, exist_ok=True)
|
|
35
|
-
if not dotenv_path.exists():
|
|
36
|
-
dotenv_path.touch(exist_ok=True)
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
# Load environment variables.
|
|
40
|
-
load_dotenv(dotenv_path)
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
# Getting API keys from environment
|
|
44
|
-
ANTHROPIC_API_KEY = os.getenv("ANTHROPIC_API_KEY")
|
|
45
|
-
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
# Get LLM conversation directories.
|
|
49
|
-
CLAUDE_CONVERSATIONS_DIR = Path(
|
|
50
|
-
os.getenv(
|
|
51
|
-
"CLAUDE_CONVERSATIONS_DIR",
|
|
52
|
-
str(llm_directory / "claude/conversations")
|
|
53
|
-
)
|
|
54
|
-
)
|
|
55
|
-
|
|
56
|
-
CHATGPT_CONVERSATIONS_DIR = Path(
|
|
57
|
-
os.getenv(
|
|
58
|
-
"CHATGPT_CONVERSATIONS_DIR",
|
|
59
|
-
str(llm_directory / "chatgpt/conversations")
|
|
60
|
-
)
|
|
61
|
-
)
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
class LLM(Protocol):
|
|
65
|
-
"""
|
|
66
|
-
Defines the attributes required for conformance to the LLM protocol.
|
|
67
|
-
"""
|
|
68
|
-
|
|
69
|
-
api_key: str
|
|
70
|
-
name: str
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
@dataclass
|
|
74
|
-
class ClaudeModel:
|
|
75
|
-
api_key: str = ANTHROPIC_API_KEY
|
|
76
|
-
model: str = "claude-3-5-sonnet-20241022"
|
|
77
|
-
name: str = "Claude"
|
|
78
|
-
|
|
79
|
-
@staticmethod
|
|
80
|
-
def load_conversation(filepath: Union[str, Path]) -> List[Dict[str, str]]:
|
|
81
|
-
"""
|
|
82
|
-
Load a previous conversation from a JSON file in the conversations directory.
|
|
83
|
-
|
|
84
|
-
Args:
|
|
85
|
-
filepath: Path to the conversation JSON file
|
|
86
|
-
|
|
87
|
-
Returns:
|
|
88
|
-
List of message dictionaries containing the conversation history
|
|
89
|
-
|
|
90
|
-
Raises:
|
|
91
|
-
FileNotFoundError: If the specified file doesn't exist
|
|
92
|
-
JSONDecodeError: If the file contains invalid JSON
|
|
93
|
-
"""
|
|
94
|
-
filepath = Path(filepath)
|
|
95
|
-
if not filepath.is_absolute():
|
|
96
|
-
filepath = Path(CLAUDE_CONVERSATIONS_DIR) / filepath
|
|
97
|
-
|
|
98
|
-
if not filepath.exists():
|
|
99
|
-
filepath.parent.mkdir(parents=True, exist_ok=True)
|
|
100
|
-
filepath.touch(exist_ok=True)
|
|
101
|
-
|
|
102
|
-
try:
|
|
103
|
-
with open(filepath, "r") as f:
|
|
104
|
-
content = f.read().strip()
|
|
105
|
-
if not content:
|
|
106
|
-
return []
|
|
107
|
-
conversation = json.loads(content)
|
|
108
|
-
|
|
109
|
-
# Validate conversation format
|
|
110
|
-
if not isinstance(conversation, list):
|
|
111
|
-
raise ValueError("Conversation must be a list of messages")
|
|
112
|
-
|
|
113
|
-
for msg in conversation:
|
|
114
|
-
if (
|
|
115
|
-
not isinstance(msg, dict)
|
|
116
|
-
or "role" not in msg
|
|
117
|
-
or "content" not in msg
|
|
118
|
-
):
|
|
119
|
-
raise ValueError("Invalid message format in conversation")
|
|
120
|
-
|
|
121
|
-
return conversation
|
|
122
|
-
|
|
123
|
-
except FileNotFoundError:
|
|
124
|
-
logger.error(f"Conversation file not found: {filepath}")
|
|
125
|
-
raise
|
|
126
|
-
except json.JSONDecodeError as e:
|
|
127
|
-
logger.error(f"Invalid JSON in conversation file: {filepath}")
|
|
128
|
-
raise
|
|
129
|
-
except Exception as e:
|
|
130
|
-
logger.error(f"Error loading conversation: {str(e)}")
|
|
131
|
-
raise
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
@dataclass
|
|
135
|
-
class ChatGPTModel:
|
|
136
|
-
api_key: str = OPENAI_API_KEY
|
|
137
|
-
model: str = "gpt-4"
|
|
138
|
-
name: str = "ChatGPT"
|
|
139
|
-
|
|
140
|
-
@staticmethod
|
|
141
|
-
def load_conversation(filepath: Union[str, Path]) -> List[Dict[str, str]]:
|
|
142
|
-
"""
|
|
143
|
-
Load a previous conversation from a JSON file in the conversations directory.
|
|
144
|
-
|
|
145
|
-
Args:
|
|
146
|
-
filepath: Path to the conversation JSON file
|
|
147
|
-
|
|
148
|
-
Returns:
|
|
149
|
-
List of message dictionaries containing the conversation history
|
|
150
|
-
|
|
151
|
-
Raises:
|
|
152
|
-
FileNotFoundError: If the specified file doesn't exist
|
|
153
|
-
JSONDecodeError: If the file contains invalid JSON
|
|
154
|
-
"""
|
|
155
|
-
filepath = Path(filepath)
|
|
156
|
-
if not filepath.is_absolute():
|
|
157
|
-
filepath = Path(CHATGPT_CONVERSATIONS_DIR) / filepath
|
|
158
|
-
|
|
159
|
-
if not filepath.exists():
|
|
160
|
-
filepath.parent.mkdir(parents=True, exist_ok=True)
|
|
161
|
-
filepath.touch(exist_ok=True)
|
|
162
|
-
|
|
163
|
-
try:
|
|
164
|
-
with open(filepath, "r") as f:
|
|
165
|
-
content = f.read().strip()
|
|
166
|
-
if not content:
|
|
167
|
-
return []
|
|
168
|
-
conversation = json.loads(content)
|
|
169
|
-
|
|
170
|
-
# Validate conversation format
|
|
171
|
-
if not isinstance(conversation, list):
|
|
172
|
-
raise ValueError("Conversation must be a list of messages")
|
|
173
|
-
|
|
174
|
-
for msg in conversation:
|
|
175
|
-
if (
|
|
176
|
-
not isinstance(msg, dict)
|
|
177
|
-
or "role" not in msg
|
|
178
|
-
or "content" not in msg
|
|
179
|
-
):
|
|
180
|
-
raise ValueError("Invalid message format in conversation")
|
|
181
|
-
|
|
182
|
-
return conversation
|
|
183
|
-
|
|
184
|
-
except FileNotFoundError:
|
|
185
|
-
logger.error(f"Conversation file not found: {filepath}")
|
|
186
|
-
raise
|
|
187
|
-
except json.JSONDecodeError as e:
|
|
188
|
-
logger.error(f"Invalid JSON in conversation file: {filepath}")
|
|
189
|
-
raise
|
|
190
|
-
except Exception as e:
|
|
191
|
-
logger.error(f"Error loading conversation: {str(e)}")
|
|
192
|
-
raise
|
|
File without changes
|
|
File without changes
|