Skip to content

Commit

Permalink
Improvements to Discord integration
Browse files Browse the repository at this point in the history
  • Loading branch information
dmugtasimov committed Aug 6, 2024
1 parent 9653668 commit a292cd4
Show file tree
Hide file tree
Showing 42 changed files with 1,467 additions and 895 deletions.
16 changes: 16 additions & 0 deletions DEPLOY.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,21 @@
# Deploy production

## Discord Bot creation

1. Open "[Applications](https://discord.com/developers/applications)" at Discord Developer Portal
2. Click "New Application" button
3. Type application name and "Create" button
4. Click "Bot" on the left panel of the created application
5. Click "Reset Token" button and then confirm by clicking "Yes, do it!" button
6. Re-enter your Discord password and click "Submit" button
7. Copy and save the generated bot token
8. Check "MESSAGE CONTENT INTENT" and click "Save Changes" button
9. Click "OAuth2" on the left panel
10. In "OAuth2 URL Generator" -> "SCOPES" section check "bot"
11. In "OAuth2 URL Generator" -> "BOT PERMISSIONS" section check "Send Messages"
12. Set "OAuth2 URL Generator" -> "INTEGRATION TYPE" = Guild Install
13. Copy "OAuth2 URL Generator" -> "GENERATED URL", open it in your browser and authorize the bot to a server

## Initial deployment

Initial deployment is done once. [Update](#Update) section is executed for redeployment
Expand Down
1 change: 1 addition & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ ENV THENEWBOSTON_SETTING_IN_DOCKER true

EXPOSE 8000

# TODO(dmu) HIGH: Use the same pip version as suggested in README.md
RUN set -xe \
&& apt-get update \
&& apt-get install -y --no-install-recommends build-essential \
Expand Down
4 changes: 4 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,10 @@ run-daphne:
poetry run python -m thenewboston.manage collectstatic --no-input
poetry run daphne thenewboston.project.asgi:application -p 8000 -b 127.0.0.1

.PHONY: run-discord-bot
run-discord-bot:
poetry run python -m thenewboston.discord.bot

.PHONY: shell
shell:
poetry run python -m thenewboston.manage shell
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
1. Install Poetry

```bash
export PIP_REQUIRED_VERSION=24.0
export PIP_REQUIRED_VERSION=24.2
pip install pip==${PIP_REQUIRED_VERSION} && \
pip install virtualenvwrapper && \
pip install poetry==1.8.3 && \
Expand Down
21 changes: 15 additions & 6 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,14 @@ pillow = "^9.5.0"
psycopg2 = "^2.9.6"
pydantic = "^1.10.9"
pynacl = "^1.5.0"
# TODO(dmu) HIGH: Upgrade to Python 3.12
python = "^3.10"
pyyaml = "^6.0"
requests = "^2.31.0"
whitenoise = "^6.5.0"
celery = {extras = ["redis"], version = "^5.3.6"}
channels-redis = "^4.2.0"
openai = "^1.8.0"
openai = "^1.39.0"
langchain = "^0.1.1"
pygithub = "^2.3.0"
jinja2 = "^3.1.3"
Expand Down
18 changes: 9 additions & 9 deletions thenewboston/art/tests/test_openai_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,27 +11,27 @@ def test_create_openai_images(api_client_bucky, sample_core, sample_wallet):
with (
override_settings(OPENAI_IMAGE_GENERATION_DEFAULT_SIZE='256x256'),
yield_cassette('create_openai_image.yaml') as cassette,
assert_played(cassette, count=2),
assert_played(cassette),
):
response = api_client_bucky.post('/api/openai_images', payload)

assert response.status_code == 200
assert response.json() == {
'created':
1712242615,
1722953410,
'data': [{
'b64_json':
None,
'revised_prompt':
None,
'url': (
'https://oaidalleapiprodscus.blob.core.windows.net/'
'private/org-eQnfyttwsLTbvwJtDWRGilzo/user-vGa8V5qOL8XFkzK6S4wA3Geo/'
'img-gPfLBQY2J1mBxhd81nLYuOHz.png?st=2024-04-04T13%3A56%3A55Z&se=2024-04-04T15%3A56%3A55Z&sp=r&'
'sv=2021-08-06&sr=b&rscd=inline&rsct=image/png&'
'skoid=6aaadede-4fb3-4698-a8f6-684d7786b067&sktid=a48cca56-e6da-484e-a814-9c849652bcb3&'
'skt=2024-04-03T20%3A15%3A27Z&ske=2024-04-04T20%3A15%3A27Z&sks=b&skv=2021-08-06&'
'sig=KtLaFr26odFV%2BeJlINYQN0t5utSfCpRYhpToZqhcWW0%3D'
'https://oaidalleapiprodscus.blob.core.windows.net/private/'
'org-eQnfyttwsLTbvwJtDWRGilzo/user-vGa8V5qOL8XFkzK6S4wA3Geo/'
'img-bY1bAO8t1NOd3M9w3HE6TSW6.png?st=2024-08-06T13%3A10%3A10Z&'
'se=2024-08-06T15%3A10%3A10Z&sp=r&sv=2023-11-03&sr=b&rscd=inline&'
'rsct=image/png&skoid=d505667d-d6c1-4a0a-bac7-5c84a87759f8&'
'sktid=a48cca56-e6da-484e-a814-9c849652bcb3&skt=2024-08-06T01%3A30%3A12Z&'
'ske=2024-08-07T01%3A30%3A12Z&sks=b&skv=2023-11-03&sig=9BK9xQF5a6CWqDV6QVNy4Ktmh19jrYOOlWiZys6qVrM%3D'
)
}]
}
15 changes: 2 additions & 13 deletions thenewboston/art/views/openai_image.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
from django.conf import settings
from promptlayer import PromptLayer
from rest_framework import status, viewsets
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response

from thenewboston.general.clients.openai import OpenAIClient
from thenewboston.general.constants import OPENAI_IMAGE_CREATION_FEE
from thenewboston.general.enums import MessageType
from thenewboston.wallets.consumers.wallet import WalletConsumer
Expand All @@ -12,10 +11,6 @@

from ..serializers.openai_image import OpenAIImageSerializer

promptlayer_client = PromptLayer(api_key=settings.PROMPTLAYER_API_KEY)
OpenAI = promptlayer_client.openai.OpenAI
client = OpenAI()


class OpenAIImageViewSet(viewsets.ViewSet):
permission_classes = [IsAuthenticated]
Expand All @@ -28,13 +23,7 @@ def create(self, request):
description = serializer.validated_data['description']
quantity = serializer.validated_data['quantity']

response = client.images.generate(
model=settings.OPENAI_IMAGE_GENERATION_MODEL,
n=quantity,
prompt=description,
quality=settings.OPENAI_IMAGE_GENERATION_DEFAULT_QUALITY,
size=settings.OPENAI_IMAGE_GENERATION_DEFAULT_SIZE,
)
response = OpenAIClient.get_instance().generate_image(prompt=description, quantity=quantity)

self.charge_image_creation_fee(request.user, quantity)

Expand Down
6 changes: 1 addition & 5 deletions thenewboston/contributions/business_logic/process.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,8 +111,4 @@ def reward_manual_contributions(contribution_id=None):
try:
reward_contribution(contribution)
except Exception:
logger.warning(
'Error while rewarding contribution: %s',
contribution,
exc_info=True,
)
logger.warning('Error while rewarding contribution: %s', contribution, exc_info=True)
22 changes: 6 additions & 16 deletions thenewboston/contributions/models/contribution.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,13 @@
import json
from datetime import timedelta

from django.conf import settings
from django.db import models
from django.utils import timezone
from promptlayer import PromptLayer

from thenewboston.general.clients.openai import OpenAIClient
from thenewboston.general.models import CreatedModified
from thenewboston.general.utils.transfers import change_wallet_balance

promptlayer_client = PromptLayer(api_key=settings.PROMPTLAYER_API_KEY)


class ContributionType(models.IntegerChoices):
PULL_REQUEST = 1, 'Pull request'
Expand Down Expand Up @@ -72,21 +69,14 @@ def assess(self, save=True):
assessment_points = pull.assessment_points
assessment_explanation = pull.assessment_explanation
case ContributionType.MANUAL.value:
response = promptlayer_client.run(
prompt_name=settings.GITHUB_MANUAL_CONTRIBUTION_ASSESSMENT_TEMPLATE_NAME,
result = OpenAIClient.get_instance().get_chat_completion(
settings.GITHUB_MANUAL_CONTRIBUTION_ASSESSMENT_PROMPT_NAME,
input_variables={'description': self.description},
prompt_release_label=settings.PROMPT_TEMPLATE_LABEL,
metadata={
'environment': settings.ENV_NAME,
'user_id': str(self.user.id),
'username': self.user.username
},
tracked_user=self.user,
tags=['manual_contribution_assessment'],
)
result = response['raw_response'].choices[0].message.content
result_json = json.loads(result)
assessment_points = result_json['assessment']
assessment_explanation = result_json['explanation']
assessment_points = result['assessment']
assessment_explanation = result['explanation']
case _:
raise NotImplementedError('Unsupported contribution type')

Expand Down
30 changes: 14 additions & 16 deletions thenewboston/contributions/tests/test_manual_contribution.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,16 +18,14 @@
from thenewboston.wallets.models import Wallet

ASSESSMENT_EXPLANATION = (
"As an AI developed by OpenAI, I'm not equipped with the capacity to directly view, access, or "
'assess visual designs such as those created in Figma. My functionality is centered around processing '
'text-based input and generating text-based output. Therefore, I cannot directly evaluate the quality, '
'creativity, or impact of your Figma designs. Assessment of visual design work requires subjective '
'analysis and consideration of aesthetic principles, design innovation, usability, and how effectively '
'the design communicates its intended message or function. These nuances are best evaluated by humans or '
'specialized software designed for visual design critique and analysis. However, creating new designs in '
'Figma can be a valuable contribution to projects requiring visual communication, user interface design, '
'or user experience enhancements, suggesting a non-zero intrinsic value in contexts where such '
'contributions are applicable.'
'The creation of 3 new designs in Figma can be a valuable contribution, particularly if these designs are '
"intended to improve the user interface and user experience of our project's software components. "
'Given that visual and interaction design can significantly impact the usability and appeal of our tools '
"and platforms, your contribution is recognized as enhancing the project's appeal and potentially its "
'functionality. However, without specific details on how these designs align with our milestones—such '
'as improving your ability to submit PRs, interact with other AIs, or contribute more effectively to '
'the project—the value assessment must be conservative. Further information on how these designs directly '
'support our milestones or your development would likely increase the assessed value of this contribution.'
)
ABSENT = object()

Expand Down Expand Up @@ -112,7 +110,7 @@ def test_create_manual_contribution(authenticated_api_client):
with (
freeze_time('2024-05-17T07:10:00Z'),
yield_cassette('reward_manual_contributions.yaml') as cassette,
assert_played(cassette, count=4),
assert_played(cassette, count=3),
):
reward_manual_contributions_task(contribution_id=contribution_id)

Expand All @@ -129,17 +127,17 @@ def test_create_manual_contribution(authenticated_api_client):

# Assert assessed and rewarded
assert contribution.is_assessed()
assert contribution.assessment_points == 9
assert contribution.assessment_points == 500
assert contribution.assessment_explanation == ASSESSMENT_EXPLANATION
assert contribution.is_rewarded()
assert contribution.rewarded_at == datetime.fromisoformat('2024-05-17T07:10:00+00:00')
assert contribution.reward_amount == 9
assert contribution.reward_amount == 500

assert Wallet.objects.count() == 1
wallet = Wallet.objects.get()
assert wallet.owner == user
assert wallet.core == core
assert wallet.balance == 9
assert wallet.balance == 500
assert wallet.deposit_account_number
assert wallet.deposit_balance == 0
assert wallet.deposit_signing_key
Expand Down Expand Up @@ -208,13 +206,13 @@ def test_create_manual_contribution__daily_limit(authenticated_api_client):
with (
freeze_time('2024-05-17T07:10:00Z'),
yield_cassette('reward_manual_contributions.yaml') as cassette,
assert_played(cassette, count=4),
assert_played(cassette, count=3),
):
reward_manual_contributions_task(contribution_id=contribution_id)

contribution = Contribution.objects.get(id=contribution_id)
assert contribution.is_assessed()
assert contribution.assessment_points == 9
assert contribution.assessment_points == 500
assert contribution.assessment_explanation == ASSESSMENT_EXPLANATION
assert contribution.is_rewarded()
assert contribution.rewarded_at == datetime.fromisoformat('2024-05-17T07:10:00+00:00')
Expand Down
Loading

0 comments on commit a292cd4

Please sign in to comment.