-
Notifications
You must be signed in to change notification settings - Fork 35
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
Chat: automatic answers & translations #3051
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
""" | ||
Wrapper for the Chat Bot / LLM API | ||
""" | ||
|
||
import requests | ||
from django.conf import settings | ||
|
||
from ....cms.models import Region | ||
|
||
|
||
class ChatBot: | ||
""" | ||
API Wrapper for the LLM / Chat Bot | ||
""" | ||
|
||
def __init__(self, hostname: str = "igchat-inference.tuerantuer.org"): | ||
self.hostname = hostname | ||
|
||
def automatic_answer(self, message: str, region: Region, language_slug: str) -> str: | ||
""" | ||
Get automatic answer to question | ||
""" | ||
url = f"https://{self.hostname}/chatanswers/extract_answer/" | ||
body = {"message": message, "language": language_slug, "region": region.slug} | ||
r = requests.post(url, json=body, timeout=30) | ||
return self.format_message(r.json()) | ||
|
||
def format_message(self, response: dict) -> str: | ||
""" | ||
Transform JSON into readable message | ||
""" | ||
sources = "".join( | ||
[ | ||
f"<li><a href='{settings.WEBAPP_URL}{path}'>{path}</a></li>" | ||
for path in response["sources"] | ||
] | ||
) | ||
return f"{response['answer']}\n<ul>{sources}</ul>" | ||
|
||
def automatic_translation( | ||
self, message: str, source_lang_slug: str, target_lang_slug: str | ||
) -> str: | ||
""" | ||
Use LLM to translate message | ||
""" | ||
raise NotImplementedError |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -4,16 +4,23 @@ | |
|
||
from __future__ import annotations | ||
|
||
import json | ||
import logging | ||
import random | ||
import socket | ||
from typing import TYPE_CHECKING | ||
|
||
from django.conf import settings | ||
from django.http import HttpResponse, JsonResponse | ||
from django.shortcuts import get_object_or_404 | ||
from django.utils.translation import gettext_lazy as _ | ||
from django.views.decorators.csrf import csrf_exempt | ||
from google.cloud import translate_v2 as translate # type: ignore[attr-defined] | ||
from google.oauth2 import service_account | ||
|
||
from ....cms.models import ABTester, AttachmentMap, UserChat | ||
from ....cms.models import ABTester, AttachmentMap, Language, Region, UserChat | ||
from ...decorators import json_response | ||
from .chat_bot import ChatBot | ||
from .zammad_api import ZammadChatAPI | ||
|
||
if TYPE_CHECKING: | ||
|
@@ -99,6 +106,18 @@ def get_messages( | |
return response_or_error(client.get_messages(user_chat)) | ||
|
||
|
||
def translate_message(message: str, language_slug: str) -> str: | ||
""" | ||
Translate a string with Google Translate | ||
""" | ||
credentials = service_account.Credentials.from_service_account_file( | ||
settings.GOOGLE_APPLICATION_CREDENTIALS | ||
) | ||
translate_client = translate.Client(credentials=credentials) | ||
result = translate_client.translate(message, target_language=language_slug) | ||
svenseeberg marked this conversation as resolved.
Show resolved
Hide resolved
|
||
return result["translatedText"] | ||
|
||
|
||
def send_message( | ||
request: HttpRequest, | ||
language_slug: str, | ||
|
@@ -120,7 +139,12 @@ def send_message( | |
if request.POST.get("force_new") or not user_chat: | ||
try: | ||
chat_id = client.create_ticket(device_id, language_slug)["id"] | ||
user_chat = UserChat.objects.create(device_id=device_id, zammad_id=chat_id) | ||
user_chat = UserChat.objects.create( | ||
device_id=device_id, | ||
zammad_id=chat_id, | ||
region=request.region, | ||
language=Language.objects.get(slug=language_slug), | ||
) | ||
except KeyError: | ||
logger.warning( | ||
"Failed to create a new chat in %r", | ||
|
@@ -210,3 +234,66 @@ def chat( | |
if request.method == "GET": | ||
return get_messages(request, client, user_chat, device_id) | ||
return send_message(request, language_slug, client, user_chat, device_id) | ||
|
||
|
||
@csrf_exempt | ||
@json_response | ||
def zammad_webhook(request: HttpRequest) -> JsonResponse: | ||
""" | ||
Receive webhooks from Zammad to update the latest article translation | ||
""" | ||
zammad_url = ( | ||
f"https://{socket.getnameinfo((request.META.get('REMOTE_ADDR'), 0), 0)[0]}" | ||
) | ||
region = get_object_or_404(Region, zammad_url=zammad_url) | ||
client = ZammadChatAPI(region) | ||
webhook_message = json.loads(request.body) | ||
message_text = webhook_message["article"]["body"] | ||
zammad_chat = UserChat.objects.get(zammad_id=webhook_message["ticket"]["id"]) | ||
|
||
actions = [] | ||
if webhook_message["article"]["internal"]: | ||
return JsonResponse( | ||
{ | ||
"region": region.slug, | ||
"results": "skipped internal message", | ||
} | ||
) | ||
if ( | ||
webhook_message["article"]["created_by"]["login"] | ||
== "[email protected]" | ||
): | ||
logger.debug("Automatic answer & question translation") | ||
actions.append("Automatic answer & question translation") | ||
client.send_message( | ||
zammad_chat.zammad_id, | ||
translate_message(message_text, region.default_language.slug), | ||
True, | ||
True, | ||
) | ||
chat_bot = ChatBot() | ||
answer = chat_bot.automatic_answer( | ||
message_text, region, zammad_chat.language.slug | ||
) | ||
client.send_message( | ||
zammad_chat.zammad_id, | ||
answer, | ||
False, | ||
True, | ||
) | ||
else: | ||
logger.debug("Automatic answer translation") | ||
actions.append("Automatic answer translation") | ||
client.send_message( | ||
zammad_chat.zammad_id, | ||
translate_message(message_text, zammad_chat.language.slug), | ||
False, | ||
True, | ||
) | ||
return JsonResponse( | ||
{ | ||
"original_message": message_text, | ||
"region": region.slug, | ||
"actions": actions, | ||
} | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Please note:
/api/v3/webhook/...
is a generic new path for webhooks.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Could you add some documentation for that at https://github.com/digitalfabrik/integreat-cms/blob/develop/docs/src/api-docs.rst?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Done.