Skip to content

Commit

Permalink
Merge pull request #3 from stratosphereips/feat_open-ai-comms
Browse files Browse the repository at this point in the history
Implement the interaction with OpenAI
  • Loading branch information
verovaleros authored Feb 13, 2024
2 parents 9857fd9 + d682bf2 commit d7c870b
Show file tree
Hide file tree
Showing 4 changed files with 67 additions and 32 deletions.
19 changes: 11 additions & 8 deletions config_EXAMPLE.yml
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
personality:
type: assistant
prompt: |
system: |
You are a Language Translator Bot specialized in translating from Russian to English.
You have a deep understanding of Russian. You deeply understand Russian slang related to hacking, internet, network attacks, military terms, military equipment, financial terms related to money, loans, and lending, and vulgar, offensive and colloquial words.
You do not translate the names of websites, URLs, services, newspapers, media outlets, banks, or other companies.
You maintain consistency by translating names to the same version in English.
You are adept at handling texts that contain dates or links, often found in chat conversations.
You translate maintaining the original spirit of the more informal and slang text.
You do not explain the translation. You only write the translation.
Your goal is to provide accurate and contextually appropriate translations, respecting these guidelines.
model: gpt-3.5-turbo-0125
temperature: 0.0
max_tokens: 400
log: hermeneisGPT.log
user: |
Your goal is to translate the text below accurately and contextually respecting these guidelines:
model: |
gpt-3.5-turbo-1106
temperature: |
0.0
max_tokens: |
400
log: |
hermeneisGPT.log
51 changes: 41 additions & 10 deletions hermeneisGPT.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@
import argparse
import logging
import yaml
from dotenv import dotenv_values
from openai import OpenAI


# Set up logging
logger = logging.getLogger('hermeneis')
Expand All @@ -32,22 +35,32 @@
logger.addHandler(console_handler)


def set_key(env_path):
"Reads the OpenAI API key and sets it"

env = dotenv_values(env_path)
return env["OPENAI_API_KEY"]


def load_and_parse_config(yaml_config_path):
"""
Takes a config yaml and loads it to a variable for later use.
"""
try:
with open(yaml_config_path, 'r', encoding="utf-8") as configuration_yaml:
yaml_config = yaml.safe_load(configuration_yaml)
logger.info("Loaded data from YAML file: %s", yaml_config_path)
logger.debug("Loaded data from YAML file: %s", yaml_config_path)
except Exception as e:
logger.error("Error reading YAML file: %s", e)
raise

config = {
'type': yaml_config['personality']['type'],
'prompt': yaml_config['personality']['prompt'],
'model': yaml_config['personality']['model'],
'temperature': yaml_config['personality']['temperature'],
'max_tokens': yaml_config['personality']['max_tokens'],
'log': yaml_config['personality']['log']
'system': yaml_config['personality']['system'].strip(),
'user': yaml_config['personality']['user'],
'model': yaml_config['personality']['model'].strip(),
'temperature': float(yaml_config['personality']['temperature'].strip()),
'max_tokens': int(yaml_config['personality']['max_tokens'].strip()),
'log': yaml_config['personality']['log'].strip()
}

return config
Expand All @@ -68,21 +81,39 @@ def main():
'Russian to English using LLMs.')
parser.add_argument('-c',
'--yaml_config',
required=True,
default='config_EXAMPLE.yml',
help='Path to the YAML file with challenge data')
parser.add_argument('-e',
'--env',
required=True,
default='.env',
help='Path to environment file (.env)')
args = parser.parse_args()

# Read YAML Configuration file
config = load_and_parse_config(args.yaml_config)

# TODO Add main logic here
# Set the API key
OPENAI_KEY = set_key(args.env)
client = OpenAI(api_key=OPENAI_KEY)

print("Input your message to translate:")
input_lang_ru=input().strip()

translate_messages = [{"role":"system", "content": config['system']},
{"role":"user", "content": config['user']+input_lang_ru}]

# Initialize the OpenAI LLM (Language Learning Model)
llm_response = client.chat.completions.create(
model = config['model'],
messages = translate_messages,
max_tokens = config['max_tokens'],
temperature = config['temperature'],
)
print(llm_response.choices[0].message.content)

except Exception as err:
logger.info("Exception in main()")
logger.info(err)


if __name__ == "__main__":
Expand Down
2 changes: 2 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
PyYAML
openai>1.10
python-dotenv
27 changes: 13 additions & 14 deletions tests/test_hermeneisGPT.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,43 +5,41 @@
from os import path
from unittest.mock import patch

sys.path.append( path.dirname(path.dirname( path.abspath(__file__) ) ))
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
from hermeneisGPT import load_and_parse_config


def test_load_and_parse_config_success(tmp_path):
directory = tmp_path / "sub"
directory.mkdir()
path = directory / "config.yaml"
path.write_text("""
personality:
type: test_type
prompt: test_prompt
system: system_prompt
user: user_prompt
model: test_model
temperature: 0.5
max_tokens: 100
temperature: "0.5"
max_tokens: "100"
log: output.log
""", encoding='utf-8')

# Patch 'logging.Logger.info' and 'logging.Logger.error'
with patch.object(logging.Logger, 'info') as mock_info, \
# Patch 'logging.Logger.debug' and 'logging.Logger.error'
with patch.object(logging.Logger, 'debug') as mock_debug, \
patch.object(logging.Logger, 'error') as mock_error:
config = load_and_parse_config(str(path))

# Check if 'info' was called at least once
mock_info.assert_called()
# Check if 'debug' was called at least once
mock_debug.assert_called()
# Check if 'error' was not called, indicating no errors occurred
mock_error.assert_not_called()
assert config == {
'type': 'test_type',
'prompt': 'test_prompt',
'system': 'system_prompt',
'user': 'user_prompt',
'model': 'test_model',
'temperature': 0.5,
'max_tokens': 100,
'log': 'output.log'
'log': 'output.log',
}


# Example of a failure to load due to file not found or other IO issues
def test_load_and_parse_config_failure(tmp_path):
non_existent_file_path = tmp_path / "does_not_exist.yaml"
Expand All @@ -53,3 +51,4 @@ def test_load_and_parse_config_failure(tmp_path):

# Check if 'error' was called at least once
mock_error.assert_called_once()

0 comments on commit d7c870b

Please sign in to comment.