Skip to content

Building a RAG powered Django Coding Assistant

Overview

This example demonstrates creating a specialized AI-powered flow for Django developers, providing documentation-based code assistance and guidance.

Create the Dataset

python
from mira_sdk import MiraClient

client = MiraClient(config={"API_KEY": "YOUR_API_KEY"})

author = "your_username"
dataset_name = "django_docs"

client.dataset.create(f"{author}/{dataset_name}", "Optional description")

urls = [
    "https://docs.djangoproject.com/en/4.2/topics/db/models/",
    "https://docs.djangoproject.com/en/4.2/topics/forms/",
    "https://docs.djangoproject.com/en/4.2/topics/auth/",
    "https://docs.djangoproject.com/en/4.2/ref/class-based-views/"
]

for url in urls:
    result = client.dataset.add_source(f"{author}/{dataset_name}", url=f"{url}")

Set up Flow Configuration

yaml
version: "1.0.0"

metadata:
  name: "django-code-assistant"
  description: "AI assistant for Django framework coding help"
  author: "your_username"
  tags: [django, python, web-development]
  private: false

inputs:
  query:
    type: string
    description: "Your Django coding question or code generation request"
    required: true
    example: "How to create a custom user model in Django?"

model:
  provider: "meta"
  name: "llama-3.1-405b-instruct"

dataset:
  source: "your_username/django_docs"

prompt: |
  You are an expert Django Code Assistant with the following guidelines:
  
  Role:
  - Provide precise, documentation-backed solutions for Django development
  - Explain Django concepts with clarity and depth

  Coding Standards:
  - Follow Django best practices
  - Use type hints and docstrings
  - Demonstrate modern Python and Django conventions
  - Provide context and reasoning for code approaches

  User's query: {query}

  Response Format:
  - Start with a concise explanation of the approach
  - Include a complete, runnable code example
  - Add comments explaining key implementation details
  - Suggest potential variations or improvements
  - Reference relevant Django documentation when applicable

readme: |
  # Django Code Assistant

  An AI-powered assistant for Django developers, providing:
  - Code generation
  - Documentation-based guidance
  - Best practice recommendations

  ## Usage Examples
  - "Create a custom user model"
  - "Implement user authentication"
  - "Explain Django model relationships"

Test your Flow Locally

python
from mira_sdk import MiraClient, Flow

client = MiraClient(config={"API_KEY": "YOUR_API_KEY"})

flow = Flow(source="/path/to/your/flow.yaml")

input_dict = {"query": "How to create a custom user model in Django?"}
response = client.flow.test(flow, input_dict)
print(response)

Deploy your Flow

python
from mira_sdk import MiraClient
from mira_sdk.exceptions import FlowError

client = MiraClient(config={"API_KEY": "YOUR_API_KEY"})

try:
    client.flow.deploy(flow)
    print("Flow deployed successfully!")
except FlowError as e:
    print(f"Error occurred: {str(e)}")

Use your Deployed Flow

python
from mira_sdk import MiraClient

client = MiraClient(config={"API_KEY": "YOUR_API_KEY"})

flow_name = "your_username/django-code-assistant"
input_data = {"query": "How to create a custom user model in Django?"}

result = client.flow.execute(flow_name, input_data)
print(result)

Output

python
# Custom User Model Implementation

# accounts/models.py
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.utils.translation import gettext_lazy as _

class CustomUser(AbstractUser):
    """
    Custom user model extending Django's AbstractUser.
    Allows additional fields and customization.
    """
    # Example additional fields
    bio = models.TextField(_('bio'), blank=True)
    birth_date = models.DateField(_('birth date'), null=True, blank=True)
    
    def __str__(self):
        """
        String representation of the user model.
        """
        return self.username

# settings.py configuration
# Add this to tell Django to use your custom user model
AUTH_USER_MODEL = 'accounts.CustomUser'

# Recommended: Create a custom UserAdmin if needed
# accounts/admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import CustomUser

class CustomUserAdmin(UserAdmin):
    """
    Custom admin configuration for the CustomUser model.
    """
    model = CustomUser
    list_display = ['username', 'email', 'birth_date', 'is_staff']
    fieldsets = UserAdmin.fieldsets + (
        (None, {'fields': ('bio', 'birth_date')}),
    )

admin.site.register(CustomUser, CustomUserAdmin)

This output provides clear and concise implementation steps, along with essential code snippets. It maintains a professional and informative tone, ensuring that users can quickly apply the solution to their Django projects.