67 lines
2.4 KiB
Python
67 lines
2.4 KiB
Python
|
|
import os
|
||
|
|
import json
|
||
|
|
from openai import OpenAI
|
||
|
|
from pydantic import BaseModel, Field
|
||
|
|
from typing import List, Dict, Optional
|
||
|
|
from src.prompts.sops import *
|
||
|
|
from src.prompts.chatbot import *
|
||
|
|
from src.models.sop_response_schemas import *
|
||
|
|
from src.models.bot_response_schema import *
|
||
|
|
from dotenv import load_dotenv
|
||
|
|
load_dotenv()
|
||
|
|
|
||
|
|
|
||
|
|
#SopGeneratorDocument
|
||
|
|
class Chatbot:
|
||
|
|
def __init__(self):
|
||
|
|
self.api_key = os.getenv("OPENAI_API_KEY")
|
||
|
|
self.client = OpenAI(api_key=self.api_key)
|
||
|
|
self.model = "gpt-4o-mini"
|
||
|
|
|
||
|
|
def _extract_text_from_docs(self, docs):
|
||
|
|
"""Extract text content from document objects."""
|
||
|
|
return [doc.page_content for doc in docs]
|
||
|
|
# Existing methods...
|
||
|
|
|
||
|
|
def validate_worker(self, question, docs) -> VisionMissionResponse:
|
||
|
|
"""
|
||
|
|
This method is responsible for validating the worker's response ("yes" or "no") using the provided document(s).
|
||
|
|
The system generates a prompt, extracts document content, and validates the response using the GPT-4 model.
|
||
|
|
|
||
|
|
:param question: The yes/no question asked to the worker.
|
||
|
|
:param docs: A list of document(s) uploaded by the worker.
|
||
|
|
:return: VisionMissionResponse containing the validated result or None if an error occurs.
|
||
|
|
"""
|
||
|
|
try:
|
||
|
|
docs_text = self._extract_text_from_docs(docs)
|
||
|
|
prompt = validate_worker_prompt()
|
||
|
|
response = self.client.beta.chat.completions.parse(
|
||
|
|
model=self.model,
|
||
|
|
messages=[
|
||
|
|
{
|
||
|
|
"role": "system",
|
||
|
|
"content": f'''{prompt} The document is uploaded next.'''
|
||
|
|
},
|
||
|
|
{
|
||
|
|
"role": "user",
|
||
|
|
"content": f"Question :{question}",
|
||
|
|
},
|
||
|
|
{
|
||
|
|
"role": "user",
|
||
|
|
"content": [{"type": "text", "text": text} for text in docs_text],
|
||
|
|
}
|
||
|
|
],
|
||
|
|
response_format=ValidateWorker,
|
||
|
|
max_tokens=4096,
|
||
|
|
temperature=0.1
|
||
|
|
)
|
||
|
|
|
||
|
|
# Parse the response from the LLM
|
||
|
|
extracted_text = json.loads(response.choices[0].message.content)
|
||
|
|
|
||
|
|
return extracted_text
|
||
|
|
|
||
|
|
except Exception as e:
|
||
|
|
print(f"An error occurred: {e}")
|
||
|
|
return None
|