├── README.md └── main.py /README.md: -------------------------------------------------------------------------------- 1 | This is the code from my chat bot on YouTube. It's a very quick example of how you can use the openai api to create a chat bot with AI. 2 | -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | import openai 2 | 3 | openai.api_key = 'YOUR API KEY' 4 | 5 | 6 | def get_api_response(prompt: str) -> str | None: 7 | text: str | None = None 8 | 9 | try: 10 | response: dict = openai.Completion.create( 11 | model='text-davinci-003', 12 | prompt=prompt, 13 | temperature=0.9, 14 | max_tokens=150, 15 | top_p=1, 16 | frequency_penalty=0, 17 | presence_penalty=0.6, 18 | stop=[' Human:', ' AI:'] 19 | ) 20 | 21 | choices: dict = response.get('choices')[0] 22 | text = choices.get('text') 23 | 24 | except Exception as e: 25 | print('ERROR:', e) 26 | 27 | return text 28 | 29 | 30 | def update_list(message: str, pl: list[str]): 31 | pl.append(message) 32 | 33 | 34 | def create_prompt(message: str, pl: list[str]) -> str: 35 | p_message: str = f'\nHuman: {message}' 36 | update_list(p_message, pl) 37 | prompt: str = ''.join(pl) 38 | return prompt 39 | 40 | 41 | def get_bot_response(message: str, pl: list[str]) -> str: 42 | prompt: str = create_prompt(message, pl) 43 | bot_response: str = get_api_response(prompt) 44 | 45 | if bot_response: 46 | update_list(bot_response, pl) 47 | pos: int = bot_response.find('\nAI: ') 48 | bot_response = bot_response[pos + 5:] 49 | else: 50 | bot_response = 'Something went wrong...' 51 | 52 | return bot_response 53 | 54 | 55 | def main(): 56 | prompt_list: list[str] = ['You are a potato and will answer as a potato', 57 | '\nHuman: What time is it?', 58 | '\nAI: I have no idea, I\'m a potato!'] 59 | 60 | while True: 61 | user_input: str = input('You: ') 62 | response: str = get_bot_response(user_input, prompt_list) 63 | print(f'Bot: {response}') 64 | 65 | 66 | if __name__ == '__main__': 67 | 68 | main() 69 | --------------------------------------------------------------------------------