simple_chatwebUI / character.py
Yusuke710's picture
Upload folder using huggingface_hub
7524f15 verified
import os
import sys
import yaml
import openai
import backoff
import argparse
import logging
from llm import get_response_from_llm, create_client
# Set up logging
#logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Constants
DEFAULT_CONFIG_PATH = "characters/Viv.yaml"
DEFAULT_LLM_MODEL = "gpt-4o-2024-08-06"
DEFAULT_MAX_TOKENS = 4096
def get_openai_api_key():
"""Retrieve the OpenAI API key from environment variables."""
api_key = os.getenv('OPENAI_API_KEY')
if not api_key:
logger.error("OpenAI API key is not set. Please set the OPENAI_API_KEY environment variable.")
sys.exit(1)
return api_key
def load_character_config(config_path):
"""Load character configuration from a YAML file."""
try:
with open(config_path, 'r') as file:
return yaml.safe_load(file)
except FileNotFoundError:
logger.error(f"Configuration file not found: {config_path}")
sys.exit(1)
except yaml.YAMLError as e:
logger.error(f"Error parsing YAML file: {e}")
sys.exit(1)
def build_system_prompt(character_name):
"""Build the system prompt for the character."""
return (
f"You are {character_name}."
"You have lived a full life, and you are eager to help people understand what it is like to live with dementia."
)
def build_prompt(user_query, character_config):
"""Construct the prompt based on the user query and character configuration."""
personality_traits = character_config['personality']['traits']
core_description = character_config['character']['core_description']
character_name = character_config['character']['name']
return (
f"You are {character_name}. Your personality traits include: {', '.join(personality_traits)}. "
f"You are described as follows: {core_description}.\n\n"
"Answer the following question, staying true to your personality and experiences:\n"
f"User Query: {user_query}"
)
def get_character_response(user_query, character_config, llm_model=DEFAULT_LLM_MODEL, max_tokens=DEFAULT_MAX_TOKENS):
"""Get the character's response using the provided get_response_from_llm function."""
prompt = build_prompt(user_query, character_config)
system_prompt = build_system_prompt(character_config['character']['name'])
client, model = create_client(llm_model)
# Call the get_response_from_llm function
response_content, _ = get_response_from_llm(
msg=prompt,
client=client,
model=model,
system_message=system_prompt,
temperature=0.75,
)
return response_content
def main():
"""Main function to run the conversational agent."""
parser = argparse.ArgumentParser(description="Character Conversational Agent")
parser.add_argument('--config', type=str, default=DEFAULT_CONFIG_PATH, help='Path to character configuration YAML file')
args = parser.parse_args()
# Set up OpenAI API key
#openai.api_key = get_openai_api_key()
# Load character configuration
character_config = load_character_config(args.config)
character_name = character_config['character']['name']
print(f"Welcome to the {character_name} conversational agent! Ask any questions or type 'q' to quit.")
while True:
try:
user_query = input("Enter your question: ")
if user_query.lower() == 'q':
print("Goodbye!")
break
response = get_character_response(user_query, character_config)
print(f"{character_name}: {response}\n")
except KeyboardInterrupt:
print("\nGoodbye!")
break
except Exception as e:
logger.error(f"An error occurred: {e}")
continue
if __name__ == "__main__":
main()