Update app.py
Browse files
app.py
CHANGED
|
@@ -1,5 +1,6 @@
|
|
| 1 |
import os
|
| 2 |
import sys
|
|
|
|
| 3 |
import gradio as gr
|
| 4 |
from langchain_openai import ChatOpenAI
|
| 5 |
from langgraph.prebuilt import create_react_agent
|
|
@@ -13,39 +14,74 @@ NEBIUS_API_KEY = os.getenv("NEBIUS_API_KEY")
|
|
| 13 |
NEBIUS_BASE_URL = "https://api.studio.nebius.ai/v1/"
|
| 14 |
MODEL_NAME = "meta-llama/Meta-Llama-3.1-70B-Instruct"
|
| 15 |
|
| 16 |
-
# ---
|
| 17 |
SYSTEM_PROMPT = """You are a 'Vibe Coding' Python Tutor.
|
| 18 |
-
Your goal is
|
| 19 |
-
1. When a user asks to learn a concept, create a python file illustrating it.
|
| 20 |
-
2. RUN the file to show them the output.
|
| 21 |
-
3. If there is an error, debug it by reading the file and fixing it.
|
| 22 |
-
4. Always explain your reasoning briefly before executing tools.
|
| 23 |
|
| 24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
"""
|
| 26 |
|
| 27 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
"""
|
| 29 |
-
Main function to run the agent loop.
|
| 30 |
-
It connects to the local MCP server for every request to ensure fresh context.
|
| 31 |
"""
|
| 32 |
-
|
| 33 |
-
# 1. Define Server Parameters
|
| 34 |
server_params = StdioServerParameters(
|
| 35 |
command=sys.executable,
|
| 36 |
args=["server.py"],
|
| 37 |
env=os.environ.copy()
|
| 38 |
)
|
| 39 |
|
| 40 |
-
# 2. Connect to MCP Server & Load Tools
|
| 41 |
async with stdio_client(server_params) as (read, write):
|
| 42 |
async with ClientSession(read, write) as session:
|
| 43 |
await session.initialize()
|
| 44 |
-
|
| 45 |
-
# Convert MCP tools to LangChain tools
|
| 46 |
tools = await load_mcp_tools(session)
|
| 47 |
|
| 48 |
-
# 3. Initialize Nebius LLM
|
| 49 |
llm = ChatOpenAI(
|
| 50 |
api_key=NEBIUS_API_KEY,
|
| 51 |
base_url=NEBIUS_BASE_URL,
|
|
@@ -53,43 +89,81 @@ async def run_tutor(user_message, chat_history):
|
|
| 53 |
temperature=0.7
|
| 54 |
)
|
| 55 |
|
| 56 |
-
# 4. Create Agent
|
| 57 |
agent_executor = create_react_agent(llm, tools, state_modifier=SYSTEM_PROMPT)
|
| 58 |
-
|
| 59 |
-
#
|
| 60 |
inputs = {"messages": [HumanMessage(content=user_message)]}
|
| 61 |
response = await agent_executor.ainvoke(inputs)
|
|
|
|
| 62 |
|
| 63 |
-
|
| 64 |
-
return response["messages"][-1].content
|
| 65 |
|
| 66 |
-
# --- Gradio UI
|
| 67 |
-
with gr.Blocks(title="AI Python Tutor (MCP
|
| 68 |
-
gr.Markdown("#
|
| 69 |
gr.Markdown("Powered by **Nebius** (Llama 3.1) & **MCP** (Local Filesystem Access)")
|
| 70 |
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
async def user_turn(user_message, history):
|
| 76 |
-
|
| 77 |
-
# This works on Gradio 3, 4, and 5
|
| 78 |
-
return "", history + [[user_message, None]]
|
| 79 |
|
| 80 |
async def bot_turn(history):
|
| 81 |
-
|
| 82 |
-
last_message = history[-1][0]
|
| 83 |
|
| 84 |
-
#
|
| 85 |
-
|
| 86 |
|
| 87 |
-
# Update
|
| 88 |
-
history
|
| 89 |
-
|
|
|
|
|
|
|
| 90 |
|
| 91 |
-
|
| 92 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
)
|
| 94 |
|
| 95 |
# --- Launch ---
|
|
|
|
| 1 |
import os
|
| 2 |
import sys
|
| 3 |
+
import re
|
| 4 |
import gradio as gr
|
| 5 |
from langchain_openai import ChatOpenAI
|
| 6 |
from langgraph.prebuilt import create_react_agent
|
|
|
|
| 14 |
NEBIUS_BASE_URL = "https://api.studio.nebius.ai/v1/"
|
| 15 |
MODEL_NAME = "meta-llama/Meta-Llama-3.1-70B-Instruct"
|
| 16 |
|
| 17 |
+
# --- Advanced System Prompt with Structured Output ---
|
| 18 |
SYSTEM_PROMPT = """You are a 'Vibe Coding' Python Tutor.
|
| 19 |
+
Your goal is to teach by DOING and then providing resources.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
+
STRUCTURE OF YOUR RESPONSE:
|
| 22 |
+
1. **The Lesson**: Explain the concept and run code using your tools ('write_file', 'run_python_script').
|
| 23 |
+
2. **Context**: Use 'list_directory' to see what the student is working on.
|
| 24 |
+
|
| 25 |
+
CRITICAL: You must end EVERY response with these exact separators to populate the student's dashboard:
|
| 26 |
+
|
| 27 |
+
---SECTION: VIDEOS---
|
| 28 |
+
(List 2-3 YouTube search queries or URLs relevant to the topic)
|
| 29 |
+
|
| 30 |
+
---SECTION: ARTICLES---
|
| 31 |
+
(List 2-3 documentation links or course names, e.g., RealPython, FreeCodeCamp)
|
| 32 |
+
|
| 33 |
+
---SECTION: QUIZ---
|
| 34 |
+
(Create 1 short multiple-choice question to test what you just taught)
|
| 35 |
"""
|
| 36 |
|
| 37 |
+
def parse_agent_response(full_text):
|
| 38 |
+
"""Splits the single LLM response into 4 UI components."""
|
| 39 |
+
# Default content if sections are missing
|
| 40 |
+
chat_content = full_text
|
| 41 |
+
videos = "Ask a coding question to get video recommendations!"
|
| 42 |
+
articles = "Ask a coding question to get reading resources!"
|
| 43 |
+
quiz = "Ask a coding question to take a quiz!"
|
| 44 |
+
|
| 45 |
+
# Robust parsing using split
|
| 46 |
+
try:
|
| 47 |
+
if "---SECTION: VIDEOS---" in full_text:
|
| 48 |
+
parts = full_text.split("---SECTION: VIDEOS---")
|
| 49 |
+
chat_content = parts[0].strip()
|
| 50 |
+
remainder = parts[1]
|
| 51 |
+
|
| 52 |
+
if "---SECTION: ARTICLES---" in remainder:
|
| 53 |
+
v_parts = remainder.split("---SECTION: ARTICLES---")
|
| 54 |
+
videos = v_parts[0].strip()
|
| 55 |
+
remainder = v_parts[1]
|
| 56 |
+
|
| 57 |
+
if "---SECTION: QUIZ---" in remainder:
|
| 58 |
+
a_parts = remainder.split("---SECTION: QUIZ---")
|
| 59 |
+
articles = a_parts[0].strip()
|
| 60 |
+
quiz = a_parts[1].strip()
|
| 61 |
+
else:
|
| 62 |
+
articles = remainder.strip()
|
| 63 |
+
else:
|
| 64 |
+
videos = remainder.strip()
|
| 65 |
+
except Exception as e:
|
| 66 |
+
print(f"Parsing error: {e}")
|
| 67 |
+
|
| 68 |
+
return chat_content, videos, articles, quiz
|
| 69 |
+
|
| 70 |
+
async def run_tutor_dashboard(user_message, chat_history):
|
| 71 |
"""
|
| 72 |
+
Main function to run the agent loop and return 4 outputs.
|
|
|
|
| 73 |
"""
|
|
|
|
|
|
|
| 74 |
server_params = StdioServerParameters(
|
| 75 |
command=sys.executable,
|
| 76 |
args=["server.py"],
|
| 77 |
env=os.environ.copy()
|
| 78 |
)
|
| 79 |
|
|
|
|
| 80 |
async with stdio_client(server_params) as (read, write):
|
| 81 |
async with ClientSession(read, write) as session:
|
| 82 |
await session.initialize()
|
|
|
|
|
|
|
| 83 |
tools = await load_mcp_tools(session)
|
| 84 |
|
|
|
|
| 85 |
llm = ChatOpenAI(
|
| 86 |
api_key=NEBIUS_API_KEY,
|
| 87 |
base_url=NEBIUS_BASE_URL,
|
|
|
|
| 89 |
temperature=0.7
|
| 90 |
)
|
| 91 |
|
|
|
|
| 92 |
agent_executor = create_react_agent(llm, tools, state_modifier=SYSTEM_PROMPT)
|
| 93 |
+
|
| 94 |
+
# Run Agent
|
| 95 |
inputs = {"messages": [HumanMessage(content=user_message)]}
|
| 96 |
response = await agent_executor.ainvoke(inputs)
|
| 97 |
+
final_text = response["messages"][-1].content
|
| 98 |
|
| 99 |
+
return parse_agent_response(final_text)
|
|
|
|
| 100 |
|
| 101 |
+
# --- Gradio Dashboard UI ---
|
| 102 |
+
with gr.Blocks(title="AI Python Tutor (MCP Dashboard)", theme=gr.themes.Soft()) as demo:
|
| 103 |
+
gr.Markdown("# 🚀 Vibe Coding Academy")
|
| 104 |
gr.Markdown("Powered by **Nebius** (Llama 3.1) & **MCP** (Local Filesystem Access)")
|
| 105 |
|
| 106 |
+
with gr.Row():
|
| 107 |
+
# Left Column: Chat & Input
|
| 108 |
+
with gr.Column(scale=2):
|
| 109 |
+
chatbot = gr.Chatbot(height=500, label="Tutor Chat", type="messages")
|
| 110 |
+
|
| 111 |
+
# BOX 1: Learning Request (Input)
|
| 112 |
+
msg = gr.Textbox(
|
| 113 |
+
label="1. What do you want to learn?",
|
| 114 |
+
placeholder="E.g., How do Python dictionaries work?",
|
| 115 |
+
lines=2
|
| 116 |
+
)
|
| 117 |
+
submit_btn = gr.Button("Start Learning", variant="primary")
|
| 118 |
+
|
| 119 |
+
# Right Column: Resources Dashboard
|
| 120 |
+
with gr.Column(scale=1):
|
| 121 |
+
# BOX 2: Videos
|
| 122 |
+
video_box = gr.Markdown(
|
| 123 |
+
value="### 📺 Recommended Videos\n*Waiting for topic...*",
|
| 124 |
+
label="2. Video References"
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
# BOX 3: Articles/Courses
|
| 128 |
+
article_box = gr.Markdown(
|
| 129 |
+
value="### 📚 Articles & Courses\n*Waiting for topic...*",
|
| 130 |
+
label="3. Articles & Courses"
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
# BOX 4: Quiz
|
| 134 |
+
quiz_box = gr.Markdown(
|
| 135 |
+
value="### 🧠 Quick Quiz\n*Waiting for topic...*",
|
| 136 |
+
label="4. Knowledge Check"
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
# --- Interaction Logic ---
|
| 140 |
async def user_turn(user_message, history):
|
| 141 |
+
return "", history + [{"role": "user", "content": user_message}]
|
|
|
|
|
|
|
| 142 |
|
| 143 |
async def bot_turn(history):
|
| 144 |
+
last_message = history[-1]["content"]
|
|
|
|
| 145 |
|
| 146 |
+
# Get all 4 outputs from the agent
|
| 147 |
+
chat_text, video_text, article_text, quiz_text = await run_tutor_dashboard(last_message, [])
|
| 148 |
|
| 149 |
+
# Update Chatbot history
|
| 150 |
+
history.append({"role": "assistant", "content": chat_text})
|
| 151 |
+
|
| 152 |
+
# Return all 4 updates
|
| 153 |
+
return history, video_text, article_text, quiz_text
|
| 154 |
|
| 155 |
+
# Wire up the inputs and outputs
|
| 156 |
+
# Notice we now output to [chatbot, video_box, article_box, quiz_box]
|
| 157 |
+
submit_btn.click(
|
| 158 |
+
user_turn, [msg, chatbot], [msg, chatbot]
|
| 159 |
+
).then(
|
| 160 |
+
bot_turn, [chatbot], [chatbot, video_box, article_box, quiz_box]
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
msg.submit(
|
| 164 |
+
user_turn, [msg, chatbot], [msg, chatbot]
|
| 165 |
+
).then(
|
| 166 |
+
bot_turn, [chatbot], [chatbot, video_box, article_box, quiz_box]
|
| 167 |
)
|
| 168 |
|
| 169 |
# --- Launch ---
|