File size: 3,832 Bytes
7524f15
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
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()