init
This commit is contained in:
commit
66729f7d08
24 files changed
+907
No files matched your search
Whitespace-only changes.
@@ -0,0 +1,22 @@
|
||||
# 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 ""
|
||||
@@ -0,0 +1,40 @@
|
||||
# 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, timeout=15)
|
||||
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)}"}
|
||||
@@ -0,0 +1,52 @@
|
||||
# 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()
|
||||
@@ -0,0 +1,8 @@
|
||||
# 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"),
|
||||
]
|
||||
@@ -0,0 +1,27 @@
|
||||
# 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")
|
||||
Reference in new issue
Block a user