Skip to content

Commit 04ca46a

Browse files
committed
Implement reading API key from Binary Ninja.
Users can now write their API key to Binary Ninja via Edit > Preferences > Settings > OpenAI (or use Command+, and search for OpenAI). This is the first place checked by the plugin. Implement #13.
1 parent 218a681 commit 04ca46a

1 file changed

Lines changed: 27 additions & 6 deletions

File tree

src/agent.py

Lines changed: 27 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
from binaryninja.lowlevelil import LowLevelILFunction
1010
from binaryninja.mediumlevelil import MediumLevelILFunction
1111
from binaryninja.highlevelil import HighLevelILFunction
12+
from binaryninja.settings import Settings
1213
from binaryninja import log
1314

1415
from .exceptions import InvalidEngineException
@@ -56,20 +57,40 @@ def __init__(self,
5657
self.engine = engine
5758

5859
def read_api_key(self, filename: Optional[Path]=None) -> str:
59-
if os.getenv('OPENAI_API_KEY'):
60-
return os.getenv('OPENAI_API_KEY')
60+
'''Checks for the API key in three locations.
61+
62+
First, it checks the openai.api_key key:value in Binary Ninja
63+
preferences. This is accessed in Binary Ninja by going to Edit >
64+
Preferences > Settings > OpenAI.
65+
Second, it checks the OPENAI_API_KEY environment variable.
66+
Finally, it checks the file specified by the filename argument.
67+
Defaults to ~/.openai/api_key.txt.
68+
'''
69+
70+
# First, check the Binary Ninja settings.
71+
settings: Settings = Settings()
72+
if settings.contains('openai.api_key'):
73+
if key := settings.get_string('openai.api_key'):
74+
return key
75+
76+
# If the settings don't exist, contain the key, or the key is empty,
77+
# check the environment variable.
78+
if key := os.getenv('OPENAI_API_KEY'):
79+
return key
80+
81+
# Finally, if the environment variable doesn't exist, check the default
82+
# file.
6183
if filename:
6284
log.log_info(f'No API key detected under the environment variable '
6385
f'OPENAI_API_KEY. Reading API key from {filename}')
6486
try:
6587
with open(filename, mode='r', encoding='ascii') as api_key_file:
6688
return api_key_file.read()
67-
except FileNotFoundError as error:
89+
except FileNotFoundError:
6890
log.log_error(f'Could not find API key file at {filename}.')
6991

70-
raise APIError('No API key found. Please set the environment '
71-
'variable OPENAI_API_KEY to your API key, or write '
72-
'it to ~/openai/api_key.txt.')
92+
raise APIError('No API key found. Refer to the documentation to add the '
93+
'API key.')
7394

7495

7596
def instruction_list(self, function: Union[LowLevelILFunction,

0 commit comments

Comments
 (0)