class AIAgent extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.isOpen = false;
this.conversation = [
{
role: 'assistant',
content: 'š Hello! I\'m your AI coding assistant.\n\nI can help you with:\n\nš» Writing and debugging code\nš Explaining programming concepts\nš Setting up new projects\nā” Optimizing your existing code\n\nJust tell me what you need help with! For example:\n\n- "Write a Python function to calculate factorial"\n- "Explain how React hooks work"\n- "Help me debug this Node.js error"\n- "Create a React component for a login form"'
}
];
this.projectContext = {
currentFile: null,
projectType: null,
language: null
};
}
connectedCallback() {
this.render();
this.setupEventListeners();
}
render() {
this.shadowRoot.innerHTML = `
`;
}
chatMessages.scrollTop = chatMessages.scrollHeight;
}
async callGrokAPI(message) {
// Simulated API call - replace with actual API in production
try {
// Check for special commands
if (message.toLowerCase().includes('create project')) {
return this.handleProjectCreation(message);
} else if (message.toLowerCase().includes('write code')) {
return this.handleCodeRequest(message);
} else if (message.toLowerCase().includes('explain')) {
return this.handleExplanationRequest(message);
} else if (message.toLowerCase().includes('debug')) {
return this.handleDebugRequest(message);
}
// Default response
return `I can help you with coding tasks. Try asking me to:
- "Create a new React project"
- "Write a Python function to calculate factorial"
- "Explain how promises work in JavaScript"
- "Debug this code: [paste your code]"`;
} catch (error) {
console.error('Error:', error);
return 'Sorry, I encountered an error. Please try again.';
}
}
handleProjectCreation(message) {
// Extract project type from message
const projectType = message.match(/create (.*?) project/i)?.[1] || 'web';
this.projectContext.projectType = projectType;
let response = `I'll help you create a ${projectType} project. `;
switch(projectType.toLowerCase()) {
case 'react':
response += `Here's how to set up a basic React project:\n\n1. Create these files:\n- index.html\n- app.js\n- styles.css\n\n2. Add this to index.html:\n\`\`\`html\n\n\n\n React App\n \n\n\n \n \n\n\n\`\`\`\n\n3. Add this to app.js:\n\`\`\`javascript\nimport React from 'react';\nimport ReactDOM from 'react-dom';\n\nfunction App() {\n return (\n
\n
Hello React!
\n
\n );\n}\n\nReactDOM.render(, document.getElementById('root'));\n\`\`\``;
this.projectContext.language = 'javascript';
break;
case 'python':
response += `Here's a basic Python project structure:\n\n1. Create main.py:\n\`\`\`python\ndef main():\n print("Hello Python!")\n\nif __name__ == "__main__":\n main()\n\`\`\`\n\n2. Create requirements.txt for dependencies`;
this.projectContext.language = 'python';
break;
default:
response += `Here's a basic web project structure:\n\n1. Create index.html:\n\`\`\`html\n\n\n\n My Project\n \n\n\n
Hello World!
\n \n\n\n\`\`\`\n\n2. Create styles.css for styling\n3. Create script.js for JavaScript`;
this.projectContext.language = 'javascript';
}
return response;
}
handleCodeRequest(message) {
if (!this.projectContext.language) {
return "First tell me what kind of project you're working on (e.g., 'Create a React project') so I can provide language-specific help.";
}
const codeType = message.match(/write (.*?) code/i)?.[1] || 'function';
let codeExample = '';
switch(this.projectContext.language) {
case 'javascript':
if (codeType.includes('function')) {
codeExample = `\`\`\`javascript\n// Function example\nfunction ${this.getFunctionName(message)}(${this.getFunctionParams(message)}) {\n // ${this.getFunctionDescription(message)}\n return result;\n}\n\`\`\``;
} else if (codeType.includes('component')) {
codeExample = `\`\`\`javascript\n// React component example\nfunction ${this.getComponentName(message)}() {\n return (\n
\n
${this.getComponentTitle(message)}
\n
\n );\n}\n\`\`\``;
}
break;
case 'python':
codeExample = `\`\`\`python\ndef ${this.getFunctionName(message)}(${this.getFunctionParams(message)}):\n """\n ${this.getFunctionDescription(message)}\n """\n return result\n\`\`\``;
break;
default:
codeExample = `Here's a generic code example for your request:\n\`\`\`\n// Implement your ${codeType} here\n\`\`\``;
}
return `Here's ${this.projectContext.language} code for ${codeType}:\n\n${codeExample}\n\nWould you like me to explain any part of this?`;
}
handleExplanationRequest(message) {
const concept = message.match(/explain (.*)/i)?.[1] || 'this concept';
return `Here's an explanation of ${concept}:\n\n${this.getConceptExplanation(concept)}\n\nLet me know if you'd like more details or examples.`;
}
handleDebugRequest(message) {
const codeBlock = message.match(/```[\s\S]*?```/)?.[0] || 'your code';
return `Looking at ${codeBlock.includes('```') ? 'the code' : 'your code'}, here are potential issues to check:\n\n1. Syntax errors\n2. Variable scope issues\n3. Type mismatches\n4. Async/await problems\n\nFor more specific help, please share the exact error message you're getting.`;
}
// Helper methods
getFunctionName(message) {
return message.match(/function named (.*?)[\s,.]/i)?.[1] || 'exampleFunction';
}
getFunctionParams(message) {
return message.match(/parameters? (.*?)[\s,.]/i)?.[1] || 'param1, param2';
}
getFunctionDescription(message) {
return message.match(/that (.*?)[\s,.]/i)?.[1] || 'Does something useful';
}
getComponentName(message) {
return message.match(/component named (.*?)[\s,.]/i)?.[1] || 'ExampleComponent';
}
getComponentTitle(message) {
return message.match(/title (.*?)[\s,.]/i)?.[1] || 'My Component';
}
getConceptExplanation(concept) {
const explanations = {
'react': 'React is a JavaScript library for building user interfaces. It lets you create reusable UI components and efficiently update the DOM when data changes.',
'python': 'Python is a high-level, interpreted programming language known for its readability and versatility. It\'s great for web development, data analysis, AI, and more.',
'javascript': 'JavaScript is the programming language of the web. It runs in browsers and can manipulate HTML/CSS, handle user interactions, and make network requests.',
'promises': 'Promises in JavaScript represent the eventual completion (or failure) of an asynchronous operation and its resulting value. They help avoid callback hell.'
};
return explanations[concept.toLowerCase()] ||
`I'll explain ${concept} in simple terms...`;
}
}
customElements.define('ai-agent', AIAgent);