microhugs / apps.py
acecalisto3's picture
Update apps.py
71d2bac verified
raw
history blame
8.71 kB
async def respond(
command: str,
history: List[Tuple[str, str]],
system_message: str,
max_tokens: int,
temperature: float,
top_p: float,
github_api_token: str,
github_username: str,
github_repository: str,
selected_model: str,
severity: str,
programming_language: str,
*args
) -> str:
global GITHUB_API_TOKEN
GITHUB_API_TOKEN = github_api_token
global issues
issues = []
global github_client
github_client = None
messages = [{"role": "system", "content": system_message}]
logging.info("System message: {}".format(system_message))
for user_msg, assistant_msg in history:
if user_msg:
messages.append({"role": "user", "content": user_msg})
logging.info("User message: {}".format(user_msg))
if assistant_msg:
messages.append({"role": "assistant", "content": assistant_msg})
logging.info("Assistant message: {}".format(assistant_msg))
logging.info("Command received: {}".format(command))
try:
command, *args = command.split(' ', 1)
args = args[0] if args else ''
except ValueError:
yield "❌ Invalid command format. Use /help for instructions"
if command == "/github":
try:
if not args:
if github_client:
yield f"ℹ️ Current GitHub connection: {github_client.config.username}/{github_client.config.repository}"
else:
yield "ℹ️ Not connected to GitHub"
parts = args.split(maxsplit=2) # Allow spaces in token
if len(parts) < 3:
raise ValueError("Format: /github <username> <repo> <token>")
github_client = GitHubIntegration(GitHubConfig(
username=parts[0],
repository=parts[1],
api_token=SecretStr(parts[2])
))
issues = await github_client.fetch_issues() # Fetch issues after successful connection
yield "✅ GitHub configured successfully"
except Exception as e:
github_client = None
yield f"❌ Error: {str(e)}"
elif command == "/help":
help_message = """Available commands:
- `/github <username> <repo> <token>`: Connect to a GitHub repository.
- `/help`: Show this help message.
- `/generate_code [code description]`: Generate code based on the description.
- `/explain_concept [concept]`: Explain a concept.
- `/write_documentation [topic]`: Write documentation for a given topic.
- `/translate_code [code] to [target language]`: Translate code to another language.
- `/analyze [issue number]`: Analyze a GitHub issue.
- `/list_issues`: List all issues in the connected repository.
"""
yield help_message
elif command.isdigit() and issues:
try:
issue_number = int(command) - 1
issue = issues[issue_number]
issue_text = issue['title'] + "\n\n" + issue['body']
resolution = analyze_issues(issue_text, selected_model, severity, programming_language)
related_issues = find_related_issues(issue_text, issues)
related_issue_text = "\n".join(
["- {} (Similarity: {:.2f})".format(issue['title'], similarity) for issue, similarity in related_issues]
)
yield "Resolution for Issue '{}':\n{}\n\nRelated Issues:\n{}".format(issue['title'], resolution, related_issue_text)
except Exception as e:
logging.error("Error analyzing issue: {}".format(e))
yield "Error analyzing issue: {}".format(e)
elif command.startswith("/generate_code"):
code_description = command.replace("/generate_code", "").strip()
if not code_description:
yield "Please provide a description of the code you want to generate."
else:
prompt = "Generate code for the following: {}\nProgramming Language: {}".format(code_description, programming_language)
try:
generated_code = analyze_issues(prompt, selected_model)
code_output = "<pre>{}</pre>".format(generated_code)
yield code_output
except Exception as e:
logging.error("Error generating code: {}".format(e))
yield "Error generating code: {}".format(e)
elif command.startswith("/explain_concept"):
concept = command.replace("/explain_concept", "").strip()
if not concept:
yield "Please provide a concept to explain."
else:
prompt = "Explain the concept of {} in detail.".format(concept)
try:
explanation = analyze_issues(prompt, selected_model)
yield "<pre>{}</pre>".format(explanation)
except Exception as e:
logging.error("Error explaining concept: {}".format(e))
yield "Error explaining concept: {}".format(e)
elif command.startswith("/write_documentation"):
topic = command.replace("/write_documentation", "").strip()
if not topic:
yield "Please provide a topic for documentation."
else:
prompt = "Write documentation for the topic: {}".format(topic)
try:
documentation = analyze_issues(prompt, selected_model)
yield "<pre>{}</pre>".format(documentation)
except Exception as e:
logging.error("Error writing documentation: {}".format(e))
yield "Error writing documentation: {}".format(e)
elif command.startswith("/translate_code"):
try:
code, _, target_language = command.replace("/translate_code", "").strip().partition(" to ")
if not code or not target_language:
yield "Please provide code and target language in the format: `/translate_code [code] to [target language]`"
else:
prompt = f"Translate the following code to {target_language}:\n```\n{code}\n```"
try:
translated_code = analyze_issues(prompt, selected_model)
yield "<pre>{}</pre>".format(translated_code)
except Exception as e:
logging.error("Error translating code: {}".format(e))
yield "Error translating code: {}".format(e)
except Exception as e:
logging.error("Error parsing translate_code command: {}".format(e))
yield "Error parsing translate_code command: {}".format(e)
elif command.startswith("/analyze"):
try:
if not github_client:
yield "❌ You need to connect to a GitHub repository first using `/github <username> <repo> <token>`."
issue_number = int(command.replace("/analyze", "").strip()) - 1
if 0 <= issue_number < len(issues):
issue = issues[issue_number]
issue_text = issue['title'] + "\n\n" + issue['body']
resolution = analyze_issues(issue_text, selected_model, severity, programming_language)
related_issues = find_related_issues(issue_text, issues)
related_issue_text = "\n".join(
["- {} (Similarity: {:.2f})".format(issue['title'], similarity) for issue, similarity in related_issues]
)
yield "Resolution for Issue '{}':\n{}\n\nRelated Issues:\n{}".format(issue['title'], resolution, related_issue_text)
else:
yield "❌ Invalid issue number. Please enter a valid issue number from the list."
except Exception as e:
logging.error("Error analyzing issue: {}".format(e))
yield "Error analyzing issue: {}".format(e)
elif command == "/list_issues":
try:
if not github_client:
yield "❌ You need to connect to a GitHub repository first using `/github <username> <repo> <token>`."
if issues:
issue_list = "\n".join(
[f"- {issue['title']} (Issue #{issue['number']})" for issue in issues]
)
yield f"Issues in {github_client.config.username}/{github_client.config.repository}:\n{issue_list}"
else:
yield "❌ No issues found in the connected repository."
except Exception as e:
logging.error("Error listing issues: {}".format(e))
yield "Error listing issues: {}".format(e)
else:
yield "I'm not sure what you mean. Try using `/help` for a list of available commands."