morvinp/coding-assistant-api
0
1import gradio as gr2import requests3import json4import os5 6# Simple coding assistant using a reliable model7def generate_coding_response(message, history):8 try:9 # Use Hugging Face Inference API with a reliable model10 API_URL = "https://api-inference.huggingface.co/models/microsoft/DialoGPT-medium"11 headers = {"Authorization": f"Bearer {os.getenv('HF_TOKEN')}"}12 13 # Format the conversation history14 conversation = ""15 for human, assistant in history:16 conversation += f"Human: {human}\nAssistant: {assistant}\n"17 18 # Add current message19 prompt = f"{conversation}Human: {message}\nAssistant:"20 21 payload = {22 "inputs": prompt,23 "parameters": {24 "max_new_tokens": 150,25 "temperature": 0.7,26 "do_sample": True,27 "return_full_text": False28 }29 }30 31 response = requests.post(API_URL, headers=headers, json=payload, timeout=30)32 33 if response.status_code == 200:34 result = response.json()35 if result and len(result) > 0 and 'generated_text' in result[0]:36 generated_text = result[0]['generated_text']37 # Clean up the response38 cleaned_response = generated_text.replace(prompt, "").strip()39 if cleaned_response:40 return cleaned_response41 else:42 return "I'd be happy to help with your coding question. Could you provide more details?"43 else:44 return "I'm having trouble generating a response. Please try again."45 else:46 return "I'm currently experiencing technical difficulties. Please try again in a moment."47 48 except Exception as e:49 return f"I apologize, but I'm having trouble processing your request. Please try again later."50 51# Create the Gradio interface52def create_chatbot():53 with gr.Blocks(title="Coding Assistant API", theme=gr.themes.Soft()) as demo:54 gr.Markdown("# ๐ป Coding Assistant")55 gr.Markdown("Ask me anything about programming, debugging, or development!")56 57 chatbot = gr.Chatbot(58 height=400,59 bubble_full_width=False,60 avatar_images=("๐ค", "๐ค")61 )62 63 with gr.Row():64 msg = gr.Textbox(65 placeholder="Ask about coding, debugging, etc...",66 container=False,67 scale=768 )69 submit = gr.Button("Send", scale=1, variant="primary")70 clear = gr.Button("Clear", scale=1)71 72 # Handle message submission73 def respond(message, chat_history):74 if not message.strip():75 return "", chat_history76 77 bot_message = generate_coding_response(message, chat_history)78 chat_history.append((message, bot_message))79 return "", chat_history80 81 # Event handlers82 submit.click(respond, [msg, chatbot], [msg, chatbot])83 msg.submit(respond, [msg, chatbot], [msg, chatbot])84 clear.click(lambda: [], None, chatbot)85 86 # API endpoint for external use87 gr.Markdown("""88 ## ๐ API Usage89 90 You can also use this as an API endpoint:91 92 ```93 import requests94 95 response = requests.post(96 "https://morvinp-coding-assistant-api.hf.space/api/predict",97 json={"data": ["Your coding question here", []]}98 )99 100 result = response.json()101 print(result["data"][1][-1][1]) # Get the bot's response102 ```103 """)104 105 return demo106 107# Launch the app108if __name__ == "__main__":109 demo = create_chatbot()110 demo.launch(server_name="0.0.0.0", server_port=7860)