ganireddikumar/OpenDevin_AI_Agent_Suite
0
1import streamlit as st2import os3import requests4from langchain_groq import ChatGroq5from huggingface_hub import InferenceClient6 7# AI Service Configuration8AI_SERVICES = {9 "Groq": {10 "Llama3-70B": "llama3-70b-8192",11 "Mistral-saba24B": "mistral-saba-24b"12 },13 "HuggingFace": {14 "Phi-3.5-Mini": "microsoft/Phi-3.5-mini-instruct"15 }16}17 18def get_ai_response(prompt, service, model, temperature):19 """Unified AI response handler"""20 try:21 if service == "Groq":22 api_key = os.getenv("GROQ_API_KEY")23 if not api_key:24 return "Error: GROQ_API_KEY not set"25 llm = ChatGroq(26 groq_api_key=api_key,27 model_name=model,28 temperature=temperature29 )30 return llm.invoke(prompt).content31 elif service == "HuggingFace":32 hf_token = os.getenv("HF_TOKEN")33 if not hf_token:34 return "Error: HF_TOKEN not set"35 return InferenceClient(token=hf_token).text_generation(36 prompt,37 model=model,38 max_new_tokens=50039 )40 return "Selected AI service not supported"41 except Exception as e:42 return f"{service} Error: {str(e)}"43 44def web_search(query, max_results=5):45 """Perform web search with DuckDuckGo API"""46 def clean_text(text):47 text = text.replace("https://", "").replace("http://", "")48 return text.split(" — ", 1)[-1]49 try:50 response = requests.get(51 "https://api.duckduckgo.com/",52 params={53 "q": query,54 "format": "json",55 "no_html": 1,56 "t": "OpenDevinApp",57 "kl": "wt-wt"58 },59 timeout=1560 )61 data = response.json()62 results = []63 if data.get("AbstractText"):64 results.append({65 "title": data.get("Heading", "Direct Answer"),66 "content": data["AbstractText"],67 "url": data.get("AbstractURL", "")68 })69 if data.get("RelatedTopics"):70 for topic in data["RelatedTopics"]:71 if "Topics" in topic:72 for subtopic in topic["Topics"]:73 if subtopic.get("Text") and subtopic.get("FirstURL"):74 results.append({75 "title": subtopic["Text"].split(" › ")[-1],76 "content": clean_text(subtopic["Text"]),77 "url": subtopic["FirstURL"]78 })79 return results[:max_results] if results else []80 except Exception as e:81 return f"Search Error: {str(e)}"82 83st.set_page_config(84 page_title="🚀 AI Agent Suite",85 layout="wide",86 initial_sidebar_state="expanded"87)88 89def main():90 st.title("🚀 AI Agent Suite")91 92 # Initialize chat histories if not already present93 if "code_chat_history" not in st.session_state:94 st.session_state.code_chat_history = []95 if "conversation" not in st.session_state:96 st.session_state.conversation = [] # This holds the full conversation history for our chatbot97 if "conversation_chatbot" not in st.session_state:98 st.session_state.conversation_chatbot = [] # Alternative history for a separate chat tab, if desired99 100 # Sidebar Configuration101 with st.sidebar:102 st.header("Configuration ⚙️")103 service = st.selectbox("AI Service", list(AI_SERVICES.keys()))104 model = st.selectbox("Model", list(AI_SERVICES[service].keys()))105 temperature = st.slider("Creativity", 0.1, 1.0, 0.7)106 107 # Application Tabs108 tab1, tab2, tab3 = st.tabs(["💻 Code", "🔍 Research", "💬 Chatbot"])109 110 111 # Tab 1: Code Generator remains unchanged112 with tab1:113 st.header("Code Generator")114 code_prompt = st.text_area("Coding Task:", height=150)115 if st.button("Generate Code", key="code_button"):116 if code_prompt.strip():117 with st.spinner("Generating..."):118 response = get_ai_response(119 f"Write Python code for: {code_prompt}. Code only.",120 service,121 AI_SERVICES[service][model],122 temperature123 )124 st.session_state.code_chat_history.append({125 "prompt": code_prompt,126 "response": response127 })128 if "```python" in response:129 code = response.split("```python")[1].split("```")[0]130 st.code(code, language="python")131 else:132 st.code(response, language="python")133 if st.session_state.code_chat_history:134 with st.expander("Code Chat History"):135 for idx, chat in enumerate(reversed(st.session_state.code_chat_history), start=1):136 st.write(f"Chat {idx}")137 st.write("Prompt:")138 st.write(chat["prompt"])139 st.write("Response:")140 if "```python" in chat["response"]:141 code = chat["response"].split("```python")[1].split("```")[0]142 st.code(code, language="python")143 else:144 st.code(chat["response"], language="python")145 st.write("---")146 147 # Tab 2: Web Research remains unchanged148 with tab2:149 st.header("Web Research")150 query = st.text_input("Search Query:")151 if st.button("Search", key="search_button"):152 if query.strip():153 results = web_search(query)154 if isinstance(results, str):155 st.error(results)156 else:157 for result in results:158 with st.expander(result.get("title", "Result")):159 if result.get("url"):160 st.markdown(f"[Source]({result['url']})")161 st.write(result.get("content", ""))162 163 164 165 166 # Tab 3: Chatbot UI (ChatGPT-like interface)167 with tab3:168 st.header("Chatbot")169 # Ensure conversation history exists170 if "chat_history" not in st.session_state:171 st.session_state.chat_history = []172 # Display conversation messages as chat bubbles173 for msg in st.session_state.chat_history:174 if msg["role"] == "user":175 st.chat_message("user").write(msg["content"])176 else:177 st.chat_message("assistant").write(msg["content"])178 # Chat input at the bottom of the page179 if hasattr(st, "chat_input"):180 user_input = st.chat_input("Send a message")181 else:182 user_input = st.text_input("Send a message", key="chat_input_box")183 if user_input:184 # Append new user message to chat history185 st.session_state.chat_history.append({"role": "user", "content": user_input})186 # Build conversation prompt using full chat history (for context)187 full_context = ""188 for msg in st.session_state.chat_history:189 role_label = "User" if msg["role"] == "user" else "Assistant"190 full_context += f"{role_label}: {msg['content']}\n"191 # Append instruction to include chain-of-thought (without markdown)192 full_prompt = full_context + (193 "\nPlease provide your chain-of-thought (i.e., your intermediate reasoning) "194 "followed by your final answer. Do not use markdown formatting for the chain-of-thought.\n"195 "Chain-of-Thought:\n[Your reasoning here]\nFinal Answer:\n[Your final answer here]"196 )197 response = get_ai_response(full_prompt, service, AI_SERVICES[service][model], temperature)198 if "Chain-of-Thought:" in response and "Final Answer:" in response:199 cot = response.split("Chain-of-Thought:")[1].split("Final Answer:")[0].strip()200 final_answer = response.split("Final Answer:")[1].strip()201 else:202 cot = "Chain-of-thought not provided."203 final_answer = response204 assistant_message = f"Chain-of-Thought: {cot}\nFinal Answer: {final_answer}"205 st.session_state.chat_history.append({"role": "assistant", "content": assistant_message})206 st.rerun()207 208if __name__ == "__main__":209 main()210 