Skip to content

Commit

Permalink
Merge pull request #15 from led-mirage/fix/error-handling
Browse files Browse the repository at this point in the history
Improve error handling for missing environment variables
  • Loading branch information
led-mirage authored Jan 25, 2025
2 parents 9e0a766 + b827585 commit 2e23d7b
Show file tree
Hide file tree
Showing 5 changed files with 87 additions and 33 deletions.
12 changes: 8 additions & 4 deletions Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ Windowsの場合は、Windowsの検索窓で「環境変数を編集」で検索

以下のリンクから ZundaGPT2Lite.ZIP をダウンロードして、作成したフォルダに展開するのだ。

https://github.com/led-mirage/ZundaGPT2Lite/releases/tag/v1.6.1
https://github.com/led-mirage/ZundaGPT2Lite/releases/tag/v1.6.2

#### 3. 実行

Expand Down Expand Up @@ -216,10 +216,10 @@ OpenAIやGoogle Gemini、AnthropicのAPIキーはあなただけのものなの

これが嫌な人は(ボクも嫌だけど)、Python本体をインストールしてPythonから普通に実行して欲しいのだ。実行ファイルのほうが手軽だし、そのほうがPythonに詳しくない人にとっては簡単なんだけど、誤認問題がついて回ることは覚えておいて欲しいのだ。

VirusTotalでの[チェック結果](https://www.virustotal.com/gui/file/f60fe38160e5ea67550957d2be1c0593beff62f18843245117be71d09e3011cd)は以下の通りなのだ。
(72個中3個のアンチウィルスエンジンで検出 :2025/01/18 v1.6.1)。
VirusTotalでの[チェック結果](https://www.virustotal.com/gui/file/89ba0509c16277ae0002c73aee33c1fb61b825f5c33889d72801e179f1847823)は以下の通りなのだ。
(72個中3個のアンチウィルスエンジンで検出 :2025/01/25 v1.6.2)。

<img src="doc/virustotal_1.6.1.png" width="600">
<img src="doc/virustotal_1.6.2.png" width="600">

### ⚡ 免責事項

Expand Down Expand Up @@ -389,3 +389,7 @@ VirusTotalでの[チェック結果](https://www.virustotal.com/gui/file/f60fe38
### 1.6.1 (2025/01/18)

- Fix: index.htmlで使っているscriptタグにSRIハッシュを追加

### 1.6.2 (2025/01/25)

- Fix: 環境変数がセットされていないときのエラー処理を変更
53 changes: 36 additions & 17 deletions app/chat/chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,11 @@ def __init__(self, client, model: str, instruction: str, bad_response: str, hist
self.chat_start_time = datetime.now()
self.chat_update_time = datetime.now()
self.stop_send_event = threading.Event()
self.client_creation_error = ""

# AIエージェントが利用可能かどうかを返す
def is_ai_agent_available(self):
return self.client is not None

# 指定index以下のメッセージを切り捨てる
def truncate_messages(self, index):
Expand Down Expand Up @@ -108,10 +113,11 @@ def send_message(
class ChatOpenAI(Chat):
def __init__(self, model: str, instruction: str, bad_response: str, history_size: int, api_timeout: float):
api_key = os.environ.get("OPENAI_API_KEY")
if api_key is None:
raise ValueError(get_text_resource("ERROR_MISSING_OPENAI_API_KEY"))

client = OpenAI(timeout=httpx.Timeout(api_timeout, connect=5.0))
client = None
if api_key:
client = OpenAI(timeout=httpx.Timeout(api_timeout, connect=5.0))

super().__init__(
client = client,
model = model,
Expand All @@ -120,18 +126,19 @@ def __init__(self, model: str, instruction: str, bad_response: str, history_size
history_size = history_size
)

if api_key is None:
self.client_creation_error = get_text_resource("ERROR_MISSING_OPENAI_API_KEY")

# Azure OpenAI チャットクラス
class ChatAzureOpenAI(Chat):
def __init__(self, model: str, instruction: str, bad_response: str, history_size: int, api_timeout: float):
endpoint = os.environ.get("AZURE_OPENAI_ENDPOINT")
if endpoint is None:
raise ValueError(get_text_resource("ERROR_MISSING_AZURE_OPENAI_ENDPOINT"))

api_key = os.environ.get("AZURE_OPENAI_API_KEY")
if api_key is None:
raise ValueError(get_text_resource("ERROR_MISSING_AZURE_OPENAI_API_KEY"))

client = AzureOpenAI(azure_endpoint=endpoint, api_key=api_key, api_version="2023-05-15", timeout=httpx.Timeout(api_timeout, connect=5.0))
client = None
if endpoint and api_key:
client = AzureOpenAI(azure_endpoint=endpoint, api_key=api_key, api_version="2023-05-15", timeout=httpx.Timeout(api_timeout, connect=5.0))

super().__init__(
client = client,
model = model,
Expand All @@ -140,17 +147,23 @@ def __init__(self, model: str, instruction: str, bad_response: str, history_size
history_size = history_size
)

if endpoint is None:
self.client_creation_error = get_text_resource("ERROR_MISSING_AZURE_OPENAI_ENDPOINT")
if api_key is None:
self.client_creation_error = get_text_resource("ERROR_MISSING_AZURE_OPENAI_API_KEY")

# Google Gemini チャットクラス
class ChatGemini(Chat):
def __init__(self, model: str, instruction: str, bad_response: str, history_size: int, gemini_option: dict):
self.gemini_option = gemini_option

api_key = os.environ.get("GEMINI_API_KEY")
if api_key is None:
raise ValueError(get_text_resource("ERROR_MISSING_GEMINI_API_KEY"))
genai.configure(api_key=api_key)

client = genai.GenerativeModel(model)
client = None
if api_key:
genai.configure(api_key=api_key)
client = genai.GenerativeModel(model)

super().__init__(
client = client,
model = model,
Expand All @@ -159,6 +172,9 @@ def __init__(self, model: str, instruction: str, bad_response: str, history_size
history_size = history_size
)

if api_key is None:
self.client_creation_error = get_text_resource("ERROR_MISSING_GEMINI_API_KEY")

# メッセージを送信して回答を得る
def send_message(
self,
Expand Down Expand Up @@ -260,11 +276,11 @@ def convert_messages(self, messages):
class ChatClaude(Chat):
def __init__(self, model: str, instruction: str, bad_response: str, history_size: int):
api_key = os.environ.get("ANTHROPIC_API_KEY")
if api_key is None:
raise ValueError(get_text_resource("ERROR_MISSING_ANTHROPIC_API_KEY"))
genai.configure(api_key=api_key)

client = anthropic.Anthropic()
client = None
if api_key:
client = anthropic.Anthropic()

super().__init__(
client = client,
model = model,
Expand All @@ -273,6 +289,9 @@ def __init__(self, model: str, instruction: str, bad_response: str, history_size
history_size = history_size
)

if api_key is None:
self.client_creation_error = get_text_resource("ERROR_MISSING_ANTHROPIC_API_KEY")

# メッセージを送信して回答を得る
def send_message(
self,
Expand Down
35 changes: 25 additions & 10 deletions app/html/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@
let g_searchTextTotal = 0;
let g_welcomeTitle = "";
let g_welcomeMessage = "";
let g_aiAgentAvailable = false;
let g_aiAgentCreationError = "";

// 初期化
document.addEventListener("DOMContentLoaded", function() {
Expand Down Expand Up @@ -248,6 +250,11 @@

// メッセージを送信する
async function sendMessage() {
if (!g_aiAgentAvailable) {
alert(g_aiAgentCreationError);
return;
}

const text = document.getElementById("message").value;
if (text === "") return;

Expand Down Expand Up @@ -418,12 +425,14 @@
}
else {
// 再回答ボタンをつける
const retryElement = document.createElement("button");
retryElement.classList.add("chat-reanswer-btn");
retryElement.textContent = "🔄️";
retryElement.style.display = "none";
retryElement.addEventListener("click", reAnswerChat);
speakerElement.appendChild(retryElement);
if (g_aiAgentAvailable) {
const retryElement = document.createElement("button");
retryElement.classList.add("chat-reanswer-btn");
retryElement.textContent = "🔄️";
retryElement.style.display = "none";
retryElement.addEventListener("click", reAnswerChat);
speakerElement.appendChild(retryElement);
}
}

// メッセージテキストを表示する要素を作成
Expand Down Expand Up @@ -649,7 +658,11 @@

// Pythonから呼び出される関数
// 情報をセットする
function setChatInfo(displayName, userName, userColor, userIcon, assistantName, assistantColor, assistantIcon, welcomeTitle, welcomeMessage) {
function setChatInfo(
displayName, userName, userColor, userIcon,
assistantName, assistantColor, assistantIcon,
welcomeTitle, welcomeMessage, aiAgentAvailable, aiAgentCreationError
) {
g_userName = userName;
g_userColor = userColor;
g_userIcon = userIcon;
Expand All @@ -659,6 +672,8 @@
g_nextMessageIndex = 0;
g_welcomeTitle = welcomeTitle;
g_welcomeMessage = welcomeMessage;
g_aiAgentAvailable = aiAgentAvailable;
g_aiAgentCreationError = aiAgentCreationError;

if (displayName === "") {
displayName = assistantName;
Expand Down Expand Up @@ -729,8 +744,8 @@
// Pythonから呼び出される関数
// チャット応答で例外が発生した
function handleChatException(message) {
alert(message)
endResponse()
alert(message);
endResponse();
}

// Pythonから呼び出される関数
Expand Down Expand Up @@ -776,7 +791,7 @@
}
MathJax.typesetPromise();
scrollToBottom();
showChatRetryButton()
showChatRetryButton();
}

// 再回答ボタンをすべて非表示にする
Expand Down
20 changes: 18 additions & 2 deletions app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
import pyi_splash # type: ignore

APP_NAME = "ZundaGPT2 Lite"
APP_VERSION = "1.6.1"
APP_VERSION = "1.6.2"
COPYRIGHT = "Copyright 2024-2025 led-mirage"

# アプリケーションクラス
Expand Down Expand Up @@ -108,8 +108,24 @@ def set_chatinfo_to_ui(self):
assistant_icon = self.get_image_base64(self.settings.assistant["icon"])
welcome_title = self.settings.settings.get("welcome_title", "")
welcome_message = self.settings.settings.get("welcome_message", "")
ai_agent_available = "true" if self.chat.is_ai_agent_available() else "false"
ai_agent_creation_error = self.chat.client_creation_error

self._window.evaluate_js(
f"setChatInfo('{display_name}', '{user_name}', '{user_color}', '{user_icon}', '{assistant_name}', '{assistant_color}', '{assistant_icon}', '{welcome_title}', '{welcome_message}')")
f"setChatInfo("
f"'{display_name}', "
f"'{user_name}', "
f"'{user_color}', "
f"'{user_icon}', "
f"'{assistant_name}', "
f"'{assistant_color}', "
f"'{assistant_icon}', "
f"'{welcome_title}', "
f"'{welcome_message}', "
f"{ai_agent_available}, "
f"'{ai_agent_creation_error}'"
f")"
)

# ひとつ前のチャットを表示して続ける
def prev_chat(self):
Expand Down
Binary file added doc/virustotal_1.6.2.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit 2e23d7b

Please sign in to comment.