aravindbethapudi2017/Multi_LLM_Code_Explainer
0
1 2 3import os4import io5import sys6import json7import requests8from dotenv import load_dotenv9from openai import OpenAI10import anthropic11from IPython.display import Markdown, display, update_display12import gradio as gr13import subprocess14 15 16 17load_dotenv()18os.environ['OPENAI_API_KEY'] = os.getenv('OPENAI_API_KEY', 'your-key-if-not-using-env')19os.environ['ANTHROPIC_API_KEY'] = os.getenv('ANTHROPIC_API_KEY', 'your-key-if-not-using-env')20os.environ['HF_TOKEN'] = os.getenv('HF_TOKEN', 'your-key-if-not-using-env')21 22openai = OpenAI()23claude = anthropic.Anthropic()24OPENAI_MODEL = "gpt-4o"25CLAUDE_MODEL = "claude-3-5-sonnet-20240620"26 27system_prompt = 'You are a code explanation assistant. Your task is to explain any code that the user provides in a simple, clear, and effective way. Focus only on the code that the user pastes. Break it down into smaller parts, explain the purpose of each part, and provide a high-level overview of what the code does. Use plain language and avoid unnecessary technical jargon. If the code is complex, use analogies or examples to make it easier to understand.'28 29user_prompt_template = 'Explain the following code in simple terms:\n```\n{}\n```'30 31def optimize_gpt(code):32 try:33 34 user_prompt = user_prompt_template.format(code)35 response_openai = openai.chat.completions.create(36 model="gpt-4",37 messages=[38 {"role": "system", "content": system_prompt},39 {"role": "user", "content": user_prompt}40 ],41 stream=True42 )43 reply = ""44 for chunk in response_openai:45 fragment = chunk.choices[0].delta.content or ""46 reply += fragment47 return reply48 except Exception as e:49 return f"Error with OpenAI API: {str(e)}"50 51import logging52 53logging.basicConfig(level=logging.INFO)54 55def optimize_claude(code):56 try:57 user_prompt = user_prompt_template.format(code)58 logging.info("Sending request to Claude API")59 response_claude = claude.messages.stream(60 model=CLAUDE_MODEL,61 max_tokens=2000,62 system=system_prompt,63 messages=[{"role": "user", "content": user_prompt}]64 )65 reply = ""66 with response_claude as stream:67 for chunk in stream.text_stream:68 reply += chunk69 logging.info("Received response from Claude API")70 return reply71 except Exception as e:72 logging.error(f"Error with Claude API: {str(e)}")73 return f"Error with Claude API: {str(e)}"74 75def combined_function(code):76 output_gpt = optimize_gpt(code)77 output_claude = optimize_claude(code)78 return output_gpt, output_claude79 80 81with gr.Blocks(theme=gr.themes.Soft()) as demo:82 gr.Markdown("# Multi LLM Code Explainer")83 gr.Markdown("Paste your code below and get real-time explanations from OpenAI's GPT-4 and Anthropic's Claude-3.5-Sonnet.")84 85 with gr.Row():86 with gr.Column():87 code_input = gr.Textbox(88 label="Enter Your Code",89 placeholder="Paste your code here...",90 lines=10,91 max_lines=20,92 interactive=True93 )94 submit_button = gr.Button("Submit", variant="primary")95 96 with gr.Column():97 gpt_output = gr.Textbox(98 label="OpenAI ChatGPT Explanation",99 lines=15,100 max_lines=20,101 interactive=False102 )103 claude_output = gr.Textbox(104 label="Claude Explanation",105 lines=15,106 max_lines=20,107 interactive=False108 )109 110 111 submit_button.click(112 fn=combined_function,113 inputs=code_input,114 outputs=[gpt_output, claude_output],115 api_name="explain_code"116 )117 118 119 120 with gr.Row():121 copy_gpt_button = gr.Button("Copy GPT Explanation")122 copy_claude_button = gr.Button("Copy Claude Explanation")123 124 125 copy_gpt_button.click(126 fn=None,127 inputs=gpt_output,128 outputs=None,129 js="(text) => navigator.clipboard.writeText(text)"130 )131 copy_claude_button.click(132 fn=None,133 inputs=claude_output,134 outputs=None,135 js="(text) => navigator.clipboard.writeText(text)"136 )137 138 139 140demo.launch()