Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file added apps/spotlight/__init__.py
Empty file.
3 changes: 3 additions & 0 deletions apps/spotlight/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.contrib import admin
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove the unused import.

The import statement from django.contrib import admin is unused in this file.

Remove the unused import:

-from django.contrib import admin
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
from django.contrib import admin
Tools
Ruff

1-1: django.contrib.admin imported but unused

Remove unused import: django.contrib.admin

(F401)


# Register your models here.
5 changes: 5 additions & 0 deletions apps/spotlight/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from django.apps import AppConfig


class SpotlightConfig(AppConfig):
name = 'spotlight'
96 changes: 96 additions & 0 deletions apps/spotlight/llm.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import os
import boto3
import openai
import json
from typing import Dict


AWS_REGION = os.environ["AWS_REGION"]
AWS_ACCESS_KEY_ID = os.environ["AWS_ACCESS_KEY_ID"]
AWS_SECRET_ACCESS_KEY = os.environ["AWS_SECRET_ACCESS_KEY"]

OPENAI_API_KEY = os.environ["OPENAI_API_KEY"]
KNOWLEDGE_BASE_ID = os.environ["KNOWLEDGE_BASE_ID"]


bedrock_session = boto3.Session(
region_name=AWS_REGION,
aws_access_key_id=AWS_ACCESS_KEY_ID,
aws_secret_access_key=AWS_SECRET_ACCESS_KEY
)

openai_client = openai.OpenAI(
api_key=OPENAI_API_KEY,
max_retries=5,
timeout=10
)


def get_openai_response(*, system_prompt: str) -> dict:
try:
chat_completion_resp = openai_client.chat.completions.create(
model="gpt-4o",
response_format={
"type": "json_object"
},
messages=[
{"role": "system", "content": system_prompt}
],
temperature=0,
max_tokens=256,
top_p=0,
frequency_penalty=0,
presence_penalty=0
)

return json.loads(
chat_completion_resp.choices[0].message.content
)

except (openai.OpenAIError, json.JSONDecodeError) as e:
raise Exception(message=str(e))



def get_support_response_from_bedrock(*, prompt_template: str, input_message: str) -> Dict:
try:
bedrock_agent_runtime_client = bedrock_session.client(
'bedrock-agent-runtime'
)

response = bedrock_agent_runtime_client.retrieve_and_generate(
input={
'text': input_message
},
retrieveAndGenerateConfiguration={
'type': 'KNOWLEDGE_BASE',
'knowledgeBaseConfiguration': {
'knowledgeBaseId': KNOWLEDGE_BASE_ID,
'modelArn': 'arn:aws:bedrock:ap-south-1::foundation-model/anthropic.claude-3-sonnet-20240229-v1:0',
'generationConfiguration': {
'inferenceConfig': {
'textInferenceConfig': {
'maxTokens': 2048,
'stopSequences': [],
'temperature': 0,
'topP': 1
}
},
'promptTemplate': {
'textPromptTemplate': prompt_template
}
},
'retrievalConfiguration': {
'vectorSearchConfiguration': {
'numberOfResults': 5,
'overrideSearchType': 'HYBRID',
}
}
}
}
)

return response

except json.JSONDecodeError as e:
print(e)
Comment on lines +95 to +96
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Improve the error handling.

Printing the exception is not an ideal way to handle errors. Consider the following improvements:

  • Use a logging framework to log the error for better visibility and debugging.
  • Raise the exception or return an appropriate error response to propagate the error and handle it at a higher level.

Here's an example of how you can improve the error handling:

import logging

logger = logging.getLogger(__name__)

try:
    # ...
except json.JSONDecodeError as e:
    logger.error(f"Error decoding JSON response from AWS Bedrock: {str(e)}")
    raise Exception("Failed to decode JSON response from AWS Bedrock") from e

32 changes: 32 additions & 0 deletions apps/spotlight/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Generated by Django 3.1.14 on 2024-09-10 05:28

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

initial = True

dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]

operations = [
migrations.CreateModel(
name='Query',
fields=[
('id', models.AutoField(primary_key=True, serialize=False)),
('query', models.TextField()),
('workspace_id', models.IntegerField(help_text='Workspace id of the organization')),
('_llm_response', models.JSONField(default={})),
('created_at', models.DateTimeField(auto_now_add=True, help_text='Created at datetime')),
('updated_at', models.DateTimeField(auto_now=True, help_text='Updated at datetime')),
('user', models.ForeignKey(help_text='Reference to users table', on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
options={
'db_table': 'queries',
},
),
]
Empty file.
23 changes: 23 additions & 0 deletions apps/spotlight/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
from django.db import models
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove the unused import.

The import statement from django.db import models is unused in this file.

Remove the unused import:

-from django.db import models
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
from django.db import models
Tools
Ruff

1-1: django.db.models imported but unused

Remove unused import: django.db.models

(F401)

from django.contrib.auth import get_user_model


User = get_user_model()


# Create your models here.
class Query(models.Model):
id = models.AutoField(primary_key=True)
query = models.TextField()
workspace_id = models.IntegerField(help_text="Workspace id of the organization")
_llm_response = models.JSONField(default={})
user = models.ForeignKey(User, on_delete=models.CASCADE, help_text='Reference to users table')
created_at = models.DateTimeField(
auto_now_add=True, help_text="Created at datetime"
)
updated_at = models.DateTimeField(
auto_now=True, help_text="Updated at datetime"
)

class Meta:
db_table = 'queries'
Empty file.
Loading
Loading