devduck 0.3.0__py3-none-any.whl → 0.4.1__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 devduck might be problematic. Click here for more details.

@@ -0,0 +1,485 @@
1
+ """System prompt management tool for Strands Agents.
2
+
3
+ This module provides a tool to view and modify system prompts used by the agent.
4
+ It helps with dynamic adaptation of the agent's behavior and capabilities,
5
+ and can persist changes by updating GitHub repository variables.
6
+
7
+ Key Features:
8
+ 1. View current system prompt from any environment variable
9
+ 2. Update system prompt (in-memory and GitHub repository variable)
10
+ 3. Add context information to system prompt
11
+ 4. Reset system prompt to default
12
+ 5. Support for custom variable names (SYSTEM_PROMPT, TOOL_BUILDER_SYSTEM_PROMPT, etc.)
13
+
14
+ Usage Examples:
15
+ ```python
16
+ from strands import Agent
17
+ from protocol_tools import system_prompt
18
+
19
+ agent = Agent(tools=[system_prompt])
20
+
21
+ # View current system prompt (default SYSTEM_PROMPT variable)
22
+ result = agent.tool.system_prompt(action="view")
23
+
24
+ # Update system prompt for tool builder
25
+ result = agent.tool.system_prompt(
26
+ action="update",
27
+ prompt="You are a specialized tool builder agent...",
28
+ repository="owner/repo",
29
+ variable_name="TOOL_BUILDER_SYSTEM_PROMPT",
30
+ )
31
+
32
+ # Work with any custom variable name
33
+ result = agent.tool.system_prompt(
34
+ action="view", variable_name="MY_CUSTOM_PROMPT"
35
+ )
36
+ ```
37
+ """
38
+
39
+ import os
40
+ from typing import Any
41
+
42
+ import requests
43
+ from strands import tool
44
+
45
+
46
+ def _get_github_token() -> str:
47
+ """Get GitHub token from environment variable."""
48
+ return os.environ.get("PAT_TOKEN", os.environ.get("GITHUB_TOKEN", ""))
49
+
50
+
51
+ def _get_github_repository_variable(
52
+ repository: str, name: str, token: str
53
+ ) -> dict[str, Any]:
54
+ """Fetch a GitHub repository variable.
55
+
56
+ Args:
57
+ repository: The repository in format "owner/repo"
58
+ name: The variable name
59
+ token: GitHub token
60
+
61
+ Returns:
62
+ Dictionary with success status, message, and value if successful
63
+ """
64
+ # GitHub API endpoint for repository variables
65
+ url = f"https://api.github.com/repos/{repository}/actions/variables/{name}"
66
+
67
+ headers = {
68
+ "Accept": "application/vnd.github+json",
69
+ "Authorization": f"Bearer {token}",
70
+ "X-GitHub-Api-Version": "2022-11-28",
71
+ }
72
+
73
+ try:
74
+ response = requests.get(url, headers=headers, timeout=30)
75
+
76
+ if response.status_code == 200:
77
+ data = response.json()
78
+ return {
79
+ "success": True,
80
+ "message": f"Variable {name} fetched successfully",
81
+ "value": data.get("value", ""),
82
+ }
83
+ else:
84
+ error_message = (
85
+ f"Failed to fetch variable: {response.status_code} - {response.text}"
86
+ )
87
+ return {"success": False, "message": error_message, "value": ""}
88
+ except Exception as e:
89
+ return {
90
+ "success": False,
91
+ "message": f"Error fetching GitHub variable: {e!s}",
92
+ "value": "",
93
+ }
94
+
95
+
96
+ def _get_system_prompt(
97
+ repository: str | None = None, variable_name: str = "SYSTEM_PROMPT"
98
+ ) -> str:
99
+ """Get the current system prompt.
100
+
101
+ First checks the local environment variable.
102
+ If empty and repository is provided, tries to fetch from GitHub repository variables.
103
+
104
+ Args:
105
+ repository: Optional GitHub repository in format "owner/repo"
106
+ variable_name: Name of the environment/repository variable to use
107
+
108
+ Returns:
109
+ The system prompt string
110
+ """
111
+ # First check local environment
112
+ local_prompt = os.environ.get(variable_name, "")
113
+ if local_prompt:
114
+ return local_prompt
115
+
116
+ # If local is empty and repository is provided, try GitHub
117
+ if repository and not local_prompt:
118
+ token = _get_github_token()
119
+ if token:
120
+ result = _get_github_repository_variable(
121
+ repository=repository, name=variable_name, token=token
122
+ )
123
+
124
+ if result["success"]:
125
+ # Store in local environment for future use
126
+ if result["value"]:
127
+ os.environ[variable_name] = result["value"]
128
+ return str(result["value"])
129
+
130
+ # Default to empty string if nothing found
131
+ return ""
132
+
133
+
134
+ def _update_system_prompt(
135
+ new_prompt: str, variable_name: str = "SYSTEM_PROMPT"
136
+ ) -> None:
137
+ """Update the system prompt in the environment variable."""
138
+ os.environ[variable_name] = new_prompt
139
+
140
+
141
+ def _get_github_event_context() -> str:
142
+ """Get GitHub event context information from environment variables."""
143
+ event_context = []
144
+
145
+ # GitHub repository information
146
+ repo = os.environ.get("GITHUB_REPOSITORY", "")
147
+ if repo:
148
+ event_context.append(f"Repository: {repo}")
149
+
150
+ # Event type
151
+ event_name = os.environ.get("GITHUB_EVENT_NAME", "")
152
+ if event_name:
153
+ event_context.append(f"Event Type: {event_name}")
154
+
155
+ # Actor
156
+ actor = os.environ.get("GITHUB_ACTOR", "")
157
+ if actor:
158
+ event_context.append(f"Actor: {actor}")
159
+
160
+ # Add more GitHub context variables as needed
161
+ return "\n".join(event_context)
162
+
163
+
164
+ def _update_github_repository_variable(
165
+ repository: str, name: str, value: str, token: str
166
+ ) -> dict[str, Any]:
167
+ """Update a GitHub repository variable.
168
+
169
+ Args:
170
+ repository: The repository in format "owner/repo"
171
+ name: The variable name
172
+ value: The variable value
173
+ token: GitHub token
174
+
175
+ Returns:
176
+ Dictionary with status and message
177
+ """
178
+ # GitHub API endpoint for repository variables
179
+ url = f"https://api.github.com/repos/{repository}/actions/variables/{name}"
180
+
181
+ headers = {
182
+ "Accept": "application/vnd.github+json",
183
+ "Authorization": f"Bearer {token}",
184
+ "X-GitHub-Api-Version": "2022-11-28",
185
+ }
186
+
187
+ data = {"name": name, "value": value}
188
+
189
+ response = requests.patch(url, headers=headers, json=data, timeout=30)
190
+
191
+ if response.status_code == 204:
192
+ return {"success": True, "message": f"Variable {name} updated successfully"}
193
+ else:
194
+ error_message = (
195
+ f"Failed to update variable: {response.status_code} - {response.text}"
196
+ )
197
+ return {"success": False, "message": error_message}
198
+
199
+
200
+ @tool
201
+ def system_prompt(
202
+ action: str,
203
+ prompt: str | None = None,
204
+ context: str | None = None,
205
+ repository: str | None = None,
206
+ variable_name: str = "SYSTEM_PROMPT",
207
+ ) -> dict[str, str | list[dict[str, str]]]:
208
+ """Manage the agent's system prompt.
209
+
210
+ This tool allows viewing and modifying the system prompt used by the agent.
211
+ It can be used to adapt the agent's behavior dynamically during runtime
212
+ and can update GitHub repository variables to persist changes.
213
+
214
+ Args:
215
+ action: The action to perform on the system prompt. One of:
216
+ - "view": View the current system prompt
217
+ - "update": Replace the current system prompt
218
+ - "add_context": Add additional context to the system prompt
219
+ - "reset": Reset to default (empty or environment-defined)
220
+ - "get_github_context": Get GitHub event context
221
+ prompt: New system prompt when using the "update" action
222
+ context: Additional context to add when using the "add_context" action
223
+ repository: GitHub repository in format "owner/repo" to update repository
224
+ variable (e.g., "cagataycali/report-agent")
225
+ variable_name: Name of the environment/repository variable to use
226
+ (default: "SYSTEM_PROMPT")
227
+
228
+ Returns:
229
+ A dictionary with the operation status and current system prompt
230
+
231
+ Example:
232
+ ```python
233
+ # View current system prompt
234
+ result = system_prompt(action="view")
235
+
236
+ # Update system prompt in memory
237
+ result = system_prompt(
238
+ action="update", prompt="You are a specialized agent for task X..."
239
+ )
240
+
241
+ # Update GitHub repository variable
242
+ result = system_prompt(
243
+ action="update",
244
+ prompt="You are a specialized agent for task X...",
245
+ repository="owner/repo",
246
+ )
247
+
248
+ # Work with custom variable name
249
+ result = system_prompt(
250
+ action="update",
251
+ prompt="You are a tool builder...",
252
+ repository="owner/repo",
253
+ variable_name="TOOL_BUILDER_SYSTEM_PROMPT",
254
+ )
255
+ ```
256
+ """
257
+ try:
258
+ if action == "view":
259
+ current_prompt = _get_system_prompt(repository, variable_name)
260
+ source = "local environment"
261
+
262
+ if not os.environ.get(variable_name) and repository:
263
+ source = f"GitHub repository {repository}"
264
+
265
+ return {
266
+ "status": "success",
267
+ "content": [
268
+ {
269
+ "text": f"Current system prompt from {variable_name} (from {source}):\n\n{current_prompt}"
270
+ }
271
+ ],
272
+ }
273
+
274
+ elif action == "update":
275
+ if not prompt:
276
+ return {
277
+ "status": "error",
278
+ "content": [
279
+ {
280
+ "text": "Error: prompt parameter is required for the update action"
281
+ }
282
+ ],
283
+ }
284
+
285
+ # Update in-memory environment variable
286
+ _update_system_prompt(prompt, variable_name)
287
+
288
+ # If repository is specified, also update GitHub repository variable
289
+ if repository:
290
+ token = _get_github_token()
291
+ if not token:
292
+ return {
293
+ "status": "error",
294
+ "content": [
295
+ {
296
+ "text": "Error: GitHub token not available. Cannot update repository variable."
297
+ }
298
+ ],
299
+ }
300
+
301
+ result = _update_github_repository_variable(
302
+ repository=repository, name=variable_name, value=prompt, token=token
303
+ )
304
+
305
+ if result["success"]:
306
+ return {
307
+ "status": "success",
308
+ "content": [
309
+ {
310
+ "text": f"System prompt updated successfully in memory ({variable_name})"
311
+ },
312
+ {
313
+ "text": f"GitHub repository variable updated: {result['message']}"
314
+ },
315
+ ],
316
+ }
317
+ else:
318
+ return {
319
+ "status": "error",
320
+ "content": [
321
+ {
322
+ "text": f"System prompt updated successfully in memory ({variable_name})"
323
+ },
324
+ {
325
+ "text": f"GitHub repository variable update failed: {result['message']}"
326
+ },
327
+ ],
328
+ }
329
+
330
+ return {
331
+ "status": "success",
332
+ "content": [
333
+ {
334
+ "text": f"System prompt updated successfully in memory ({variable_name})"
335
+ }
336
+ ],
337
+ }
338
+
339
+ elif action == "add_context":
340
+ if not context:
341
+ return {
342
+ "status": "error",
343
+ "content": [
344
+ {
345
+ "text": "Error: context parameter is required for the add_context action"
346
+ }
347
+ ],
348
+ }
349
+
350
+ current_prompt = _get_system_prompt(repository, variable_name)
351
+ new_prompt = f"{current_prompt}\n\n{context}" if current_prompt else context
352
+ _update_system_prompt(new_prompt, variable_name)
353
+
354
+ # If repository is specified, also update GitHub repository variable
355
+ if repository:
356
+ token = _get_github_token()
357
+ if not token:
358
+ return {
359
+ "status": "error",
360
+ "content": [
361
+ {
362
+ "text": f"Context added to system prompt successfully in memory ({variable_name})"
363
+ },
364
+ {
365
+ "text": "Error: GitHub token not available. Cannot update repository variable."
366
+ },
367
+ ],
368
+ }
369
+
370
+ result = _update_github_repository_variable(
371
+ repository=repository,
372
+ name=variable_name,
373
+ value=new_prompt,
374
+ token=token,
375
+ )
376
+
377
+ if result["success"]:
378
+ return {
379
+ "status": "success",
380
+ "content": [
381
+ {
382
+ "text": f"Context added to system prompt successfully in memory ({variable_name})"
383
+ },
384
+ {
385
+ "text": f"GitHub repository variable updated: {result['message']}"
386
+ },
387
+ ],
388
+ }
389
+ else:
390
+ return {
391
+ "status": "error",
392
+ "content": [
393
+ {
394
+ "text": f"Context added to system prompt successfully in memory ({variable_name})"
395
+ },
396
+ {
397
+ "text": f"GitHub repository variable update failed: {result['message']}"
398
+ },
399
+ ],
400
+ }
401
+
402
+ return {
403
+ "status": "success",
404
+ "content": [
405
+ {
406
+ "text": f"Context added to system prompt successfully ({variable_name})"
407
+ }
408
+ ],
409
+ }
410
+
411
+ elif action == "reset":
412
+ # Reset to empty or environment-defined default
413
+ os.environ.pop(variable_name, None)
414
+
415
+ # If repository is specified, reset GitHub repository variable
416
+ if repository:
417
+ token = _get_github_token()
418
+ if not token:
419
+ return {
420
+ "status": "error",
421
+ "content": [
422
+ {
423
+ "text": f"System prompt reset to default in memory ({variable_name})"
424
+ },
425
+ {
426
+ "text": "Error: GitHub token not available. Cannot update repository variable."
427
+ },
428
+ ],
429
+ }
430
+
431
+ result = _update_github_repository_variable(
432
+ repository=repository, name=variable_name, value="", token=token
433
+ )
434
+
435
+ if result["success"]:
436
+ return {
437
+ "status": "success",
438
+ "content": [
439
+ {
440
+ "text": f"System prompt reset to default in memory ({variable_name})"
441
+ },
442
+ {
443
+ "text": f"GitHub repository variable reset: {result['message']}"
444
+ },
445
+ ],
446
+ }
447
+ else:
448
+ return {
449
+ "status": "error",
450
+ "content": [
451
+ {
452
+ "text": f"System prompt reset to default in memory ({variable_name})"
453
+ },
454
+ {
455
+ "text": f"GitHub repository variable reset failed: {result['message']}"
456
+ },
457
+ ],
458
+ }
459
+
460
+ return {
461
+ "status": "success",
462
+ "content": [
463
+ {"text": f"System prompt reset to default ({variable_name})"}
464
+ ],
465
+ }
466
+
467
+ elif action == "get_github_context":
468
+ github_context = _get_github_event_context()
469
+ return {
470
+ "status": "success",
471
+ "content": [{"text": f"GitHub Event Context:\n\n{github_context}"}],
472
+ }
473
+
474
+ else:
475
+ return {
476
+ "status": "error",
477
+ "content": [
478
+ {
479
+ "text": f"Error: Unknown action '{action}'. Valid actions are view, update, add_context, reset, get_github_context"
480
+ }
481
+ ],
482
+ }
483
+
484
+ except Exception as e:
485
+ return {"status": "error", "content": [{"text": f"Error: {e!s}"}]}