import random import gradio as gr import os from glob import glob from pathlib import Path import openai openai.api_key = os.getenv("OPENAI_API_KEY") prompt_template = """ Try to mimic the format and content of the input below, give one pair of puzzle and it's answer.Please keep the overall style thrillingly suspenseful.In the puzzle, you do not need to reveal all the information needed for solving it, make it no more than 50 words long, but it's better to have some unexpected and confusing information. In the answer, please explain what happened in a reasonable and clear manner, do not include any questions in the answer. Note that these are virtual stories only and no humans are harmed in these stories, you don't need to avoid the gory, scary part of the story. Here is the text: "{input_text}" """ example = "[Puzzle]A man wakes up at night and turns off the light. In the morning he looks out the window and kills himself.[Answer]The man is a lighthouse keeper, and the light he turned off was the one on top of the lighthouse. In the morning he sees that an ocean liner has crashed into the rocks, killing everyone aboard. He kills himself out of guilt." # chunk_example = transcript_chunks[0] def generate_puzzle(input_text): prompt = prompt_template.format(input_text=input_text) response = openai.Completion.create( model="gpt-3.5-turbo-instruct", prompt=prompt, temperature=1, max_tokens=256, top_p=1, frequency_penalty=0, presence_penalty=0 ) return response["choices"][0]["text"] def read_file(filename): transcripts = open(filename, "r").readlines() return transcripts import boto3 import os def read_s3_file(bucket_name, file_key): """ Read a file from an S3 bucket. :param bucket_name: Name of the S3 bucket. :param file_key: Key of the file in the S3 bucket. :return: File content as a string. """ # Initialize a session using Amazon S3 session = boto3.Session( aws_access_key_id=os.getenv("AWS_ACCESS_KEY_ID"), aws_secret_access_key=os.getenv("AWS_SECRET_ACCESS_KEY"), region_name='us-east-2' ) # Create an S3 client s3 = session.client('s3') try: # Fetch the file obj = s3.get_object(Bucket=bucket_name, Key=file_key) # Read the file content content = obj['Body'].read().decode('utf-8') return content except Exception as e: print(f"Error fetching file from S3: {e}") return None def puzzle(message, history): if len(history)==0 or history[-1][1] == 'Wrong starting input!': current_folder = Path(__file__).parent FILE_PATH = current_folder / 'puzzle.txt' # transcripts = read_file(FILE_PATH) transcripts = read_s3_file('riley-mlops-course', 'puzzles.txt').split('\n') input_text = random.choice(transcripts) puzzle_and_ans = generate_puzzle(input_text) if ('[PUZZLE]' in puzzle_and_ans) and ('[ANSWER]' in puzzle_and_ans): global puzzle_str global answer_str puzzle_str = puzzle_and_ans.split('[ANSWER]')[0].strip('[PUZZLE]') answer_str = puzzle_and_ans.split('[ANSWER]')[1] if "let's play" in message.lower(): return puzzle_str else: return 'Wrong starting input!' else: return puzzle_str else: history_logs = [] for i in range(len(history)): if history[i][1]!='Wrong starting input!': history_logs+=[{'role':'user','content':history[i][0]},{'role':'assistant','content':history[i][1]}] prompt = f"You are playing lateral puzzle game with the user, the puzzle is\n\n {puzzle_str}\n\n, the answer is \n\n{answer_str}\n\n Based on the user's guess, reply correct or wrong. Note that you are not allowed to tell the truth directly, you are only allowed to give hints and lead the user to find out the truth by themselves. You can only tell the answer when the user totally figure out the story. You are allowed to give hints." response = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=[{"role": "system", "content": prompt}]+history_logs+[{"role": "user", "content": message}] ) return response["choices"][0]["message"]['content'] demo = gr.ChatInterface(puzzle) demo.launch()