import os import toml from huggingfacehub import InferenceClient Load configuration from…
- User
import os import toml from huggingface_hub import InferenceClient
Load configuration from TOML file
CONFIG_DIRECTORY = "chat/pages/ai/config/" CONFIG_FILE = "config.toml"
def load_config(config_directory, config_file): """Load configuration from the given TOML file.""" config_path = os.path.join(config_directory, config_file) try: return toml.load(config_path) except (IOError, toml.TomlDecodeError) as e: print(f"Error loading configuration from {config_path}: {e}") return {}
Initialize Hugging Face client
def initialize_ai_client(model_name): """Initialize the Hugging Face AI client.""" try: return InferenceClient(model_name) except Exception as e: print(f"Error initializing AI client: {e}") return None
def chat_with_ai(prompt, client, max_tokens): """Send messages to the AI model and get a streaming response.""" try: response_generator = client.chat_completion( [{"role": "user", "content": prompt}], stream=True, max_tokens=max_tokens # Set max_tokens from the config )
# Collecting streamed responses full_response = "" for reply in response_generator: chunk = reply.choices[0].delta.content full_response += chunk print(chunk, end='', flush=True) # Print each chunk as it comes in print() # For a newline after the streaming response return full_response.strip() except Exception as e: return f"An error occurred while communicating with the AI: {e}"def generate_quote(user_feelings, client, max_tokens): """Generate a motivational quote based on the user's feelings.""" prompt = f"Based on the following feelings or situation:\n\n{user_feelings}\n\nPlease generate a motivational quote or prompt to uplift the user."
quote = chat_with_ai(prompt, client, max_tokens) return quotedef write_quote_to_file(quote, file_path): """Write the generated quote to a text file.""" with open(file_path, 'w') as f: f.write(quote)
def start_quote_generator(): """Start the quote generation process with the AI.""" config = load_config(CONFIG_DIRECTORY, CONFIG_FILE)
# Initialize AI Client model_name = config['ai']['model'] max_tokens = config['ai'].get('max_tokens', 1500) # Set default if not specified client = initialize_ai_client(model_name) if not client: return print("Welcome to the Quote Generator! Let's uplift your day!") user_feelings = input("How are you feeling today? (Please describe your current feelings): ") # Generate the motivational quote quote = generate_quote(user_feelings, client, max_tokens) print(f"\nGenerated Quote: {quote}") # Save the quote to a file output_file = "C:/Users/scott/Documents/github/project_longtime-1/chat/ai_output/quotes/" write_quote_to_file(quote, output_file) print(f"Quote has been saved to {output_file}.")if name == "main": start_quote_generator()
- Assistant
- User
- Assistant
- User
- Assistant
- User
- Assistant