Learn how to handle user input with code snippets in n8n for Mistral AI by properly formatting, escaping, and structuring prompts to get accurate code analysis and feedback.
Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
To handle user input with code snippets when sending to Mistral in n8n, you need to properly format the user's code before sending it to the Mistral API. This involves escaping special characters, formatting the code as a proper Markdown code block, and structuring your n8n workflow to process and send this data correctly to the Mistral AI node.
Step 1: Understanding the Challenge
When working with Mistral AI in n8n, sending code snippets from user input requires proper formatting to ensure the code is recognized and processed correctly by the AI. The main challenges include:
Step 2: Setting Up Your n8n Workflow
First, you need to create a workflow in n8n that will receive user input, process it, and send it to Mistral:
Step 3: Creating a Webhook to Receive User Input
Start by setting up a Webhook node to receive the user's input containing code:
// Configure a Webhook node with:
// Method: POST
// Path: /code-analysis
// Response Mode: Last Node
This webhook will create an endpoint that can receive POST requests with JSON data containing the user's code snippet.
Step 4: Processing the User Input
Add a Function node to process the incoming data from the webhook:
// Function node code to process user input
const userInput = items[0].json.userInput || "";
const codeSnippet = items[0].json.codeSnippet || "";
// Format the code snippet with proper Markdown formatting for code
const formattedCodeSnippet = "`\n" + codeSnippet + "\n`";
// Create a structured prompt for Mistral
const prompt = `User Question: ${userInput}\n\nCode Snippet:\n${formattedCodeSnippet}\n\nPlease analyze this code and provide feedback.`;
// Return the formatted data
return {
json: {
prompt: prompt
}
};
This function takes the user input and code snippet, formats the code with triple backticks to create a proper Markdown code block, and creates a structured prompt for Mistral.
Step 5: Setting Up the Mistral AI Node
Now, connect the Function node to a Mistral AI node:
// Configure the Mistral AI node with:
// Operation: Chat Completion
// Model: Choose the appropriate Mistral model (e.g., mistral-medium, mistral-small)
// Messages: Use an expression to access the prompt from the previous node
// System Prompt: "You are a helpful assistant specializing in code analysis. When provided with code, analyze it for correctness, efficiency, and best practices."
In the Messages field, use an expression to reference the prompt created in the previous Function node:
[
{
"role": "user",
"content": "{{$node["Function"].json.prompt}}"
}
]
Step 6: Handling More Complex Code Formatting
For more complex code handling, you can enhance the Function node to better prepare the code:
// Enhanced Function node for better code handling
const userInput = items[0].json.userInput || "";
const codeSnippet = items[0].json.codeSnippet || "";
const language = items[0].json.language || ""; // Optional language specification
// Determine if a language was specified
const langSpecifier = language ? language : "";
// Format with language specification if provided
const formattedCodeSnippet = "`" + langSpecifier + "\n" + codeSnippet + "\n`";
// Escape any problematic characters in the user input
const sanitizedUserInput = userInput.replace(/[\\"\n]/g, match => {
if (match === '\\') return '\\\\\';
if (match === '"') return '\\"';
if (match === '\n') return '\n';
return match;
});
// Create a structured prompt for Mistral
const prompt = `User Question: ${sanitizedUserInput}\n\nCode Snippet:\n${formattedCodeSnippet}\n\nPlease analyze this code and provide feedback.`;
return {
json: {
prompt: prompt
}
};
This enhanced version allows for language specification in the code block and sanitizes special characters in the user input.
Step 7: Adding Context-Specific Instructions
To make your code analysis more specific, you can add context to your prompt:
// Function node with context-specific instructions
const userInput = items[0].json.userInput || "";
const codeSnippet = items[0].json.codeSnippet || "";
const language = items[0].json.language || "";
const analysisType = items[0].json.analysisType || "general"; // e.g., "security", "performance", "best-practices"
let analysisInstructions = "";
// Set specific instructions based on the analysis type
switch(analysisType) {
case "security":
analysisInstructions = "Focus on identifying security vulnerabilities, injection risks, and authentication issues.";
break;
case "performance":
analysisInstructions = "Focus on performance optimization, identifying bottlenecks, and suggesting efficiency improvements.";
break;
case "best-practices":
analysisInstructions = "Focus on code style, maintainability, and adherence to best practices for the given language.";
break;
default:
analysisInstructions = "Provide a general analysis of the code.";
}
// Format the code with language specifier
const formattedCodeSnippet = "`" + language + "\n" + codeSnippet + "\n`";
// Create the prompt with specific instructions
const prompt = `User Question: ${userInput}\n\nCode Snippet:\n${formattedCodeSnippet}\n\n${analysisInstructions}`;
return {
json: {
prompt: prompt
}
};
Step 8: Handling Multi-File Code Analysis
For scenarios where users need to submit multiple files or code snippets:
// Function node for multi-file code analysis
const userInput = items[0].json.userInput || "";
const codeFiles = items[0].json.codeFiles || []; // Array of file objects
// Format each file's code with its name and language
let formattedCode = "";
codeFiles.forEach(file => {
const fileName = file.name || "Unnamed File";
const language = file.language || "";
const code = file.code || "";
formattedCode += `\nFile: ${fileName}\n\`\`\`${language}\n${code}\n\`\`\`\n\n\`;
});
// Create the prompt with all files
const prompt = `User Question: ${userInput}\n\nCode Files:${formattedCode}\nPlease analyze these code files and their interactions.`;
return {
json: {
prompt: prompt
}
};
This approach lets users submit multiple files, which can be important for analyzing code that spans multiple modules.
Step 9: Processing Mistral's Response
After the Mistral AI node, add another Function node to process the response:
// Function node to process Mistral's response
const mistralResponse = items[0].json.choices[0].message.content;
// You can further process the response here if needed
// For example, extract code suggestions, format the analysis, etc.
return {
json: {
analysis: mistralResponse,
// Add any additional processed fields here
}
};
Step 10: Creating a Complete Response Webhook
Finally, add a Respond to Webhook node to send the results back to the user:
// Configure the Respond to Webhook node:
// Response Code: 200
// Response Data: {{$node["Process Response"].json.analysis}}
This completes the flow from receiving user input with code to returning Mistral's analysis.
Step 11: Enhancing with Error Handling
Add error handling to make your workflow more robust:
// Function node with error handling
try {
const userInput = items[0].json.userInput || "";
const codeSnippet = items[0].json.codeSnippet || "";
// Validate input
if (!codeSnippet) {
throw new Error("No code snippet provided");
}
// Proceed with formatting as before
const formattedCodeSnippet = "`\n" + codeSnippet + "\n`";
const prompt = `User Question: ${userInput}\n\nCode Snippet:\n${formattedCodeSnippet}\n\nPlease analyze this code.`;
return {
json: {
prompt: prompt
}
};
} catch (error) {
// Return a meaningful error
return {
json: {
error: true,
message: error.message,
prompt: "There was an error processing your code: " + error.message
}
};
}
Step 12: Adding Conditional Paths Based on Input Type
For more complex workflows, add an IF node to handle different types of code inputs:
// Function node to determine input type
const inputData = items[0].json;
let inputType = "unknown";
if (inputData.codeSnippet) {
inputType = "single-snippet";
} else if (Array.isArray(inputData.codeFiles) && inputData.codeFiles.length > 0) {
inputType = "multi-file";
} else if (inputData.githubRepo) {
inputType = "github-repo";
}
return {
json: {
originalData: inputData,
inputType: inputType
}
};
Then add an IF node that routes to different Function nodes based on the input type, with each Function node optimized for that specific type of input.
Step 13: Adding a Complete Example with All Components
Here's a complete example showing how all components work together:
// Example JSON request to your webhook
{
"userInput": "Can you optimize this function for performance?",
"language": "javascript",
"codeSnippet": "function fibonacci(n) {\n if (n <= 1) return n;\n return fibonacci(n-1) + fibonacci(n-2);\n}",
"analysisType": "performance"
}
The workflow processes this as follows:
Step 14: Testing Your Workflow
To test your workflow:
Here's a sample curl command to test your endpoint:
curl -X POST http://your-n8n-instance/webhook/code-analysis \\
-H "Content-Type: application/json" \\
-d '{
"userInput": "Is this code efficient?",
"language": "python",
"codeSnippet": "def bubble\_sort(arr):\n n = len(arr)\n for i in range(n):\n for j in range(0, n-i-1):\n if arr[j] > arr[j+1]:\n arr[j], arr[j+1] = arr[j+1], arr[j]\n return arr",
"analysisType": "performance"
}'
Step 15: Advanced Customization with Custom UI
For a more user-friendly experience, you can create a custom front-end that sends code to your n8n webhook:
// Example HTML/JS for a simple code submission form
Code Analysis Tool
Code Analysis Tool
This HTML page provides a simple interface for users to input their code, select a language and analysis type, and receive feedback.
Summary
By following these steps, you can create a robust n8n workflow that handles user code input, formats it properly for Mistral AI, and returns useful code analysis. The key aspects to remember are:
With these techniques, you can create powerful code analysis tools powered by Mistral AI within n8n workflows.
When it comes to serving you, we sweat the little things. That’s why our work makes a big impact.