780 lines
27 KiB
Plaintext
780 lines
27 KiB
Plaintext
File ./exercise_tracker/models.py
|
|
# exercise_tracker/models.py
|
|
from django.db import models
|
|
|
|
|
|
class Session(models.Model):
|
|
name = models.CharField(max_length=100, blank=True)
|
|
date = models.DateField()
|
|
location = models.CharField(max_length=100, blank=True)
|
|
|
|
def __str__(self):
|
|
return f"{self.name or 'Workout'} ({self.date})"
|
|
|
|
|
|
class Exercise(models.Model):
|
|
session = models.ForeignKey(Session, related_name='exercises', on_delete=models.CASCADE)
|
|
name = models.CharField(max_length=255)
|
|
|
|
def __str__(self):
|
|
return f"{self.name} in {self.session.name or 'Workout'}"
|
|
|
|
|
|
class Set(models.Model):
|
|
exercise = models.ForeignKey(Exercise, related_name='sets', on_delete=models.CASCADE)
|
|
|
|
reps = models.IntegerField(null=True, blank=True)
|
|
weight_kg = models.FloatField(null=True, blank=True)
|
|
|
|
distance_meters = models.FloatField(null=True, blank=True)
|
|
duration_seconds = models.IntegerField(null=True, blank=True)
|
|
|
|
is_personal_record = models.BooleanField(default=False)
|
|
|
|
def __str__(self):
|
|
if self.distance_meters is not None:
|
|
mins = self.duration_seconds // 60 if self.duration_seconds else 0
|
|
secs = self.duration_seconds % 60 if self.duration_seconds else 0
|
|
return f"Cardio: {self.exercise.name} ({mins}m {secs}s, {self.distance_meters / 1000:.2f}km)"
|
|
reps_str = self.reps or "∞"
|
|
weight_str = f"{self.weight_kg:.1f}" if self.weight_kg is not None else ""
|
|
return f"{reps_str}x{weight_str}kg ({self.exercise.name})"
|
|
-----------------------------------------------------------------------------
|
|
File ./exercise_tracker/migrations/__init__.py
|
|
-----------------------------------------------------------------------------
|
|
File ./exercise_tracker/tasks.py
|
|
# exercise_tracker/tasks.py
|
|
from core.base import TaskModule
|
|
from .models import Session, Exercise, Set
|
|
|
|
|
|
class ExerciseTracker(TaskModule):
|
|
MODULE_NAME = "exercise_tracker"
|
|
DESCRIPTION = "Log workouts, exercises, and training sets (strength & cardio)"
|
|
|
|
TOOLS = [
|
|
{
|
|
"type": "function",
|
|
"function": {
|
|
"name": "log_workout",
|
|
"description": "Record a complete workout session with exercises and sets",
|
|
"parameters": {
|
|
"type": "object",
|
|
"properties": {
|
|
"session_name": {"type": "string"},
|
|
"date": {"type": "string", "format": "date"},
|
|
"exercises": {
|
|
"type": "array",
|
|
"items": {
|
|
"type": "object",
|
|
"properties": {
|
|
"exercise_name": {"type": "string"},
|
|
"sets": {
|
|
"type": "array",
|
|
"items": {
|
|
"type": "object",
|
|
"properties": {
|
|
# Strength options
|
|
"reps": {"type": "integer"},
|
|
"weight_kg": {"type": "number"},
|
|
|
|
# Cardio options
|
|
"duration_seconds": {"type": "integer"},
|
|
"distance_meters": {"type": "number"}
|
|
}
|
|
}
|
|
}
|
|
},
|
|
"required": ["exercise_name"]
|
|
}
|
|
}
|
|
},
|
|
"required": ["session_name", "date", "exercises"]
|
|
}
|
|
}
|
|
}
|
|
]
|
|
|
|
@classmethod
|
|
def execute_tool(cls, tool_name: str, arguments: dict) -> dict:
|
|
if tool_name == "log_workout":
|
|
session = Session.objects.create(name=arguments["session_name"], date=arguments["date"])
|
|
|
|
for ex_data in arguments.get("exercises", []):
|
|
exercise = Exercise.objects.create(session=session, name=ex_data["exercise_name"])
|
|
|
|
for set_data in ex_data.get("sets", []):
|
|
Set.objects.create(
|
|
exercise=exercise,
|
|
reps=set_data.get("reps"),
|
|
weight_kg=set_data.get("weight_kg"),
|
|
duration_seconds=set_data.get("duration_seconds"),
|
|
distance_meters=set_data.get("distance_meters")
|
|
)
|
|
|
|
return {"status": "success", "message": f"Logged workout: {session.name}"}
|
|
|
|
raise ValueError(f"Unknown tool: {tool_name}")
|
|
-----------------------------------------------------------------------------
|
|
File ./exercise_tracker/__init__.py
|
|
-----------------------------------------------------------------------------
|
|
File ./dagda/settings.py
|
|
"""
|
|
Django settings for dagda project.
|
|
|
|
Generated by 'django-admin startproject' using Django 6.1.3.
|
|
|
|
For more information on this file, see
|
|
https://docs.djangoproject.com/en/6.1/topics/settings/
|
|
|
|
For the full list of settings and their values, see
|
|
https://docs.djangoproject.com/en/6.1/ref/settings/
|
|
"""
|
|
|
|
from pathlib import Path
|
|
|
|
# Build paths inside the project like this: BASE_DIR / 'subdir'.
|
|
BASE_DIR = Path(__file__).resolve().parent.parent
|
|
|
|
|
|
# Quick-start development settings - unsuitable for production
|
|
# See https://docs.djangoproject.com/en/6.1/howto/deployment/checklist/
|
|
|
|
# SECURITY WARNING: keep the secret key used in production secret!
|
|
SECRET_KEY = 'django-insecure-jby^z#toz(p!$z=gr7+p8^d(qq1-yvb)8#+7ousf+)=&k-5zx^'
|
|
|
|
# SECURITY WARNING: don't run with debug turned on in production!
|
|
DEBUG = True
|
|
|
|
ALLOWED_HOSTS = ['*']
|
|
|
|
|
|
# Application definition
|
|
|
|
INSTALLED_APPS = [
|
|
'core',
|
|
'meal_tracker',
|
|
'exercise_tracker',
|
|
'calendar',
|
|
|
|
'django.contrib.admin',
|
|
'django.contrib.auth',
|
|
'django.contrib.contenttypes',
|
|
'django.contrib.sessions',
|
|
'django.contrib.messages',
|
|
'django.contrib.staticfiles',
|
|
]
|
|
|
|
MIDDLEWARE = [
|
|
'django.middleware.security.SecurityMiddleware',
|
|
'django.contrib.sessions.middleware.SessionMiddleware',
|
|
'django.middleware.common.CommonMiddleware',
|
|
'django.middleware.csrf.CsrfViewMiddleware',
|
|
'django.contrib.auth.middleware.AuthenticationMiddleware',
|
|
'django.contrib.messages.middleware.MessageMiddleware',
|
|
'django.middleware.clickjacking.XFrameOptionsMiddleware',
|
|
]
|
|
|
|
ROOT_URLCONF = 'dagda.urls'
|
|
|
|
TEMPLATES = [
|
|
{
|
|
'BACKEND': 'django.template.backends.django.DjangoTemplates',
|
|
'DIRS': [BASE_DIR / 'templates']
|
|
,
|
|
'APP_DIRS': True,
|
|
'OPTIONS': {
|
|
'context_processors': [
|
|
'django.template.context_processors.request',
|
|
'django.contrib.auth.context_processors.auth',
|
|
'django.contrib.messages.context_processors.messages',
|
|
],
|
|
},
|
|
},
|
|
]
|
|
|
|
WSGI_APPLICATION = 'dagda.wsgi.application'
|
|
|
|
|
|
# Database
|
|
# https://docs.djangoproject.com/en/6.1/ref/settings/#databases
|
|
|
|
DATABASES = {
|
|
'default': {
|
|
'ENGINE': 'django.db.backends.sqlite3',
|
|
'NAME': BASE_DIR / 'db.sqlite3',
|
|
}
|
|
}
|
|
|
|
|
|
# Password validation
|
|
# https://docs.djangoproject.com/en/6.1/ref/settings/#auth-password-validators
|
|
|
|
AUTH_PASSWORD_VALIDATORS = [
|
|
{
|
|
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
|
|
},
|
|
{
|
|
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
|
|
},
|
|
{
|
|
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
|
|
},
|
|
{
|
|
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
|
|
},
|
|
]
|
|
|
|
|
|
# Internationalization
|
|
# https://docs.djangoproject.com/en/6.1/topics/i18n/
|
|
|
|
LANGUAGE_CODE = 'en-us'
|
|
|
|
TIME_ZONE = 'UTC'
|
|
|
|
USE_I18N = True
|
|
|
|
USE_TZ = True
|
|
|
|
|
|
# Static files (CSS, JavaScript, Images)
|
|
# https://docs.djangoproject.com/en/6.1/howto/static-files/
|
|
|
|
STATIC_URL = 'static/'
|
|
|
|
|
|
# Email
|
|
# https://docs.djangoproject.com/en/6.1/topics/email/#topic-email-configuration
|
|
|
|
MAILERS = {
|
|
'default': {
|
|
'BACKEND': 'django.core.mail.backends.console.EmailBackend',
|
|
},
|
|
}
|
|
|
|
LLAMA_CPP_URL = "http://brigit.lan:8080/v1/chat/completions"
|
|
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
|
|
-----------------------------------------------------------------------------
|
|
File ./dagda/asgi.py
|
|
"""
|
|
ASGI config for dagda project.
|
|
|
|
It exposes the ASGI callable as a module-level variable named ``application``.
|
|
|
|
For more information on this file, see
|
|
https://docs.djangoproject.com/en/6.1/howto/deployment/asgi/
|
|
"""
|
|
|
|
import os
|
|
|
|
from django.core.asgi import get_asgi_application
|
|
|
|
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dagda.settings')
|
|
|
|
application = get_asgi_application()
|
|
-----------------------------------------------------------------------------
|
|
File ./dagda/urls.py
|
|
"""
|
|
URL configuration for dagda project.
|
|
|
|
The `urlpatterns` list routes URLs to views. For more information please see:
|
|
https://docs.djangoproject.com/en/6.1/topics/http/urls/
|
|
Examples:
|
|
Function views
|
|
1. Add an import: from my_app import views
|
|
2. Add a URL to urlpatterns: path('', views.home, name='home')
|
|
Class-based views
|
|
1. Add an import: from other_app.views import Home
|
|
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
|
|
Including another URLconf
|
|
1. Import the include() function: from django.urls import include, path
|
|
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
|
|
"""
|
|
from django.contrib import admin
|
|
from django.urls import path
|
|
|
|
urlpatterns = [
|
|
path('admin/', admin.site.urls),
|
|
path('', include('core.urls')),
|
|
]
|
|
-----------------------------------------------------------------------------
|
|
File ./dagda/wsgi.py
|
|
"""
|
|
WSGI config for dagda project.
|
|
|
|
It exposes the WSGI callable as a module-level variable named ``application``.
|
|
|
|
For more information on this file, see
|
|
https://docs.djangoproject.com/en/6.1/howto/deployment/wsgi/
|
|
"""
|
|
|
|
import os
|
|
|
|
from django.core.wsgi import get_wsgi_application
|
|
|
|
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dagda.settings')
|
|
|
|
application = get_wsgi_application()
|
|
-----------------------------------------------------------------------------
|
|
File ./dagda/__init__.py
|
|
-----------------------------------------------------------------------------
|
|
File ./meal_tracker/models.py
|
|
# meal_tracker/models.py
|
|
from django.db import models
|
|
|
|
|
|
class Ingredient(models.Model):
|
|
name = models.CharField(max_length=255, db_index=True)
|
|
calories_per_100g = models.FloatField()
|
|
protein_per_100g = models.FloatField()
|
|
fat_per_100g = models.FloatField()
|
|
carbs_per_100g = models.FloatField()
|
|
|
|
class Meta:
|
|
verbose_name_plural = "Ingredients"
|
|
|
|
def __str__(self):
|
|
return self.name
|
|
|
|
|
|
class Food(models.Model):
|
|
name = models.CharField(max_length=255, unique=True)
|
|
estimated_calories = models.IntegerField(null=True, blank=True)
|
|
estimated_protein = models.FloatField(null=True, blank=True)
|
|
estimated_fat = models.FloatField(null=True, blank=True)
|
|
estimated_carbs = models.FloatField(null=True, blank=True)
|
|
|
|
ingredients = models.ManyToManyField('Ingredient', through='FoodComponent')
|
|
|
|
@property
|
|
def total_calories(self):
|
|
if self.estimated_calories:
|
|
return self.estimated_calories
|
|
return sum(c.get_component_calories() for c in self.ingredients.all())
|
|
|
|
def __str__(self):
|
|
return self.name
|
|
|
|
|
|
class FoodComponent(models.Model):
|
|
food = models.ForeignKey(Food, related_name='components', on_delete=models.CASCADE)
|
|
ingredient = models.ForeignKey(Ingredient, related_name='foods_used_in', on_delete=models.CASCADE)
|
|
amount_grams = models.FloatField()
|
|
calories = models.IntegerField(default=0)
|
|
protein = models.FloatField(default=0)
|
|
fat = models.FloatField(default=0)
|
|
carbs = models.FloatField(default=0)
|
|
|
|
def save(self, *args, **kwargs):
|
|
if self.ingredient:
|
|
factor = self.amount_grams / 100.0
|
|
self.calories = int(self.ingredient.calories_per_100g * factor)
|
|
self.protein = self.ingredient.protein_per_100g * factor
|
|
self.fat = self.ingredient.fat_per_100g * factor
|
|
self.carbs = self.ingredient.carbs_per_100g * factor
|
|
super().save(*args, **kwargs)
|
|
|
|
def __str__(self):
|
|
return f"{self.food.name} component"
|
|
|
|
|
|
class Meal(models.Model):
|
|
date = models.DateField()
|
|
created_at = models.DateTimeField(auto_now_add=True)
|
|
|
|
def get_total_macros(self):
|
|
totals = {'calories': 0, 'protein': 0, 'fat': 0, 'carbs': 0}
|
|
for item in self.items.all():
|
|
totals['calories'] += item.get_food_calories()
|
|
totals['protein'] += item.get_food_protein()
|
|
totals['fat'] += item.get_food_fat()
|
|
totals['carbs'] += item.get_food_carbs()
|
|
return totals
|
|
|
|
def __str__(self):
|
|
return f"Meal on {self.date}"
|
|
|
|
|
|
class MealItem(models.Model):
|
|
meal = models.ForeignKey(Meal, related_name='items', on_delete=models.CASCADE)
|
|
food = models.ForeignKey(Food, related_name='meals_contained', on_delete=models.PROTECT)
|
|
quantity_grams = models.FloatField()
|
|
|
|
def get_food_calories(self):
|
|
if self.food.estimated_calories:
|
|
return int(self.food.estimated_calories)
|
|
total = 0
|
|
for comp in self.food.components.all():
|
|
factor = self.quantity_grams / comp.amount_grams
|
|
total += int(comp.calories * factor)
|
|
return total
|
|
|
|
def get_food_protein(self):
|
|
if self.food.estimated_protein is not None:
|
|
return self.food.estimated_protein
|
|
total = 0
|
|
for comp in self.food.components.all():
|
|
factor = self.quantity_grams / comp.amount_grams
|
|
total += comp.protein * factor
|
|
return total
|
|
|
|
def get_food_fat(self):
|
|
if self.food.estimated_fat is not None:
|
|
return self.food.estimated_fat
|
|
total = 0
|
|
for comp in self.food.components.all():
|
|
factor = self.quantity_grams / comp.amount_grams
|
|
total += comp.fat * factor
|
|
return total
|
|
|
|
def get_food_carbs(self):
|
|
if self.food.estimated_carbs is not None:
|
|
return self.food.estimated_carbs
|
|
total = 0
|
|
for comp in self.food.components.all():
|
|
factor = self.quantity_grams / comp.amount_grams
|
|
total += comp.carbs * factor
|
|
return total
|
|
|
|
def __str__(self):
|
|
return f"{self.food.name} ({self.quantity_grams}g)"
|
|
|
|
-----------------------------------------------------------------------------
|
|
File ./meal_tracker/migrations/__init__.py
|
|
-----------------------------------------------------------------------------
|
|
File ./meal_tracker/tasks.py
|
|
# meal_tracker/tasks.py
|
|
from core.base import TaskModule
|
|
from .models import Meal, MealItem, Food
|
|
|
|
|
|
class MealTracker(TaskModule):
|
|
MODULE_NAME = "meal_tracker"
|
|
DESCRIPTION = "Log meals with food items and nutritional tracking"
|
|
|
|
TOOLS = [
|
|
{
|
|
"type": "function",
|
|
"function": {
|
|
"name": "log_meal",
|
|
"description": "Log a meal entry with food, quantity, and macros",
|
|
"parameters": {
|
|
"type": "object",
|
|
"properties": {
|
|
"date": {"type": "string", "format": "date"},
|
|
"items": {
|
|
"type": "array",
|
|
"items": {
|
|
"type": "object",
|
|
"properties": {
|
|
"food_name": {"type": "string"},
|
|
"quantity_grams": {"type": "integer"},
|
|
"estimated_calories": {"type": "integer"},
|
|
"estimated_protein": {"type": "number"},
|
|
"estimated_fat": {"type": "number"},
|
|
"estimated_carbs": {"type": "number"}
|
|
},
|
|
"required": ["food_name", "quantity_grams"]
|
|
}
|
|
}
|
|
},
|
|
"required": ["date", "items"]
|
|
}
|
|
}
|
|
}
|
|
]
|
|
|
|
@classmethod
|
|
def execute_tool(cls, tool_name: str, arguments: dict) -> dict:
|
|
if tool_name == "log_meal":
|
|
meal = Meal.objects.create(date=arguments["date"])
|
|
for item_data in arguments["items"]:
|
|
food = Food.objects.create(
|
|
name=item_data["food_name"],
|
|
estimated_calories=item_data.get("estimated_calories"),
|
|
estimated_protein=item_data.get("estimated_protein"),
|
|
estimated_fat=item_data.get("estimated_fat"),
|
|
estimated_carbs=item_data.get("estimated_carbs")
|
|
)
|
|
MealItem.objects.create(meal=meal, food=food, quantity_grams=item_data["quantity_grams"])
|
|
return {"status": "success",
|
|
"message": f"Logged {len(arguments['items'])} food items for {arguments['date']}"}
|
|
raise ValueError(f"Unknown tool: {tool_name}")
|
|
-----------------------------------------------------------------------------
|
|
File ./meal_tracker/__init__.py
|
|
-----------------------------------------------------------------------------
|
|
File ./templates/core/base.html
|
|
<!DOCTYPE html>
|
|
<html lang="en">
|
|
<head>
|
|
<meta charset="UTF-8">
|
|
<title>Title</title>
|
|
</head>
|
|
<body>
|
|
|
|
</body>
|
|
</html>-----------------------------------------------------------------------------
|
|
File ./templates/core/dashboard.html
|
|
<!-- templates/core/dashboard.html -->
|
|
<!DOCTYPE html>
|
|
<html lang="en">
|
|
<head>
|
|
<meta charset="UTF-8">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
<title>AI Task Agent</title>
|
|
<!-- Bootstrap 5 CSS -->
|
|
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
|
|
<style>
|
|
body { background-color: #f4f6f9; }
|
|
.card { border-radius: 12px; box-shadow: 0 4px 6px rgba(0,0,0,0.05); }
|
|
.form-control:focus { border-color: #0d6efd; box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, .25); }
|
|
</style>
|
|
</head>
|
|
<body>
|
|
<div class="container py-5">
|
|
<!-- Header -->
|
|
<div class="row mb-4 text-center">
|
|
<div class="col">
|
|
<h1 class="display-6 fw-bold text-primary">Local AI Agent</h1>
|
|
<p class="text-muted">Natural language interface for your tasks.</p>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Input Section -->
|
|
<div class="row justify-content-center mb-5">
|
|
<div class="col-md-8">
|
|
<div class="card p-4 border-0">
|
|
<form method="post" action="{% url 'agent_input' %}">
|
|
{% csrf_token %}
|
|
<label for="input" class="form-label fw-bold">Task Input</label>
|
|
<textarea name="input" id="input" class="form-control mb-3" rows="4"
|
|
placeholder="e.g., 'Log a workout: Leg Day with Squats 5x5 at 100kg' or 'Add a meeting tomorrow at 2pm'"
|
|
required></textarea>
|
|
<button type="submit" class="btn btn-primary w-100 py-2">Process Request</button>
|
|
</form>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Messages / Results -->
|
|
{% if messages %}
|
|
<div class="row justify-content-center">
|
|
<div class="col-md-8">
|
|
{% for message in messages %}
|
|
<div class="alert alert-{{ message.tags }} alert-dismissible fade show shadow-sm" role="alert">
|
|
{{ message }}
|
|
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
|
|
</div>
|
|
{% endfor %}
|
|
</div>
|
|
</div>
|
|
{% endif %}
|
|
|
|
<!-- Module Status/Links (Placeholder) -->
|
|
<div class="row justify-content-center mt-5">
|
|
<div class="col-md-8 text-center">
|
|
<div class="d-flex justify-content-around flex-wrap gap-2">
|
|
<span class="badge bg-success p-2"><i class="bi bi-cake"></i> Meal Tracker</span>
|
|
<span class="badge bg-primary p-2"><i class="bi bi-dumbbell"></i> Exercise Tracker</span>
|
|
<span class="badge bg-info p-2"><i class="bi bi-calendar-event"></i> Calendar</span>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
|
|
<!-- Bootstrap JS -->
|
|
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
|
|
</body>
|
|
</html>
|
|
-----------------------------------------------------------------------------
|
|
File ./requirements.txt
|
|
Django==5.1.4
|
|
requests>=2.31.0
|
|
psycopg2-binary>=2.9.9 # Use only if using PostgreSQL-----------------------------------------------------------------------------
|
|
File ./core/registry.py
|
|
# core/registry.py
|
|
import importlib
|
|
from django.apps import apps
|
|
from core.base import TaskModule
|
|
|
|
|
|
class TaskRegistry:
|
|
MODULES = {}
|
|
|
|
@classmethod
|
|
def discover_modules(cls):
|
|
for app_config in apps.get_app_configs():
|
|
try:
|
|
module_path = f"{app_config.name}.tasks"
|
|
importlib.import_module(module_path)
|
|
|
|
for obj_name in dir(apps.get_app_config(app_config.name).module):
|
|
obj = getattr(apps.get_app_config(app_config.name).module, obj_name)
|
|
if (isinstance(obj, type) and
|
|
issubclass(obj, TaskModule) and
|
|
obj.__name__ != 'TaskModule'):
|
|
cls.MODULES[obj.MODULE_NAME] = obj
|
|
except Exception:
|
|
continue
|
|
|
|
@classmethod
|
|
def get_all_tools(cls) -> list:
|
|
tools = []
|
|
for module in cls.MODULES.values():
|
|
tools.extend(module.get_tools())
|
|
return tools
|
|
|
|
@classmethod
|
|
def execute(cls, tool_name: str, arguments: dict) -> dict:
|
|
for name, module in cls.MODULES.items():
|
|
available_tools = [t["function"]["name"] for t in module.get_tools()]
|
|
if tool_name in available_tools:
|
|
return module.execute_tool(tool_name, arguments)
|
|
return {"status": "error", "message": f"Unknown tool: {tool_name}"}
|
|
|
|
@classmethod
|
|
def build_system_prompt(cls) -> str:
|
|
fragments = [
|
|
"You are an AI assistant with access to the following modules:",
|
|
*(f"- **{name.upper()}**: {mod.DESCRIPTION}" for name, mod in cls.MODULES.items()),
|
|
"\nOnly call tools that exist in your available tool list."
|
|
]
|
|
return "\n".join(fragments)
|
|
|
|
|
|
# Auto-discover on first import
|
|
TaskRegistry.discover_modules()
|
|
-----------------------------------------------------------------------------
|
|
File ./core/base.py
|
|
# core/base.py
|
|
from abc import ABC, abstractmethod
|
|
from typing import List, Dict, Any
|
|
|
|
|
|
class TaskModule(ABC):
|
|
MODULE_NAME = ""
|
|
DESCRIPTION = ""
|
|
|
|
TOOLS = [] # Each module defines its tools
|
|
|
|
@classmethod
|
|
def get_tools(cls) -> List[Dict[str, Any]]:
|
|
return cls.TOOLS
|
|
|
|
@classmethod
|
|
def execute_tool(cls, tool_name: str, arguments: dict) -> Dict[str, Any]:
|
|
raise NotImplementedError("Modules must implement execute_tool()")
|
|
|
|
@staticmethod
|
|
def get_system_prompt_fragment() -> str:
|
|
return ""
|
|
-----------------------------------------------------------------------------
|
|
File ./core/urls.py
|
|
# core/urls.py
|
|
from django.urls import path
|
|
from . import views
|
|
|
|
urlpatterns = [
|
|
path("", views.dashboard, name="dashboard"),
|
|
path("log/", views.agent_input, name="agent_input"),
|
|
]
|
|
-----------------------------------------------------------------------------
|
|
File ./core/views.py
|
|
# core/views.py
|
|
from django.shortcuts import render, redirect
|
|
from django.contrib import messages
|
|
from core.llm_client import process_user_input
|
|
|
|
|
|
def dashboard(request):
|
|
return render(request, "core/dashboard.html")
|
|
|
|
|
|
def agent_input(request):
|
|
if request.method == "POST":
|
|
user_text = request.POST.get("input", "").strip()
|
|
if not user_text:
|
|
messages.warning(request, "Please enter a command.")
|
|
return redirect("dashboard")
|
|
|
|
result = process_user_input(user_text)
|
|
|
|
if result.get("error"):
|
|
messages.error(request, result["error"])
|
|
elif result.get("status") == "success":
|
|
messages.success(request, result.get("message", "Task completed"))
|
|
else:
|
|
messages.info(request, result.get("message", "No action taken."))
|
|
|
|
return redirect("dashboard")
|
|
-----------------------------------------------------------------------------
|
|
File ./core/llm_client.py
|
|
# core/llm_client.py
|
|
import requests
|
|
import json
|
|
from django.conf import settings
|
|
from core.registry import TaskRegistry
|
|
|
|
SYSTEM_PROMPT = f"""{TaskRegistry.build_system_prompt()}
|
|
Rules:
|
|
- ALWAYS use tools when appropriate. Never respond with text unless explicitly asked for a summary.
|
|
- If unsure which module handles a request, choose the most relevant one.
|
|
- Include a "final_response" field in every tool_call result for user display."""
|
|
|
|
def process_user_input(user_text: str):
|
|
tools = TaskRegistry.get_all_tools()
|
|
|
|
payload = {
|
|
"model": "llama3.1",
|
|
"messages": [
|
|
{"role": "system", "content": SYSTEM_PROMPT},
|
|
{"role": "user", "content": user_text}
|
|
],
|
|
"tools": tools,
|
|
"tool_choice": "auto",
|
|
"temperature": 0.2
|
|
}
|
|
|
|
try:
|
|
resp = requests.post(settings.LLAMA_CPP_URL, json=payload)
|
|
data = resp.json()
|
|
|
|
tool_calls = data["choices"][0]["message"].get("tool_calls", [])
|
|
if not tool_calls:
|
|
return {"status": "text", "message": data["choices"][0]["message"]["content"]}
|
|
|
|
result = TaskRegistry.execute(tool_calls[0]["function"]["name"],
|
|
json.loads(tool_calls[0]["function"]["arguments"]))
|
|
return result
|
|
|
|
except Exception as e:
|
|
return {"error": f"LLM processing failed: {str(e)}"}
|
|
-----------------------------------------------------------------------------
|
|
File ./core/__init__.py
|
|
-----------------------------------------------------------------------------
|
|
File ./manage.py
|
|
#!/usr/bin/env python
|
|
"""Django's command-line utility for administrative tasks."""
|
|
import os
|
|
import sys
|
|
|
|
|
|
def main():
|
|
"""Run administrative tasks."""
|
|
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dagda.settings')
|
|
try:
|
|
from django.core.management import execute_from_command_line
|
|
except ImportError as exc:
|
|
raise ImportError(
|
|
"Couldn't import Django. Are you sure it's installed and "
|
|
"available on your PYTHONPATH environment variable? Did you "
|
|
"forget to activate a virtual environment?"
|
|
) from exc
|
|
execute_from_command_line(sys.argv)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|
|
-----------------------------------------------------------------------------
|