Skip to content

Commit e7e0a4c

Browse files
committed
Add 'check_api_key'
1. Verify if the API key is entered. 2. Determine if the API key is usable. 3. Display the corresponding error or warning.
1 parent d47cb9b commit e7e0a4c

File tree

3 files changed

+62
-1
lines changed

3 files changed

+62
-1
lines changed

app.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ def load_api_key() -> None:
8787
if temp_file_path:
8888
os.remove(temp_file_path)
8989

90-
docGPT_tool, calculate_tool, search_tool, llm_tool = None, None, None, None
90+
docGPT_tool, calculate_tool, search_tool, llm_tool = [None] * 4
9191

9292
try:
9393
agent_ = AgentHelper()

docGPT/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
11
from .docGPT import DocGPT
2+
from .check_api_key import OpenAiAPI, SerpAPI

docGPT/check_api_key.py

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
import os
2+
from abc import ABC, abstractmethod
3+
4+
import openai
5+
import streamlit as st
6+
from langchain import SerpAPIWrapper
7+
8+
9+
class ApiKey(ABC):
10+
"""Check the Api key is valid or not"""
11+
query = 'This is a test.'
12+
13+
@classmethod
14+
@abstractmethod
15+
def is_valid(cls):
16+
pass
17+
18+
19+
class OpenAiAPI(ApiKey):
20+
@classmethod
21+
def is_valid(cls) -> str:
22+
if not st.session_state['openai_api_key']:
23+
st.error('⚠️ :red[You have not pass OpenAI API key.] Necessary Pass')
24+
return
25+
26+
openai.api_key = os.getenv('OPENAI_API_KEY')
27+
try:
28+
response = openai.Completion.create(
29+
engine='davinci',
30+
prompt=cls.query,
31+
max_tokens=5
32+
)
33+
return response
34+
except Exception as e:
35+
st.error(
36+
'🚨 :red[Your OpenAI API key has a problem.] '
37+
'[Check your usage](https://platform.openai.com/account/usage)'
38+
)
39+
print(f'Test error\n{e}')
40+
41+
42+
class SerpAPI(ApiKey):
43+
@classmethod
44+
def is_valid(cls) -> str:
45+
if not st.session_state['serpapi_api_key']:
46+
st.warning('⚠️ You have not pass SerpAPI key. (You cannot ask current events.)')
47+
return
48+
49+
os.environ['SERPAPI_API_KEY'] = os.getenv('SERPAPI_API_KEY')
50+
try:
51+
search = SerpAPIWrapper()
52+
response = search.run(cls.query)
53+
return response
54+
except Exception as e:
55+
st.error(
56+
'🚨 :red[Your SerpAPI key has a problem.] '
57+
'[Check your usage](https://serpapi.com/dashboard)'
58+
)
59+
print(f'Test error\n{e}')
60+

0 commit comments

Comments
 (0)