✨ Add ai correction api endpoint

This commit is contained in:
Arnaud Robin
2024-09-12 15:56:32 +02:00
parent 77282907cb
commit ae82d137c2
5 changed files with 37 additions and 3 deletions
+3
View File
@@ -39,3 +39,6 @@ LOGOUT_REDIRECT_URL=http://localhost:3000
OIDC_REDIRECT_ALLOWED_HOSTS=["http://localhost:8083", "http://localhost:3000"]
OIDC_AUTH_REQUEST_EXTRA_PARAMS={"acr_values": "eidas1"}
AI_BASE_URL=https://openaiendpoint.com
AI_API_KEY=password
+25 -3
View File
@@ -1,5 +1,6 @@
"""API endpoints"""
import json
import os
import re
import uuid
@@ -17,6 +18,9 @@ from django.db.models import (
from django.http import Http404
from botocore.exceptions import ClientError
from openai import OpenAI
from rest_framework import (
decorators,
exceptions,
@@ -371,8 +375,7 @@ class DocumentViewSet(
@decorators.action(detail=True, methods=["post"], url_path="ai")
def ai(self, request, *args, **kwargs):
"""
Return the document's versions but only those created after the user got access
to the document
Process text using AI based on the specified action.
"""
if not request.user.is_authenticated:
raise exceptions.PermissionDenied("Authentication required.")
@@ -380,7 +383,26 @@ class DocumentViewSet(
action = request.data.get("action")
text = request.data.get("text")
return drf_response.Response(text.upper())
client = OpenAI(
base_url = settings.AI_BASE_URL,
api_key= settings.AI_API_KEY
)
if action == "rephrase":
try:
response = client.chat.completions.create(
model="meta-llama/Meta-Llama-3.1-70B-Instruct",
messages=[
{"role": "system", "content": 'Tu es un correcteur de texte. Corrige uniquement la grammaire et l\'orthographe de la phrase donnée. Renvoie uniquement un JSON au format suivant: {"phrase_corrigee": "ta phrase corrigée"}. Ne donne aucune autre information.'},
{"role": "user", "content": f'{{"phrase": "{text}"}}'},
]
)
corrected_response = json.loads(response.choices[0].message.content)
return drf_response.Response(corrected_response['phrase_corrigee'])
except (json.JSONDecodeError, KeyError) as e:
return drf_response.Response({"error": f"Error processing AI response: {str(e)}"}, status=500)
else:
return drf_response.Response({"error": "Invalid action"}, status=400)
@decorators.action(detail=True, methods=["get"], url_path="versions")
+6
View File
@@ -387,6 +387,12 @@ class Base(Configuration):
ALLOW_LOGOUT_GET_METHOD = values.BooleanValue(
default=True, environ_name="ALLOW_LOGOUT_GET_METHOD", environ_prefix=None
)
AI_BASE_URL = values.Value(
None, environ_name="AI_BASE_URL", environ_prefix=None
)
AI_API_KEY = values.Value(
None, environ_name="AI_API_KEY", environ_prefix=None
)
# pylint: disable=invalid-name
@property
+1
View File
@@ -47,6 +47,7 @@ dependencies = [
"jsonschema==4.23.0",
"markdown==3.7",
"nested-multipart-parser==1.5.0",
"openai==1.44.1",
"psycopg[binary]==3.2.1",
"PyJWT==2.9.0",
"pypandoc==1.13",
@@ -36,6 +36,8 @@ export function AIButton({ doc }: AIButtonProps) {
action,
});
console.log('AI response:', newText);
editor.insertInlineContent([
newText,
//{ type: 'text', text: 'World', styles: { bold: true } },