generated from pheonix-coder/flask-minimal-template
-
Notifications
You must be signed in to change notification settings - Fork 50
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #206 from Anushka-Pote/main
Enhanced Error Handling for API Calls and API Key Validation #201
- Loading branch information
Showing
4 changed files
with
121 additions
and
54 deletions.
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,70 +1,91 @@ | ||
import os | ||
import logging | ||
from groq import Groq | ||
from dotenv import load_dotenv | ||
from typing import List, Dict | ||
from openai import OpenAI | ||
import google.generativeai as genai | ||
from anthropic import Anthropic | ||
|
||
|
||
load_dotenv() | ||
|
||
# Set up logging | ||
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s") | ||
logger = logging.getLogger(__name__) | ||
|
||
def chat_with_chatbot(messages: List[Dict[str, str]], apiKey: str, engine: str) -> str: | ||
if engine == "groq": | ||
content = chat_with_groq(messages, apiKey) | ||
return content | ||
elif engine == "openai": | ||
content = chat_with_openai(messages, apiKey) | ||
return content | ||
elif engine == "anthropic": | ||
content = chat_with_anthropic(messages, apiKey) | ||
return content | ||
elif engine == "gemini": | ||
content = chat_with_gemini(messages, apiKey) | ||
if not apiKey: | ||
logger.error("API key is missing.") | ||
raise ValueError("API key is required for making API requests.") | ||
|
||
try: | ||
if engine == "groq": | ||
content = chat_with_groq(messages, apiKey) | ||
elif engine == "openai": | ||
content = chat_with_openai(messages, apiKey) | ||
elif engine == "anthropic": | ||
content = chat_with_anthropic(messages, apiKey) | ||
elif engine == "gemini": | ||
content = chat_with_gemini(messages, apiKey) | ||
else: | ||
logger.error(f"Unsupported engine: {engine}") | ||
raise ValueError(f"Unsupported engine: {engine}") | ||
logger.info(f"Request to {engine} API was successful.") | ||
return content | ||
else: | ||
raise ValueError(f"Unsupported engine: {engine}") | ||
|
||
except Exception as e: | ||
logger.error(f"Error in chat_with_chatbot function with engine {engine}: {e}") | ||
raise | ||
|
||
def chat_with_groq(messages: List[Dict[str, str]], apiKey: str) -> str: | ||
client = Groq(api_key=apiKey) | ||
chat_completion = client.chat.completions.create( | ||
messages=messages, | ||
model="llama3-8b-8192", | ||
) | ||
return chat_completion.choices[0].message.content | ||
|
||
try: | ||
client = Groq(api_key=apiKey) | ||
chat_completion = client.chat.completions.create( | ||
messages=messages, | ||
model="llama3-8b-8192", | ||
) | ||
return chat_completion.choices[0].message.content | ||
except Exception as e: | ||
logger.error(f"Error in chat_with_groq: {e}") | ||
raise | ||
|
||
def chat_with_openai(messages: List[Dict[str, str]], apiKey: str) -> str: | ||
client = OpenAI(api_key=apiKey) | ||
chat_completion = client.chat.completions.create( | ||
messages=messages, | ||
model="gpt-3.5-turbo", | ||
) | ||
return chat_completion.choices[0].message.content | ||
|
||
try: | ||
client = OpenAI(api_key=apiKey) | ||
chat_completion = client.chat.completions.create( | ||
messages=messages, | ||
model="gpt-3.5-turbo", | ||
) | ||
return chat_completion.choices[0].message.content | ||
except Exception as e: | ||
logger.error(f"Error in chat_with_openai: {e}") | ||
raise | ||
|
||
def chat_with_anthropic(messages: List[Dict[str, str]], apiKey: str) -> str: | ||
client = Anthropic(api_key=apiKey) | ||
chat_completion = client.messages.create( | ||
max_tokens=1024, | ||
messages=messages, | ||
model="claude-3-5-sonnet-latest", | ||
) | ||
return chat_completion.content | ||
|
||
try: | ||
client = Anthropic(api_key=apiKey) | ||
chat_completion = client.messages.create( | ||
max_tokens=1024, | ||
messages=messages, | ||
model="claude-3-5-sonnet-latest", | ||
) | ||
return chat_completion.content | ||
except Exception as e: | ||
logger.error(f"Error in chat_with_anthropic: {e}") | ||
raise | ||
|
||
def chat_with_gemini(messages: List[Dict[str, str]], apiKey: str) -> str: | ||
genai.configure(api_key=apiKey) | ||
model = genai.GenerativeModel("gemini-1.5-flash") | ||
formatted_messages = [ | ||
{ | ||
"role": ( | ||
message["role"] if message["role"] == "user" else "model" | ||
), # User or assistant | ||
"parts": [message["content"]], # Wrap the content in a list | ||
} | ||
for message in messages | ||
] | ||
response = model.generate_content(formatted_messages) | ||
return response.text | ||
try: | ||
genai.configure(api_key=apiKey) | ||
model = genai.GenerativeModel("gemini-1.5-flash") | ||
formatted_messages = [ | ||
{ | ||
"role": message["role"] if message["role"] == "user" else "model", | ||
"parts": [message["content"]], | ||
} | ||
for message in messages | ||
] | ||
response = model.generate_content(formatted_messages) | ||
return response.text | ||
except Exception as e: | ||
logger.error(f"Error in chat_with_gemini: {e}") | ||
raise |
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 |
---|---|---|
@@ -1,8 +1,21 @@ | ||
import logging | ||
from sqlalchemy import func | ||
from .models import User, Chatbot, Chat, Image | ||
from typing import Union, List, Optional, Dict | ||
|
||
logger = logging.getLogger(__name__) | ||
logger.setLevel(logging.INFO) | ||
handler = logging.FileHandler("contribution_data_fetch.log") | ||
handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')) | ||
logger.addHandler(handler) | ||
|
||
def fetch_contribution_data(db): | ||
users = db.session.query(User).order_by(User.contribution_score.desc()).all() | ||
return users | ||
"""Fetch user data sorted by contribution score, and log details.""" | ||
|
||
try: | ||
users = db.session.query(User).order_by(User.contribution_score.desc()).all() | ||
logger.info("Fetched user contribution data successfully.") | ||
return users | ||
except Exception as e: | ||
logger.error(f"Error fetching contribution data: {str(e)}") | ||
return [] |
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