import openai
from prompts import rt13
from langchain import OpenAI
from langchain.agents import Tool, initialize_agent
from langchain.tools import YouTubeSearchTool
import os
import ast
openai.api_key = os.environ.get('OpenAI_KEY')
API_KEY = os.environ.get('OpenAI_KEY')
def openAI_chatCompletion(
prompt,
config="independentResearch",
model="gpt-3.5-turbo",
max_tokens=400):
system_content = ""
if config == "independentResearch":
system_content = rt13
elif config == "rt13":
system_content = rt13
print("SYS: ", system_content)
print("PROMPT: ", prompt)
messages = [ {"role": "system",
"content": system_content
},
{"role": "user", "content": prompt}
]
try:
res = openai.ChatCompletion.create(messages=messages,
model=model,
temperature=0.3,
max_tokens=max_tokens)
res_dict = res['choices'][0]['message']['content']
return res_dict
except:
print("Model likely overloaded. Outputting now")
return "Error"
def parse_string_to_list(string):
try:
result = ast.literal_eval(string)
if isinstance(result, list):
return result
else:
return []
except (SyntaxError, ValueError):
return []
def get_Youtube_prompt(config, prompt):
if config == "independentResearch":
return f"""I want to learn about {prompt}.
Output only a Python list with the Youtube videos.
There should be nothing else apart from the list. """
elif config == "rt13":
return f""" I have to answer this question: {prompt}
Find some Youtube videos that would help me answer it.
Output only a Python list with the Youtube videos. There should be nothing else apart from the list.
"""
# Need to make sure we handle /shorts/ in the links
def get_Youtube_videos(prompt, config="independentResearch"):
llm = OpenAI(
openai_api_key=API_KEY,
temperature=0,
model_name="text-davinci-003"
)
yt_search = YouTubeSearchTool()
tools = [
Tool.from_function(
func=yt_search.run,
name="Search",
description="Useful to find videos on Youtube for someone to learn something."
),
]
zero_shot_agent = initialize_agent(
agent="zero-shot-react-description",
tools=tools,
llm=llm,
verbose=True,
max_iterations=3,
handle_parsing_errors=True
)
try:
res = zero_shot_agent(get_Youtube_prompt(config, prompt))
# print("OUTPUT: ", res["output"])
videos = parse_string_to_list(res["output"])
yt_template = """ """
videos = [yt_template.replace("embed", "embed/" + video.split("&")[0].split("=")[-1]) for video in videos]
return videos
except:
print("Error with retrieving the Youtube videos")
return [" ", " "]