1- #!/usr/bin/env python3
2- """
3- AI Code Assistant - Gradio Web Interface
4- Query your codebase with natural language
5- """
6- import os
71import gradio as gr
8- from query_engine import QueryEngine
2+ import requests
93
10- # Global engine
11- engine = None
12- is_indexed = False
4+ OLLAMA_URL = "http://localhost:11434/api/generate"
5+ MODEL = "qwen2.5-coder"
136
7+ def query_code (question : str ) -> str :
8+ prompt = f"""You are a code assistant. Answer this question about code:
149
15- def index_codebase (path ):
16- """Index a codebase"""
17- global engine , is_indexed
18-
19- if not path :
20- return "⚠️ Please provide a path to your codebase"
21-
22- if not os .path .exists (path ):
23- return f"⚠️ Path does not exist: { path } "
24-
25- try :
26- engine = QueryEngine ()
27- result = engine .index (path )
28- is_indexed = True
29- return f"✅ Indexed { result .get ('files' , 0 )} files with { result .get ('documents' , 0 )} documents"
30- except Exception as e :
31- return f"❌ Error: { str (e )} "
32-
33-
34- def ask_question (question ):
35- """Ask a question about the codebase"""
36- global engine , is_indexed
37-
38- if not is_indexed :
39- return "⚠️ Please index your codebase first using the Index tab"
40-
41- if not question :
42- return ""
43-
44- try :
45- answer = engine .query (question )
46- return answer
47- except Exception as e :
48- return f"❌ Error: { str (e )} "
49-
50-
51- def analyze_file (file_path ):
52- """Analyze a single file"""
53- global engine
54-
55- if not engine :
56- return "⚠️ Initialize the engine first"
57-
58- if not file_path or not os .path .exists (file_path ):
59- return "⚠️ File not found"
10+ Question: { question }
6011
12+ Provide a helpful answer."""
6113 try :
62- result = engine .analyzer .analyze_file (file_path )
63-
64- output = f"### 📊 Analysis: { result .get ('file' , 'Unknown' )} \n \n "
65- output += f"**Language:** { result .get ('language' , 'Unknown' )} \n \n "
66- output += f"**Lines:** { result .get ('lines' , 0 )} \n \n "
67- output += f"**Size:** { result .get ('size' , 0 )} bytes\n \n "
68-
69- if result .get ('functions' ):
70- output += "**Functions:**\n "
71- for fn in result ['functions' ][:10 ]:
72- output += f"- `{ fn } `\n "
73-
74- if result .get ('classes' ):
75- output += "\n **Classes:**\n "
76- for cls in result ['classes' ][:10 ]:
77- output += f"- `{ cls } `\n "
78-
79- return output
80-
81- except Exception as e :
82- return f"❌ Error: { str (e )} "
83-
84-
85- # Build Gradio Interface
86- with gr .Blocks (title = "AI Code Assistant" , theme = gr .themes .Soft ()) as app :
87- gr .Markdown ("# 🤖 AI Code Assistant" )
88- gr .Markdown ("Ask questions about your codebase in natural language" )
89-
90- with gr .Tab ("💬 Ask" ):
91- gr .Markdown ("### Query your codebase" )
92-
93- with gr .Row ():
94- with gr .Column (scale = 3 ):
95- chatbot = gr .Chatbot (height = 400 )
96- msg = gr .Textbox (
97- placeholder = "e.g., How does authentication work? Where is the main function?" ,
98- show_label = False
99- )
100- with gr .Row ():
101- submit_btn = gr .Button ("Send" , variant = "primary" )
102- clear_btn = gr .Button ("Clear" )
103-
104- with gr .Column (scale = 1 ):
105- gr .Markdown ("### Tips" )
106- gr .Markdown ("""
107- - Ask about specific features
108- - Find where functions are defined
109- - Get help understanding code
110- - Ask for code improvements
111- """ )
112-
113- def respond (message , history ):
114- response = ask_question (message )
115- history .append ((message , response ))
116- return "" , history
117-
118- submit_btn .click (respond , [msg , chatbot ], [msg , chatbot ])
119- msg .submit (respond , [msg , chatbot ], [msg , chatbot ])
120- clear_btn .click (lambda : (None , []), outputs = [msg , chatbot ])
121-
122- with gr .Tab ("📂 Index" ):
123- gr .Markdown ("### Index your codebase" )
124-
125- with gr .Row ():
126- with gr .Column ():
127- codebase_path = gr .Textbox (
128- label = "Codebase Path" ,
129- placeholder = "./my_project"
130- )
131- index_btn = gr .Button ("🔍 Index Codebase" , variant = "primary" )
132-
133- with gr .Column ():
134- status_output = gr .Textbox (label = "Status" , lines = 5 )
135-
136- index_btn .click (
137- index_codebase ,
138- inputs = [codebase_path ],
139- outputs = status_output
14+ response = requests .post (
15+ OLLAMA_URL ,
16+ json = {"model" : MODEL , "prompt" : prompt , "stream" : False },
17+ timeout = 60
14018 )
141-
142- with gr .Tab ("📊 Analyze" ):
143- gr .Markdown ("### Analyze a single file" )
144-
145- with gr .Row ():
146- with gr .Column ():
147- file_path = gr .Textbox (
148- label = "File Path" ,
149- placeholder = "./src/main.py"
150- )
151- analyze_btn = gr .Button ("Analyze" , variant = "primary" )
152-
153- with gr .Column ():
154- analysis_output = gr .Markdown ()
155-
156- analyze_btn .click (
157- analyze_file ,
158- inputs = [file_path ],
159- outputs = analysis_output
160- )
161-
162- with gr .Tab ("ℹ️ About" ):
163- gr .Markdown ("""
164- ## AI Code Assistant
165-
166- An AI-powered coding assistant that understands YOUR codebase:
167- - 🧠 Learns your entire codebase
168- - 💡 Suggests improvements
169- - 🧪 Generates tests
170- - 📖 Documents code
171- - 🔍 Finds bugs
172- - 💬 Chat in natural language
173-
174- ### Supported Languages
175- Python, JavaScript, TypeScript, Java, Go, Rust, C/C++, C#, Ruby, PHP, Swift, Kotlin, and more!
176- """ )
177-
178- # Launch
179- if __name__ == "__main__" :
180- print ("🚀 Starting AI Code Assistant Web UI..." )
181- print (" Open http://localhost:7861 in your browser" )
182- app .launch (server_name = "0.0.0.0" , server_port = 7861 )
19+ if response .status_code == 200 :
20+ return response .json ().get ("response" , "No answer" )
21+ except Exception as e :
22+ return f"Error: { e } "
23+ return "Ollama not running"
24+
25+ def ask (q , history ):
26+ answer = query_code (q )
27+ history .append ((q , answer ))
28+ return "" , history
29+
30+ with gr .Blocks (title = "💻 AI Code Assistant" ) as demo :
31+ gr .Markdown ("# 💻 AI Code Assistant\n ### Ask about YOUR code" )
32+ chatbot = gr .Chatbot (height = 500 )
33+ question = gr .Textbox (label = "Ask" , placeholder = "How does auth work?" )
34+ ask_btn = gr .Button ("💬 Ask" , variant = "primary" )
35+ question .submit (lambda q , h : ask (q , h ), [question , chatbot ], [question , chatbot ])
36+ ask_btn .click (lambda q , h : ask (q , h ), [question , chatbot ], [question , chatbot ])
37+
38+ demo .launch (server_name = "0.0.0.0" , server_port = 7863 )
0 commit comments