-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathprocess_feedback.py
More file actions
179 lines (142 loc) · 5.12 KB
/
Copy pathprocess_feedback.py
File metadata and controls
179 lines (142 loc) · 5.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
#!/usr/bin/env python3
"""CLI script for processing feedback files.
This script is called by the GitHub Actions workflow to process
feedback submissions and triage them appropriately.
Usage:
python -m src.scripts.process_feedback feedback/file.jsonl
python -m src.scripts.process_feedback feedback/file.jsonl --dry-run=true
"""
import argparse
import asyncio
import json
import logging
import os
import sys
from pathlib import Path
# Configure logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
logger = logging.getLogger(__name__)
async def process_feedback_file(
file_path: Path,
dry_run: bool = False,
) -> list[dict]:
"""Process a single feedback file.
Args:
file_path: Path to feedback file (JSON or JSONL)
dry_run: If True, don't execute actions
Returns:
List of processing results
"""
from src.agents.feedback_triage_agent import (
FeedbackRecord,
FeedbackTriageAgent,
load_feedback_file,
save_processed_feedback,
)
from src.utils.github_client import GitHubClient
from src.utils.openrouter_llm import create_openrouter_llm
# Get API keys from environment (prefer testing key for CI/tests)
openrouter_key = os.getenv("OPENROUTER_API_KEY_FOR_TESTING") or os.getenv("OPENROUTER_API_KEY")
github_token = os.getenv("GITHUB_TOKEN")
if not openrouter_key:
logger.error("OPENROUTER_API_KEY or OPENROUTER_API_KEY_FOR_TESTING not set")
sys.exit(1)
# Get model configuration from environment
model = os.getenv("ANNOTATION_MODEL", "anthropic/claude-haiku-4.5")
provider = os.getenv("LLM_PROVIDER_PREFERENCE", "")
# Create LLM
llm = create_openrouter_llm(
model=model,
api_key=openrouter_key,
temperature=0.1,
max_tokens=1000,
provider=provider if provider else None,
)
# Create GitHub client if token available
github_client = None
if github_token:
github_client = GitHubClient(
token=github_token,
owner=os.getenv("GITHUB_REPOSITORY_OWNER", "Annotation-Garden"),
repo=os.getenv("GITHUB_REPOSITORY", "hedit").split("/")[-1],
)
logger.info("GitHub client initialized")
else:
logger.warning("GITHUB_TOKEN not set, running without GitHub integration")
# Create agent
agent = FeedbackTriageAgent(llm=llm, github_client=github_client)
# Load feedback records
if file_path.suffix == ".jsonl":
records = load_feedback_file(file_path)
else:
# Single JSON file
with open(file_path) as f:
data = json.load(f)
records = [FeedbackRecord.from_json(data)]
logger.info(f"Loaded {len(records)} feedback record(s) from {file_path}")
results = []
for i, record in enumerate(records):
logger.info(f"Processing record {i + 1}/{len(records)}")
try:
result = await agent.process_and_execute(record, dry_run=dry_run)
results.append(result)
# Log result
action = result.get("action", "unknown")
logger.info(f"Record {i + 1}: Action={action}, Reason={result.get('reason', 'N/A')}")
if "issue_url" in result:
logger.info(f" Created issue: {result['issue_url']}")
if "comment_url" in result:
logger.info(f" Added comment: {result['comment_url']}")
# Save processed feedback
if not dry_run:
output_dir = Path("feedback/processed")
save_processed_feedback(record, result, output_dir)
except Exception as e:
logger.error(f"Failed to process record {i + 1}: {e}")
results.append({"error": str(e)})
return results
def main():
"""Main entry point."""
parser = argparse.ArgumentParser(
description="Process feedback files and triage to GitHub issues"
)
parser.add_argument(
"file",
type=Path,
help="Path to feedback file (JSON or JSONL)",
)
parser.add_argument(
"--dry-run",
type=str,
default="false",
help="Dry run mode (true/false)",
)
args = parser.parse_args()
# Parse dry_run as boolean
dry_run = args.dry_run.lower() in ("true", "1", "yes")
if not args.file.exists():
logger.error(f"File not found: {args.file}")
sys.exit(1)
logger.info(f"Processing feedback file: {args.file}")
logger.info(f"Dry run mode: {dry_run}")
# Run async processing
results = asyncio.run(process_feedback_file(args.file, dry_run=dry_run))
# Print summary
print("\n" + "=" * 50)
print("PROCESSING SUMMARY")
print("=" * 50)
actions = {}
for result in results:
action = result.get("action", "error")
actions[action] = actions.get(action, 0) + 1
for action, count in actions.items():
print(f" {action}: {count}")
print("=" * 50)
# Output results as JSON for potential downstream processing
print("\nFull results (JSON):")
print(json.dumps(results, indent=2))
if __name__ == "__main__":
main()