Spaces:
Sleeping
Sleeping
File size: 2,029 Bytes
db17eb5 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
"""AI model clients and API configuration for OpenAI and Anthropic."""
from openai import OpenAI
import anthropic
import os
from dotenv import load_dotenv
from .constants import OPENAI_MODEL, CLAUDE_MODEL, MAX_TOKENS, logger
# Load environment variables from .env file
load_dotenv(override=True)
# Retrieve API keys from environment variables
openai_api_key = os.getenv("OPENAI_API_KEY")
anthropic_api_key = os.getenv("ANTHROPIC_API_KEY")
# Warn if any API key is missing for proper error handling
if not openai_api_key:
logger.error("❌ OpenAI API Key is missing!")
if not anthropic_api_key:
logger.error("❌ Anthropic API Key is missing!")
# Initialize API clients with the retrieved keys
openai = OpenAI(api_key=openai_api_key)
claude = anthropic.Anthropic()
def get_gpt_completion(prompt, system_message):
"""Call OpenAI's GPT model with prompt and system message."""
try:
# Create chat completion with system and user messages
response = openai.chat.completions.create(
model=OPENAI_MODEL,
messages=[
{"role": "system", "content": system_message},
{"role": "user", "content": prompt},
],
stream=False,
)
# Extract and return the generated content
return response.choices[0].message.content
except Exception as e:
logger.error(f"GPT error: {e}")
raise
def get_claude_completion(prompt, system_message):
"""Call Anthropic's Claude model with prompt and system message."""
try:
# Create message with Claude API using system prompt and user message
result = claude.messages.create(
model=CLAUDE_MODEL,
max_tokens=MAX_TOKENS,
system=system_message,
messages=[{"role": "user", "content": prompt}],
)
# Extract and return the text content from response
return result.content[0].text
except Exception as e:
logger.error(f"Claude error: {e}")
raise
|