gnarly 0.0.0.dev8__py3-none-any.whl → 0.0.0.dev10__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.

@@ -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,
@@ -51,13 +51,53 @@ except IOError as e:
51
51
 
52
52
  # ─── interfaces ──────────────────────────────────────────────────────── ✦✦ ──
53
53
  class Claude(ClaudeModel):
54
+ """
55
+ Interface for interacting with Claude AI via the Anthropic API.
56
+
57
+ This class provides a conversational interface to Claude, maintaining
58
+ conversation history and handling API communication.
59
+
60
+ Parameters
61
+ ----------
62
+ system_prompt : str, optional
63
+ The system prompt to use for conversations, by default
64
+ "You are Claude, a friendly AI assistant."
65
+
66
+ Attributes
67
+ ----------
68
+ api_key : str
69
+ The Anthropic API key retrieved from environment variables.
70
+ conversation : List[Dict]
71
+ List of conversation messages with 'role' and 'content' keys.
72
+ max_tokens : int
73
+ Maximum number of tokens for responses, by default 4096.
74
+ system_prompt : str
75
+ The system prompt used for conversations.
76
+ temperature : float
77
+ Sampling temperature for response generation, by default 0.2.
78
+ save_to : Path
79
+ Directory path where conversations are saved.
80
+
81
+ Raises
82
+ ------
83
+ ValueError
84
+ If ANTHROPIC_API_KEY environment variable is not set.
85
+
86
+ Examples
87
+ --------
88
+ >>> claude = Claude()
89
+ >>> response, full_result = claude.message("Hello!")
90
+ >>> print(response['content'])
91
+ Hello! How can I help you today?
92
+ """
93
+
54
94
  def __init__(
55
95
  self,
56
96
  system_prompt: str = "You are Claude, a friendly AI assistant."
57
97
  ):
58
98
  super().__init__()
59
- self.api_key: str = self.api_key or os.getenv("ANTHROPIC_API_KEY")
60
- if not self.api_key:
99
+ self._api_key = self.api_key or os.getenv("ANTHROPIC_API_KEY", "")
100
+ if not self._api_key:
61
101
  raise ValueError("ANTHROPIC_API_KEY environment variable is required")
62
102
 
63
103
  self.conversation: List[Dict] = []
@@ -71,11 +111,48 @@ class Claude(ClaudeModel):
71
111
  # Create directory if it doesn't exist
72
112
  self.save_to.parent.mkdir(parents=True, exist_ok=True)
73
113
  logger.info(f"Conversation will be saved to {self.save_to}")
114
+
115
+ @property
116
+ def api_key(self) -> str:
117
+ """
118
+ Get the API key (masked for security).
119
+
120
+ Returns
121
+ -------
122
+ str
123
+ Masked API key string.
124
+ """
125
+ if hasattr(self, '_api_key') and self._api_key:
126
+ return f"sk-...{self._api_key[-4:]}" if len(self._api_key) > 4 else "***"
127
+ return ""
74
128
 
75
129
  def message(self, msg: str) -> Tuple[Dict, Dict]:
76
130
  """
77
- Creates a payload using the `msg` string and returns Claude's
78
- response as a string.
131
+ Send a message to Claude and get a response.
132
+
133
+ Parameters
134
+ ----------
135
+ msg : str
136
+ The message to send to Claude.
137
+
138
+ Returns
139
+ -------
140
+ Tuple[Dict, Dict]
141
+ A tuple containing:
142
+ - response: Dict with 'role' and 'content' keys
143
+ - full_result: Complete API response dictionary
144
+
145
+ Raises
146
+ ------
147
+ Exception
148
+ If the API request fails or returns an error.
149
+
150
+ Examples
151
+ --------
152
+ >>> claude = Claude()
153
+ >>> response, result = claude.message("What is 2+2?")
154
+ >>> print(response['content'])
155
+ 2 + 2 = 4
79
156
  """
80
157
  self.conversation.append({"role": "user", "content": msg})
81
158
 
@@ -91,7 +168,7 @@ class Claude(ClaudeModel):
91
168
  }
92
169
 
93
170
  headers = {
94
- "x-api-key": self.api_key,
171
+ "x-api-key": self._api_key,
95
172
  "Content-Type": "application/json",
96
173
  "anthropic-version": "2023-06-01"
97
174
  }
@@ -123,14 +200,27 @@ class Claude(ClaudeModel):
123
200
 
124
201
  def save(self, save_as: Union[str, Path] = None) -> int:
125
202
  """
126
- Save the current conversation to a file.
203
+ Save the current conversation to a JSON file.
127
204
 
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
205
+ Parameters
206
+ ----------
207
+ save_as : Union[str, Path], optional
208
+ Path to save the conversation. If not provided, uses the default
209
+ path from initialization. Relative paths are resolved relative
210
+ to the Claude conversations directory.
211
+
212
+ Returns
213
+ -------
214
+ int
215
+ 0 on success, 1 on failure.
216
+
217
+ Examples
218
+ --------
219
+ >>> claude = Claude()
220
+ >>> claude.message("Hello")
221
+ >>> result = claude.save("my_conversation.json")
222
+ >>> print(result)
223
+ 0
134
224
  """
135
225
  try:
136
226
  target_path = Path(save_as) if save_as else self.save_to
@@ -148,29 +238,52 @@ class Claude(ClaudeModel):
148
238
  logger.error(f"Failed to save conversation: {str(e)}")
149
239
  return 1
150
240
 
241
+
151
242
  class ChatGPT(ChatGPTModel):
152
- """A turn-based, chat-like interface for the OpenAI API via HTTP requests.
243
+ """
244
+ A turn-based, chat-like interface for the OpenAI API.
153
245
 
154
- This class's attributes are automatically defined on instantiation.
246
+ This class provides a conversational interface to ChatGPT models,
247
+ maintaining conversation history and handling API communication
248
+ via HTTP requests.
155
249
 
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.
250
+ Parameters
251
+ ----------
252
+ model : str, optional
253
+ The ChatGPT model identifier to use, by default "gpt-4".
254
+ instructions : str, optional
255
+ The system prompt/instructions for the model, by default
256
+ "You are ChatGPT, a helpful AI assistant.".
257
+
258
+ Attributes
259
+ ----------
260
+ api_key : str
261
+ The OpenAI API key retrieved from environment variables.
262
+ conversation : List[Dict]
263
+ List of message dictionaries representing the conversation history.
264
+ Each message has 'role' and 'content' keys.
265
+ model : str
266
+ The ChatGPT model identifier.
267
+ instructions : str
268
+ The system instructions/prompt.
269
+ max_tokens : int
270
+ Maximum number of tokens for model output, by default 4096.
271
+ save_to : Path
272
+ Directory path where conversations are saved.
273
+ temperature : float
274
+ Sampling temperature for response randomness, by default 0.2.
275
+
276
+ Raises
277
+ ------
278
+ ValueError
279
+ If OPENAI_API_KEY environment variable is not set.
280
+
281
+ Examples
282
+ --------
283
+ >>> chatgpt = ChatGPT(model="gpt-4", instructions="You are a helpful assistant.")
284
+ >>> response = chatgpt.message("Hello!")
285
+ >>> print(response)
286
+ Hello! How can I help you today?
174
287
  """
175
288
 
176
289
  def __init__(
@@ -178,22 +291,9 @@ class ChatGPT(ChatGPTModel):
178
291
  model: str = "gpt-4",
179
292
  instructions: str = "You are ChatGPT, a helpful AI assistant."
180
293
  ) -> 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
294
  super().__init__()
195
- self.api_key: str = self.api_key or os.getenv("OPENAI_API_KEY")
196
- if not self.api_key:
295
+ self._api_key = self.api_key or os.getenv("OPENAI_API_KEY", "")
296
+ if not self._api_key:
197
297
  raise ValueError("OPENAI_API_KEY environment variable is required")
198
298
 
199
299
  self.conversation: List[Dict] = []
@@ -205,17 +305,48 @@ class ChatGPT(ChatGPTModel):
205
305
 
206
306
  # Ensure that the conversations directory exists.
207
307
  self.save_to.parent.mkdir(parents=True, exist_ok=True)
308
+
309
+ @property
310
+ def api_key(self) -> str:
311
+ """
312
+ Get the API key (masked for security).
313
+
314
+ Returns
315
+ -------
316
+ str
317
+ Masked API key string.
318
+ """
319
+ if hasattr(self, '_api_key') and self._api_key:
320
+ return f"sk-...{self._api_key[-4:]}" if len(self._api_key) > 4 else "***"
321
+ return ""
208
322
 
209
323
  def message(self, msg: str) -> str:
210
- """Send a message to ChatGPT.
324
+ """
325
+ Send a message to ChatGPT and get a response.
211
326
 
212
327
  This method calls OpenAI's Chat Completions API via HTTP request.
213
328
 
214
- Args:
215
- msg: A string representing the message to be sent.
329
+ Parameters
330
+ ----------
331
+ msg : str
332
+ The message to be sent to ChatGPT.
216
333
 
217
- Returns:
334
+ Returns
335
+ -------
336
+ str
218
337
  The response text from ChatGPT.
338
+
339
+ Raises
340
+ ------
341
+ Exception
342
+ If the API request fails or returns an error.
343
+
344
+ Examples
345
+ --------
346
+ >>> chatgpt = ChatGPT()
347
+ >>> response = chatgpt.message("What is the capital of France?")
348
+ >>> print(response)
349
+ The capital of France is Paris.
219
350
  """
220
351
  self.conversation.append({"role": "user", "content": msg})
221
352
 
@@ -233,7 +364,7 @@ class ChatGPT(ChatGPTModel):
233
364
  }
234
365
 
235
366
  headers = {
236
- "Authorization": f"Bearer {self.api_key}",
367
+ "Authorization": f"Bearer {self._api_key}",
237
368
  "Content-Type": "application/json"
238
369
  }
239
370
 
@@ -266,13 +397,27 @@ class ChatGPT(ChatGPTModel):
266
397
  self,
267
398
  save_as: Union[str, Path] = None
268
399
  ) -> int:
269
- """Save the current conversation to a file.
400
+ """
401
+ Save the current conversation to a JSON file.
270
402
 
271
- Args:
272
- save_as: Optional path to save the conversation.
403
+ Parameters
404
+ ----------
405
+ save_as : Union[str, Path], optional
406
+ Path to save the conversation. If not provided, generates
407
+ a timestamped filename in the default conversations directory.
273
408
 
274
- Returns:
275
- 0 on success, 1 on failure
409
+ Returns
410
+ -------
411
+ int
412
+ 0 on success, 1 on failure.
413
+
414
+ Examples
415
+ --------
416
+ >>> chatgpt = ChatGPT()
417
+ >>> chatgpt.message("Hello")
418
+ >>> result = chatgpt.save("my_conversation.json")
419
+ >>> print(result)
420
+ 0
276
421
  """
277
422
  if save_as is None:
278
423
  save_as = Path(
@@ -40,9 +40,9 @@ if not dotenv_path.exists():
40
40
  load_dotenv(dotenv_path)
41
41
 
42
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")
43
+ # Getting API keys from environment - masked for security
44
+ ANTHROPIC_API_KEY = os.getenv("ANTHROPIC_API_KEY", "")
45
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY", "")
46
46
 
47
47
 
48
48
  # Get LLM conversation directories.
@@ -63,7 +63,14 @@ CHATGPT_CONVERSATIONS_DIR = Path(
63
63
 
64
64
  class LLM(Protocol):
65
65
  """
66
- Defines the attributes required for conformance to the LLM protocol.
66
+ Protocol defining the attributes required for LLM conformance.
67
+
68
+ Attributes
69
+ ----------
70
+ api_key : str
71
+ The API key for the LLM service.
72
+ name : str
73
+ The name of the LLM model.
67
74
  """
68
75
 
69
76
  api_key: str
@@ -72,24 +79,67 @@ class LLM(Protocol):
72
79
 
73
80
  @dataclass
74
81
  class ClaudeModel:
75
- api_key: str = ANTHROPIC_API_KEY
82
+ """
83
+ Data class representing a Claude model configuration.
84
+
85
+ Parameters
86
+ ----------
87
+ api_key : str, optional
88
+ The Anthropic API key. Retrieved from environment if not provided.
89
+ model : str, optional
90
+ The Claude model identifier, by default "claude-3-5-sonnet-20241022".
91
+ name : str, optional
92
+ The model name, by default "Claude".
93
+
94
+ Attributes
95
+ ----------
96
+ api_key : str
97
+ The Anthropic API key.
98
+ model : str
99
+ The Claude model identifier.
100
+ name : str
101
+ The model name.
102
+ """
103
+ api_key: str = "" # Will be set from environment in __post_init__
76
104
  model: str = "claude-3-5-sonnet-20241022"
77
105
  name: str = "Claude"
106
+
107
+ def __post_init__(self):
108
+ """Initialize API key from environment if not provided."""
109
+ if not self.api_key:
110
+ self.api_key = ANTHROPIC_API_KEY
78
111
 
79
112
  @staticmethod
80
113
  def load_conversation(filepath: Union[str, Path]) -> List[Dict[str, str]]:
81
114
  """
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
115
+ Load a previous conversation from a JSON file.
116
+
117
+ Parameters
118
+ ----------
119
+ filepath : Union[str, Path]
120
+ Path to the conversation JSON file. If relative, will be resolved
121
+ relative to the Claude conversations directory.
122
+
123
+ Returns
124
+ -------
125
+ List[Dict[str, str]]
126
+ List of message dictionaries containing the conversation history.
127
+ Each dictionary has 'role' and 'content' keys.
128
+
129
+ Raises
130
+ ------
131
+ FileNotFoundError
132
+ If the specified file doesn't exist.
133
+ json.JSONDecodeError
134
+ If the file contains invalid JSON.
135
+ ValueError
136
+ If the conversation format is invalid.
137
+
138
+ Examples
139
+ --------
140
+ >>> messages = ClaudeModel.load_conversation("my_chat.json")
141
+ >>> print(len(messages))
142
+ 5
93
143
  """
94
144
  filepath = Path(filepath)
95
145
  if not filepath.is_absolute():
@@ -133,24 +183,67 @@ class ClaudeModel:
133
183
 
134
184
  @dataclass
135
185
  class ChatGPTModel:
136
- api_key: str = OPENAI_API_KEY
186
+ """
187
+ Data class representing a ChatGPT model configuration.
188
+
189
+ Parameters
190
+ ----------
191
+ api_key : str, optional
192
+ The OpenAI API key. Retrieved from environment if not provided.
193
+ model : str, optional
194
+ The GPT model identifier, by default "gpt-4".
195
+ name : str, optional
196
+ The model name, by default "ChatGPT".
197
+
198
+ Attributes
199
+ ----------
200
+ api_key : str
201
+ The OpenAI API key.
202
+ model : str
203
+ The GPT model identifier.
204
+ name : str
205
+ The model name.
206
+ """
207
+ api_key: str = "" # Will be set from environment in __post_init__
137
208
  model: str = "gpt-4"
138
209
  name: str = "ChatGPT"
210
+
211
+ def __post_init__(self):
212
+ """Initialize API key from environment if not provided."""
213
+ if not self.api_key:
214
+ self.api_key = OPENAI_API_KEY
139
215
 
140
216
  @staticmethod
141
217
  def load_conversation(filepath: Union[str, Path]) -> List[Dict[str, str]]:
142
218
  """
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
219
+ Load a previous conversation from a JSON file.
220
+
221
+ Parameters
222
+ ----------
223
+ filepath : Union[str, Path]
224
+ Path to the conversation JSON file. If relative, will be resolved
225
+ relative to the ChatGPT conversations directory.
226
+
227
+ Returns
228
+ -------
229
+ List[Dict[str, str]]
230
+ List of message dictionaries containing the conversation history.
231
+ Each dictionary has 'role' and 'content' keys.
232
+
233
+ Raises
234
+ ------
235
+ FileNotFoundError
236
+ If the specified file doesn't exist.
237
+ json.JSONDecodeError
238
+ If the file contains invalid JSON.
239
+ ValueError
240
+ If the conversation format is invalid.
241
+
242
+ Examples
243
+ --------
244
+ >>> messages = ChatGPTModel.load_conversation("my_chat.json")
245
+ >>> print(len(messages))
246
+ 3
154
247
  """
155
248
  filepath = Path(filepath)
156
249
  if not filepath.is_absolute():
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: gnarly
3
- Version: 0.0.0.dev8
3
+ Version: 0.0.0.dev10
4
4
  Summary: A sophisticated, general-use abstraction layer for the lazy.
5
5
  Author-email: "K. LeBryce" <k.lebryce@pm.me>
6
6
  Requires-Python: >=3.10
@@ -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=VRw0_ZbEb0HjCzQ5iGsgrbWjeFBDoJPxMwmD2muMYXo,2485
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=Dp--TKKgyLUhIRZ51gJLzty2ktfXf03sh1sL0uHtOEM,6982
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=DSuxpzInemp_nftyPZehKSYJZbBOMdxFqCyGQEEFNIk,14374
13
+ gnarly/utils/llm/models.py,sha256=r0Z2GgzepY5xZyOcPjaIzfs4DbcxsHFazxthTK_48U0,8220
14
+ gnarly-0.0.0.dev10.dist-info/METADATA,sha256=S1kur3FqmKU39zyQZLT9eDpBhQleqq7v7X9YK2i-AHI,253
15
+ gnarly-0.0.0.dev10.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
16
+ gnarly-0.0.0.dev10.dist-info/entry_points.txt,sha256=u6QA852MMLgzBBI9pNUz8GUPNSAydvD3m8IXWzFTe50,39
17
+ gnarly-0.0.0.dev10.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
@@ -1,20 +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/types.py,sha256=VRw0_ZbEb0HjCzQ5iGsgrbWjeFBDoJPxMwmD2muMYXo,2485
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=sjuuYVrtC-MPP150rHDN008qKuPbsEIVhSJWHOhIXUk,6484
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=nvAQecw9W9PHoWKeiLG108Hyl-7AG94GbEgBOHgtrcw,5589
14
- gnarly/utils/llm/.ipynb_checkpoints/claude-checkpoint.py,sha256=AaEdgg1tzdj7gmL8LKE9T98VYhZ5jCCkEmsj-_v2LWI,2864
15
- gnarly/utils/llm/.ipynb_checkpoints/interfaces-checkpoint.py,sha256=Q9vkqtUNXAj79PV9DTr8jdPSZbGM8NCEq2NTjxBHvWo,10437
16
- gnarly/utils/llm/.ipynb_checkpoints/models-checkpoint.py,sha256=nvAQecw9W9PHoWKeiLG108Hyl-7AG94GbEgBOHgtrcw,5589
17
- gnarly-0.0.0.dev8.dist-info/METADATA,sha256=ROxKvOrmK9oQyuBkNRXKFVmdhpbAvL6mQWcBPz6q_LY,252
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,,