diff --git a/ollamate/asgi.py b/ollamate/asgi.py index 0dcb726..1f3288b 100644 --- a/ollamate/asgi.py +++ b/ollamate/asgi.py @@ -11,6 +11,6 @@ from django.core.asgi import get_asgi_application -os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ollamate.settings') +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ollamate.settings") application = get_asgi_application() diff --git a/ollamate/settings.py b/ollamate/settings.py index ea65907..4587455 100644 --- a/ollamate/settings.py +++ b/ollamate/settings.py @@ -22,7 +22,7 @@ BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Read the .env file -env_file = os.path.join(BASE_DIR, '.env') +env_file = os.path.join(BASE_DIR, ".env") if os.path.isfile(env_file): print(f"Loading environment variables from {env_file}") environ.Env.read_env(env_file) @@ -40,7 +40,7 @@ # See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! -SECRET_KEY = 'django-insecure-(y%c-1p0lnlrxg!$3w)ptcyp=wzer(biav_-%_fehgn1oatx8p' +SECRET_KEY = "django-insecure-(y%c-1p0lnlrxg!$3w)ptcyp=wzer(biav_-%_fehgn1oatx8p" # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True @@ -52,45 +52,45 @@ # Application definition INSTALLED_APPS = [ - 'django.contrib.admin', - 'django.contrib.auth', - 'django.contrib.contenttypes', - 'django.contrib.sessions', - 'django.contrib.messages', - 'django.contrib.staticfiles', - 'streamingapp', - 'azure_auth' + "django.contrib.admin", + "django.contrib.auth", + "django.contrib.contenttypes", + "django.contrib.sessions", + "django.contrib.messages", + "django.contrib.staticfiles", + "streamingapp", + "azure_auth", ] 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', + "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 = 'ollamate.urls' +ROOT_URLCONF = "ollamate.urls" TEMPLATES = [ { - 'BACKEND': 'django.template.backends.django.DjangoTemplates', - 'DIRS': [], - 'APP_DIRS': True, - 'OPTIONS': { - 'context_processors': [ - 'django.template.context_processors.debug', - 'django.template.context_processors.request', - 'django.contrib.auth.context_processors.auth', - 'django.contrib.messages.context_processors.messages', + "BACKEND": "django.template.backends.django.DjangoTemplates", + "DIRS": [], + "APP_DIRS": True, + "OPTIONS": { + "context_processors": [ + "django.template.context_processors.debug", + "django.template.context_processors.request", + "django.contrib.auth.context_processors.auth", + "django.contrib.messages.context_processors.messages", ], }, }, ] -WSGI_APPLICATION = 'ollamate.wsgi.application' +WSGI_APPLICATION = "ollamate.wsgi.application" # Database @@ -98,7 +98,9 @@ DB_HOST = os.environ.get("DB_HOST", "127.0.0.1") ENABLE_DB_SSL = ( - str(os.environ.get("ENABLE_DB_SSL", DB_HOST not in ["127.0.0.1", "localhost"])).lower() + str( + os.environ.get("ENABLE_DB_SSL", DB_HOST not in ["127.0.0.1", "localhost"]) + ).lower() == "true" ) DATABASES: dict = { @@ -121,16 +123,16 @@ AUTH_PASSWORD_VALIDATORS = [ { - 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', + "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator", }, { - 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', + "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator", }, { - 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', + "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator", }, { - 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', + "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator", }, ] @@ -138,9 +140,9 @@ # Internationalization # https://docs.djangoproject.com/en/5.0/topics/i18n/ -LANGUAGE_CODE = 'en-us' +LANGUAGE_CODE = "en-us" -TIME_ZONE = 'UTC' +TIME_ZONE = "UTC" USE_I18N = True @@ -150,12 +152,12 @@ # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/5.0/howto/static-files/ -STATIC_URL = 'static/' +STATIC_URL = "static/" # Default primary key field type # https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field -DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' +DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" # Azure authentication settings @@ -164,21 +166,22 @@ "CLIENT_SECRET": env("CLIENT_SECRET"), "REDIRECT_URI": env("REDIRECT_URI"), "SCOPES": ["User.Read"], - "AUTHORITY": "https://login.microsoftonline.com/{}".format(env("AZURE_TENANT_ID")), # Or https://login.microsoftonline.com/common if multi-tenant -# # "LOGOUT_URI": "https:///logout", # Optional -# # "PUBLIC_URLS": ["",], # Optional, public views accessible by non-authenticated users -# # "PUBLIC_PATHS": ['/go/',], # Optional, public paths accessible by non-authenticated users -# # "ROLES": { -# # "95170e67-2bbf-4e3e-a4d7-e7e5829fe7a7": "GroupName1", -# # "3dc6539e-0589-4663-b782-fef100d839aa": "GroupName2" -# # }, # Optional, will add user to django group if user is in EntraID group - "USERNAME_ATTRIBUTE": "mail", # The AAD attribute or ID token claim you want to use as the value for the user model `USERNAME_FIELD` -# # "EXTRA_FIELDS": [], # Optional, extra AAD user profile attributes you want to make available in the user mapping function -# "USER_MAPPING_FN": "azure_auth.tests.misc.user_mapping_fn", # Optional, path to the function used to map the AAD to Django attributes + "AUTHORITY": "https://login.microsoftonline.com/{}".format( + env("AZURE_TENANT_ID") + ), # Or https://login.microsoftonline.com/common if multi-tenant + # # "LOGOUT_URI": "https:///logout", # Optional + # # "PUBLIC_URLS": ["",], # Optional, public views accessible by non-authenticated users + # # "PUBLIC_PATHS": ['/go/',], # Optional, public paths accessible by non-authenticated users + # # "ROLES": { + # # "95170e67-2bbf-4e3e-a4d7-e7e5829fe7a7": "GroupName1", + # # "3dc6539e-0589-4663-b782-fef100d839aa": "GroupName2" + # # }, # Optional, will add user to django group if user is in EntraID group + "USERNAME_ATTRIBUTE": "mail", # The AAD attribute or ID token claim you want to use as the value for the user model `USERNAME_FIELD` + # # "EXTRA_FIELDS": [], # Optional, extra AAD user profile attributes you want to make available in the user mapping function + # "USER_MAPPING_FN": "azure_auth.tests.misc.user_mapping_fn", # Optional, path to the function used to map the AAD to Django attributes } LOGIN_URL = "/azure_auth/login" LOGIN_REDIRECT_URL = "/" -LOGOUT_REDIRECT_URL = '/' +LOGOUT_REDIRECT_URL = "/" AUTHENTICATION_BACKENDS = ("azure_auth.backends.AzureBackend",) - diff --git a/ollamate/urls.py b/ollamate/urls.py index b37c2b0..ed41375 100644 --- a/ollamate/urls.py +++ b/ollamate/urls.py @@ -19,8 +19,11 @@ from streamingapp.views import redirect_to_ollama urlpatterns = [ - path('admin/', admin.site.urls), - path("azure_auth/", include("azure_auth.urls"),), - path('stream/', include('streamingapp.urls')), - path('', redirect_to_ollama) + path("admin/", admin.site.urls), + path( + "azure_auth/", + include("azure_auth.urls"), + ), + path("stream/", include("streamingapp.urls")), + path("", redirect_to_ollama), ] diff --git a/ollamate/wsgi.py b/ollamate/wsgi.py index a07ca1e..ba2312a 100644 --- a/ollamate/wsgi.py +++ b/ollamate/wsgi.py @@ -11,6 +11,6 @@ from django.core.wsgi import get_wsgi_application -os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ollamate.settings') +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ollamate.settings") application = get_wsgi_application() diff --git a/streamingapp/apps.py b/streamingapp/apps.py index 02796ae..31356e5 100644 --- a/streamingapp/apps.py +++ b/streamingapp/apps.py @@ -2,5 +2,5 @@ class StreamingappConfig(AppConfig): - default_auto_field = 'django.db.models.BigAutoField' - name = 'streamingapp' + default_auto_field = "django.db.models.BigAutoField" + name = "streamingapp" diff --git a/streamingapp/urls.py b/streamingapp/urls.py index 1d03544..4175580 100644 --- a/streamingapp/urls.py +++ b/streamingapp/urls.py @@ -2,5 +2,5 @@ from . import views urlpatterns = [ - path('call-ollama/', views.call_ollama, name='call_ollama'), + path("call-ollama/", views.call_ollama, name="call_ollama"), ] diff --git a/streamingapp/views.py b/streamingapp/views.py index 9d3a2be..662a79a 100644 --- a/streamingapp/views.py +++ b/streamingapp/views.py @@ -8,26 +8,23 @@ # Configure logging logging.basicConfig(level=logging.DEBUG) + @azure_auth_required def call_ollama(request): - if request.method == 'POST': - user_input = request.POST.get('userInput', '') + if request.method == "POST": + user_input = request.POST.get("userInput", "") try: conversation_history = json.loads(user_input) except json.JSONDecodeError as e: logging.error("JSONDecodeError: %s", e) return JsonResponse({"error": "Invalid input format"}, status=400) - url = 'http://localhost:11434/api/chat' - headers = {'Content-Type': 'application/json'} - data = { - "model": "llama3", - "messages": conversation_history, - "stream": False - } - + url = "http://localhost:11434/api/chat" + headers = {"Content-Type": "application/json"} + data = {"model": "llama3", "messages": conversation_history, "stream": False} + logging.debug("Sending data to Ollama API: %s", json.dumps(data, indent=2)) - + try: response = requests.post(url, json=data, headers=headers) response.raise_for_status() @@ -37,14 +34,17 @@ def call_ollama(request): ollama_response = response_data.get("message", {}).get("content", "") if not ollama_response: logging.error("Empty response from Ollama API") - return JsonResponse({"error": "Empty response from Ollama API"}, status=500) - + return JsonResponse( + {"error": "Empty response from Ollama API"}, status=500 + ) + return JsonResponse({"response": ollama_response}) except requests.RequestException as e: logging.error("RequestException: %s", e) return JsonResponse({"error": str(e)}, status=500) else: - return render(request, 'streamingapp/input_form.html') - + return render(request, "streamingapp/input_form.html") + + def redirect_to_ollama(request): - return redirect('/stream/call-ollama') \ No newline at end of file + return redirect("/stream/call-ollama")