147 lines
No EOL
5.7 KiB
Python
147 lines
No EOL
5.7 KiB
Python
import logging
|
|
import httpx
|
|
from typing import Dict, Any, List, Optional, Union
|
|
from fastapi import HTTPException
|
|
from modules.utility import APP_CONFIG
|
|
|
|
# Logger konfigurieren
|
|
logger = logging.getLogger(__name__)
|
|
|
|
# Konfigurationsdaten laden
|
|
def load_config_data():
|
|
return {
|
|
"api_key": APP_CONFIG.get('Connector_AiOpenai_API_SECRET'),
|
|
"api_url": APP_CONFIG.get('Connector_AiOpenai_API_URL'),
|
|
"model_name": APP_CONFIG.get('Connector_AiOpenai_MODEL_NAME'),
|
|
"temperature": float(APP_CONFIG.get('Connector_AiOpenai_TEMPERATURE')),
|
|
"max_tokens": int(APP_CONFIG.get('Connector_AiOpenai_MAX_TOKENS'))
|
|
}
|
|
|
|
class ChatService:
|
|
"""
|
|
Connector für die Kommunikation mit der OpenAI API.
|
|
"""
|
|
|
|
def __init__(self):
|
|
# Konfiguration laden
|
|
self.config = load_config_data()
|
|
self.api_key = self.config["api_key"]
|
|
self.api_url = self.config["api_url"]
|
|
self.model_name = self.config["model_name"]
|
|
|
|
# HttpClient für API-Aufrufe
|
|
self.http_client = httpx.AsyncClient(
|
|
timeout=120.0, # Längeres Timeout für komplexe Anfragen
|
|
headers={
|
|
"Authorization": f"Bearer {self.api_key}",
|
|
"Content-Type": "application/json"
|
|
}
|
|
)
|
|
|
|
logger.info(f"OpenAI Connector initialisiert mit Modell: {self.model_name}")
|
|
|
|
async def call_api(self, messages: List[Dict[str, Any]], temperature: float = None, max_tokens: int = None) -> str:
|
|
"""
|
|
Ruft die OpenAI API mit den gegebenen Nachrichten auf.
|
|
|
|
Args:
|
|
messages: Liste von Nachrichten im OpenAI-Format (role, content)
|
|
temperature: Temperatur für die Antwortgenerierung (0.0-1.0)
|
|
max_tokens: Maximale Anzahl der Token in der Antwort
|
|
|
|
Returns:
|
|
Die Antwort der OpenAI API
|
|
|
|
Raises:
|
|
HTTPException: Bei Fehlern in der API-Kommunikation
|
|
"""
|
|
try:
|
|
# Verwende Parameter aus der Konfiguration, falls keine überschrieben wurden
|
|
if temperature is None:
|
|
temperature = self.config.get("temperature", 0.2)
|
|
|
|
if max_tokens is None:
|
|
max_tokens = self.config.get("max_tokens", 2000)
|
|
|
|
payload = {
|
|
"model": self.model_name,
|
|
"messages": messages,
|
|
"temperature": temperature,
|
|
"max_tokens": max_tokens
|
|
}
|
|
|
|
response = await self.http_client.post(
|
|
self.api_url,
|
|
json=payload
|
|
)
|
|
|
|
if response.status_code != 200:
|
|
logger.error(f"OpenAI API-Fehler: {response.status_code} - {response.text}")
|
|
raise HTTPException(status_code=500, detail="Fehler bei der Kommunikation mit OpenAI API")
|
|
|
|
response_json = response.json()
|
|
content = response_json["choices"][0]["message"]["content"]
|
|
return content
|
|
|
|
except Exception as e:
|
|
logger.error(f"Fehler beim Aufruf der OpenAI API: {str(e)}")
|
|
raise HTTPException(status_code=500, detail=f"Fehler beim Aufruf der OpenAI API: {str(e)}")
|
|
|
|
async def close(self):
|
|
"""Schließt den HTTP-Client beim Beenden der Anwendung"""
|
|
await self.http_client.aclose()
|
|
|
|
async def analyze_image(self, image_data: Union[str, bytes], mime_type: str = None, prompt: str = "Describe this image") -> str:
|
|
"""
|
|
Analysiert ein Bild mit der OpenAI Vision API.
|
|
|
|
Args:
|
|
image_data: Entweder ein Dateipfad (str) oder Bilddaten (bytes)
|
|
mime_type: Der MIME-Typ des Bildes (optional, nur für Binärdaten)
|
|
prompt: Der Prompt für die Analyse
|
|
|
|
Returns:
|
|
Die Antwort der OpenAI Vision API als Text
|
|
"""
|
|
try:
|
|
logger.debug("Starting image analysis...")
|
|
# Unterscheide zwischen Dateipfad und Binärdaten
|
|
if isinstance(image_data, str):
|
|
# Es ist ein Dateipfad - importiere filehandling nur bei Bedarf
|
|
from gateway.gwserver.modules import agentservice_filemanager as file_handler
|
|
base64_data, auto_mime_type = file_handler.encode_file_to_base64(image_data)
|
|
mime_type = mime_type or auto_mime_type
|
|
else:
|
|
# Es sind Binärdaten
|
|
import base64
|
|
base64_data = base64.b64encode(image_data).decode('utf-8')
|
|
# MIME-Typ muss angegeben sein für Binärdaten
|
|
if not mime_type:
|
|
# Fallback auf generischen Bildtyp
|
|
mime_type = "image/png"
|
|
|
|
# Bereite den Payload für die Vision API vor
|
|
messages = [
|
|
{
|
|
"role": "user",
|
|
"content": [
|
|
{"type": "text", "text": prompt},
|
|
{
|
|
"type": "image_url",
|
|
"image_url": {
|
|
"url": f"data:{mime_type};base64,{base64_data}"
|
|
}
|
|
}
|
|
]
|
|
}
|
|
]
|
|
|
|
# Verwende die bestehende call_api Funktion mit dem Vision-Modell
|
|
response = await self.call_api(messages)
|
|
|
|
# Inhalt extrahieren und zurückgeben
|
|
return response
|
|
|
|
except Exception as e:
|
|
logger.error(f"Fehler bei der Bildanalyse: {str(e)}", exc_info=True)
|
|
return f"[Fehler bei der Bildanalyse: {str(e)}]" |