|
| 1 | +import os |
| 2 | + |
| 3 | +import openai |
| 4 | +from openai.api_resources.engine import Engine |
| 5 | +from openai.error import APIError |
| 6 | + |
| 7 | +from binaryninja.lowlevelil import LowLevelILFunction |
| 8 | +from binaryninja.mediumlevelil import MediumLevelILFunction |
| 9 | +from binaryninja.highlevelil import HighLevelILFunction |
| 10 | + |
| 11 | +from .exceptions import InvalidEngineException |
| 12 | + |
| 13 | + |
| 14 | +class Agent: |
| 15 | + |
| 16 | + def ___init__(self, function: LowLevelILFunction | MediumLevelILFunction | |
| 17 | + HighLevelILFunction, engine: str) -> None: |
| 18 | + |
| 19 | + # Read the API key from the environment variable. |
| 20 | + openai.api_key = os.getenv('OPENAI_API_KEY') |
| 21 | + if openai.api_key is None: |
| 22 | + raise APIError('No API key found. Please set the environment ' |
| 23 | + 'variable OPENAI_API_KEY to your API key.') |
| 24 | + |
| 25 | + # Ensure that a function type was passed in. |
| 26 | + if not isinstance( |
| 27 | + function, |
| 28 | + (LowLevelILFunction, MediumLevelILFunction, HighLevelILFunction)): |
| 29 | + raise TypeError(f'Expected a BNIL function of type ' |
| 30 | + f'LowLevelILFunction, MediumLevelILFunction, or ' |
| 31 | + f'HighLevelILFunction, got {type(function)}.') |
| 32 | + |
| 33 | + # Get the list of available engines. |
| 34 | + engines: list[Engine] = openai.Engine.list().data |
| 35 | + # Ensure the user's selected engine is available. |
| 36 | + # pylint: disable=unnecessary-comprehension |
| 37 | + if engine not in [i.id for i in engines]: |
| 38 | + InvalidEngineException(f'Invalid engine: {engine}. Valid engines ' |
| 39 | + f'are: {[id for id in engines.id]}') |
| 40 | + |
| 41 | + # Set instance attributes. |
| 42 | + self.function = function |
| 43 | + self.engine = engine |
| 44 | + |
| 45 | + def instruction_list(self, function: LowLevelILFunction | |
| 46 | + MediumLevelILFunction | |
| 47 | + HighLevelILFunction) -> list[str]: |
| 48 | + '''Generates a list of instructions in string representation given a |
| 49 | + BNIL function. |
| 50 | + ''' |
| 51 | + instructions: list[str] = [] |
| 52 | + for instruction in function.instructions: |
| 53 | + instructions.append(str(instruction)) |
| 54 | + return instructions |
0 commit comments