Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Spotlight api #110

Open
wants to merge 25 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 11 commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
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 django.contrib.admin module is imported but not used in this file.

Apply this diff to 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.get("AWS_REGION")
AWS_ACCESS_KEY_ID = os.environ.get("AWS_ACCESS_KEY_ID")
AWS_SECRET_ACCESS_KEY = os.environ.get("AWS_SECRET_ACCESS_KEY")

OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")
KNOWLEDGE_BASE_ID = os.environ.get("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=1000,
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))
Comment on lines +50 to +51
Copy link

Choose a reason for hiding this comment

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

Distinguish exceptions raised within the except clause.

The static analysis tool suggests using raise ... from err or raise ... from None to distinguish exceptions raised within the except clause from errors in exception handling.

Apply this diff to fix the issue:

-    except (openai.OpenAIError, json.JSONDecodeError) as e:
-        raise Exception(message=str(e))
+    except (openai.OpenAIError, json.JSONDecodeError) as e:
+        raise Exception(message=str(e)) from e
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
except (openai.OpenAIError, json.JSONDecodeError) as e:
raise Exception(message=str(e))
except (openai.OpenAIError, json.JSONDecodeError) as e:
raise Exception(message=str(e)) from e
Tools
Ruff

51-51: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)




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.

Raise an exception instead of printing the error message.

The function prints the error message instead of raising an exception. This can be improved by raising an exception with the error message.

Apply this diff to fix the issue:

-    except json.JSONDecodeError as e:
-        print(e)
+    except json.JSONDecodeError as e:
+        raise Exception(message=str(e)) from e
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
except json.JSONDecodeError as e:
print(e)
except json.JSONDecodeError as e:
raise Exception(message=str(e)) 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
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")
Copy link

Choose a reason for hiding this comment

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

Use a foreign key for the workspace_id field if it references a Workspace model.

The workspace_id field is an integer field, which implies it's a reference to a Workspace model (not shown in this file).

Consider using a foreign key field instead of a raw integer field if indeed this is meant to be a reference to another model. This would enforce referential integrity at the database level.

-workspace_id = models.IntegerField(help_text="Workspace id of the organization")
+workspace = models.ForeignKey(
+    'Workspace',  
+    on_delete=models.CASCADE,
+    help_text="Reference to the associated Workspace"
+)

Note: Replace 'Workspace' with the actual Workspace model class if it's defined in the same file, or with the full app label and model name (e.g., 'myapp.Workspace') if it's in a different app.

Committable suggestion was skipped due to low confidence.

_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