File size: 13,819 Bytes
dfc517e
1666a21
 
37dde34
7cdbd20
1666a21
180df23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb04de8
37dde34
 
4dec0f2
1666a21
 
dfc517e
37dde34
1666a21
 
dfc517e
1666a21
 
eb04de8
37dde34
1666a21
37dde34
e759860
1666a21
37dde34
1666a21
37dde34
eb04de8
1666a21
37dde34
 
 
 
 
 
dfc517e
1666a21
8327e4e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1666a21
 
 
 
eb04de8
1666a21
dfc517e
1666a21
 
 
882008c
37dde34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1666a21
 
 
 
 
 
37dde34
 
 
1666a21
 
37dde34
1666a21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37dde34
 
 
 
 
 
dfc517e
1666a21
 
 
 
 
 
 
 
 
069bc6a
eb04de8
1666a21
 
 
eb04de8
37336a7
37dde34
1666a21
 
37dde34
1666a21
37dde34
 
1666a21
 
37dde34
1666a21
 
 
 
 
 
 
 
37336a7
1666a21
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
import gradio as gr
import anthropic
from typing import List, Dict, Optional, Tuple
import json

# Constants
DEFAULT_SYSTEM_PROMPT = """<AIFramework>
    <Identity>
        You are an elite Python programming expert powered by Claude 3.5 Sonnet, specializing in developing complex, production-grade software solutions. You excel at writing extensive, well-structured code and can handle any scale of programming challenge.
    </Identity>

    <CoreCompetencies>
        <PythonExpertise>
            <Specialization>
                - Master-level Python 3.x development with deep knowledge of language internals
                - Expert in advanced features: metaclasses, decorators, generators, async/await
                - Proficient in memory management and optimization techniques
                - Deep understanding of Python's GIL and concurrency models
            </Specialization>
            <Libraries>
                - Mastery of standard library and all major frameworks
                - Expert in: Django, FastAPI, Flask, SQLAlchemy, Pydantic
                - Data science: NumPy, Pandas, SciPy, scikit-learn
                - Testing: pytest, unittest, hypothesis
                - Async frameworks: asyncio, aiohttp, uvicorn
            </Libraries>
            <BestPractices>
                - Expert implementation of all PEP standards
                - Advanced Pythonic code patterns and idioms
                - Performance optimization techniques
                - Clean code principles and patterns
            </BestPractices>
        </PythonExpertise>

        <CodeQuality>
            <Architecture>
                - Design scalable, maintainable software architectures
                - Implement enterprise-level design patterns
                - Create modular, extensible systems
                - Develop microservices architectures
            </Architecture>
            <Performance>
                - Optimize for speed, memory efficiency, and scalability
                - Profile and improve code performance
                - Implement caching strategies
                - Optimize database queries and data structures
            </Performance>
            <Testing>
                - Comprehensive testing strategies
                - Test-driven development (TDD)
                - Behavior-driven development (BDD)
                - Performance testing and benchmarking
            </Testing>
        </CodeQuality>
    </CoreCompetencies>

    <CodingGuidelines>
        <CodeStructure>
            - Write modular, reusable code with clear separation of concerns
            - Implement proper dependency injection and inversion of control
            - Design extensible class hierarchies and interfaces
            - Create well-structured package organization
            - Use appropriate design patterns
            - Implement clean architecture principles
        </CodeStructure>

        <Documentation>
            - Write detailed docstrings following Google/NumPy style
            - Include comprehensive type hints and return type annotations
            - Document complex algorithms and business logic
            - Provide usage examples in docstrings
            - Create detailed API documentation
            - Include architecture diagrams when needed
        </Documentation>

        <ErrorHandling>
            - Implement comprehensive exception handling
            - Create custom exception hierarchies when appropriate
            - Add detailed error messages and logging
            - Handle edge cases and invalid inputs
            - Implement retry mechanisms where appropriate
            - Add circuit breakers for external services
        </ErrorHandling>

        <Testing>
            - Write comprehensive unit tests with pytest
            - Include integration and end-to-end tests
            - Add property-based testing for complex functions
            - Achieve high test coverage
            - Implement mutation testing
            - Add load and stress testing
        </Testing>
    </CodingGuidelines>

    <ResponseBehavior>
        <CodeDelivery>
            - Provide complete, production-ready code solutions
            - Include all necessary imports and dependencies
            - Structure long code into multiple files when appropriate
            - Add setup instructions and requirements.txt
            - Include deployment configurations when relevant
            - Provide Docker configurations if needed
        </CodeDelivery>

        <Explanations>
            - Break down complex solutions into clear steps
            - Explain architectural decisions and tradeoffs
            - Provide performance analysis when relevant
            - Include debugging tips and common pitfalls
            - Add scaling considerations
            - Discuss alternative approaches
        </Explanations>

        <BestPractices>
            - Follow SOLID principles strictly
            - Implement appropriate design patterns
            - Consider security implications
            - Optimize for maintainability and readability
            - Follow 12-factor app principles
            - Implement CI/CD best practices
        </BestPractices>
    </ResponseBehavior>

    <Specialties>
        <LongCodeManagement>
            - Break down large codebases into manageable modules
            - Implement clear folder structures
            - Create comprehensive documentation
            - Use proper versioning and dependency management
            - Implement modular architecture
            - Create clear API boundaries
        </LongCodeManagement>

        <Debugging>
            - Provide sophisticated debugging strategies
            - Implement comprehensive logging
            - Add performance profiling
            - Include error tracking and reporting
            - Use debugging tools effectively
            - Implement monitoring solutions
        </Debugging>

        <Security>
            - Implement security best practices
            - Handle sensitive data properly
            - Prevent common vulnerabilities
            - Add input validation and sanitization
            - Implement authentication and authorization
            - Follow OWASP guidelines
        </Security>

        <DataManagement>
            - Design efficient database schemas
            - Optimize database queries
            - Implement caching strategies
            - Handle large-scale data processing
            - Implement data validation
            - Ensure data integrity
        </DataManagement>
    </Specialties>
</AIFramework>"""

MAX_TOKENS = 4096
TEMPERATURE = 0.7

class ChatState:
    """Manages the state of the chat session"""
    def __init__(self):
        self.client: Optional[anthropic.Client] = None
        self.system_prompt: str = DEFAULT_SYSTEM_PROMPT
        self.history: List[Tuple[str, str]] = []

    def initialize_client(self, api_key: str) -> Tuple[bool, str]:
        """Initialize the Anthropic client with the provided API key"""
        try:
            self.client = anthropic.Client(api_key=api_key)
            # Test the API key with a minimal request
            self.client.messages.create(
                model="claude-3-5-sonnet-20241022",
                max_tokens=10,
                messages=[{"role": "user", "content": "test"}]
            )
            return True, "API key validated successfully!"
        except Exception as e:
            self.client = None
            return False, f"Error validating API key: {str(e)}"

    def update_system_prompt(self, new_prompt: str) -> str:
        """Update the system prompt"""
        self.system_prompt = new_prompt
        return "System prompt updated successfully!"

    def generate_response(self, message: str) -> str:
        """Generate a response using the Claude API"""
        if not self.client:
            return "Please enter a valid API key first."
    
        try:
            # Convert history to message format
            messages = []
            for human_msg, assistant_msg in self.history:
                messages.extend([
                    {"role": "user", "content": human_msg},
                    {"role": "assistant", "content": assistant_msg}
                ])
            
            # Add the current message
            messages.append({"role": "user", "content": message})
    
            # Make API call with system parameter
            response = self.client.messages.create(
                model="claude-3-5-sonnet-20241022",
                max_tokens=MAX_TOKENS,
                temperature=TEMPERATURE,
                system=self.system_prompt,  # Pass system prompt as a separate parameter
                messages=messages
            )
    
            return response.content[0].text
    
        except Exception as e:
            return f"Error generating response: {str(e)}"

    def clear_history(self) -> None:
        """Clear the conversation history"""
        self.history = []

def create_demo() -> gr.Blocks:
    """Create the Gradio interface"""
    chat_state = ChatState()

    with gr.Blocks(title="Claude Coding Assistant", theme=gr.themes.Soft()) as demo:
        with gr.Row():
            # Main chat area (2/3 width)
            with gr.Column(scale=2):
                gr.Markdown("""
                # Claude Coding Assistant πŸ€–πŸ’»
                
                A specialized coding assistant powered by Claude 3.5 Sonnet. Features:
                - Complete code solutions with best practices
                - Detailed explanations and documentation
                - Code review and optimization suggestions
                - Security considerations and design patterns
                """)

                # API Key input section
                with gr.Row():
                    api_key_input = gr.Textbox(
                        label="Anthropic API Key",
                        placeholder="Enter your API key...",
                        type="password",
                        scale=4
                    )
                    validate_btn = gr.Button("Validate API Key", scale=1)
                    status_text = gr.Textbox(label="Status", interactive=False, scale=2)

                # Chat interface
                chatbot = gr.Chatbot(
                    height=600,
                    show_label=False,
                    container=True,
                    show_copy_button=True
                )
                
                with gr.Row():
                    message_input = gr.Textbox(
                        label="Your message",
                        placeholder="Ask me about coding, software design, or technical problems...",
                        lines=3,
                        scale=4
                    )
                    submit_btn = gr.Button("Send", scale=1)
                    clear_btn = gr.Button("Clear Chat", scale=1)

            # Sidebar for system prompt (1/3 width)
            with gr.Column(scale=1):
                gr.Markdown("### System Prompt Editor")
                system_prompt_input = gr.TextArea(
                    value=DEFAULT_SYSTEM_PROMPT,
                    label="Customize the AI's behavior",
                    lines=20,
                    placeholder="Enter system prompt..."
                )
                update_prompt_btn = gr.Button("Update System Prompt")
                prompt_status = gr.Textbox(label="Prompt Status", interactive=False)

        # Event handlers
        def validate_api_key(api_key: str) -> str:
            success, message = chat_state.initialize_client(api_key)
            return message

        def update_system_prompt(new_prompt: str) -> str:
            return chat_state.update_system_prompt(new_prompt)

        def respond(message: str, history: List[Tuple[str, str]]) -> Tuple[List[Tuple[str, str]], str]:
            if not chat_state.client:
                return history + [("", "Please validate your API key first.")], ""
            
            response = chat_state.generate_response(message)
            chat_state.history = history + [(message, response)]
            return chat_state.history, ""

        def clear_chat() -> Tuple[List[Tuple[str, str]], str]:
            chat_state.clear_history()
            return [], ""

        # Connect event handlers
        validate_btn.click(
            validate_api_key,
            inputs=[api_key_input],
            outputs=[status_text]
        )

        update_prompt_btn.click(
            update_system_prompt,
            inputs=[system_prompt_input],
            outputs=[prompt_status]
        )

        submit_btn.click(
            respond,
            inputs=[message_input, chatbot],
            outputs=[chatbot, message_input]
        )

        message_input.submit(
            respond,
            inputs=[message_input, chatbot],
            outputs=[chatbot, message_input]
        )

        clear_btn.click(
            clear_chat,
            outputs=[chatbot, message_input]
        )

        # Add examples
        gr.Examples(
            examples=[
                "Can you help me implement a binary search tree in Python with type hints?",
                "Review this code for security issues:\n```python\ndef process_user_input(data):\n    result = eval(data)\n    return result```",
                "Explain the SOLID principles with practical examples in TypeScript.",
                "How would you implement rate limiting in a REST API?",
            ],
            inputs=message_input,
            label="Example Questions"
        )

    return demo

# Create and launch the demo
demo = create_demo()

# For local testing
if __name__ == "__main__":
    demo.launch()