Skip to content

Instantly share code, notes, and snippets.

@nheingit
Last active March 1, 2024 14:10
Show Gist options
  • Save nheingit/3768dc7754ee579aa98b339fe0aa0584 to your computer and use it in GitHub Desktop.
Save nheingit/3768dc7754ee579aa98b339fe0aa0584 to your computer and use it in GitHub Desktop.
Day1 - LSU Final Output
import os
import logging
from telegram import Update
from telegram.ext import ApplicationBuilder, ContextTypes, CommandHandler
from openai import OpenAI
openai = OpenAI(api_key=os.environ['OPENAI_API_KEY'])
tg_bot_token = os.environ['TG_BOT_TOKEN']
messages = [{
"role": "system",
"content": "You are a helpful assistant that answers questions."
}]
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
async def chat(update: Update, context: ContextTypes.DEFAULT_TYPE):
messages.append({"role": "user", "content": update.message.text})
completion = openai.chat.completions.create(model="gpt-3.5-turbo",
messages=messages)
completion_answer = completion.choices[0].message
messages.append(completion_answer)
await context.bot.send_message(chat_id=update.effective_chat.id,
text=completion_answer.content)
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
await context.bot.send_message(chat_id=update.effective_chat.id,
text="I'm a bot, please talk to me!")
if __name__ == '__main__':
application = ApplicationBuilder().token(tg_bot_token).build()
start_handler = CommandHandler('start', start)
chat_handler = CommandHandler('chat', chat)
application.add_handler(start_handler)
application.add_handler(chat_handler)
application.run_polling()
@Jakolo121
Copy link

Jakolo121 commented Dec 1, 2023

Hello Noah!
Thaks for the course, you did a great work!
I found some improvements.
OpenAI updated their API and the chat completion API now needs to be formated openai.chat.completions.create(model="gpt-3.5-turbo", messages=messages)

I also had problems with acccesing completion_answer even tho the syntax is correct, I had to change the syntax to completion['choices'][0].message.content

I hope you find this usefull!

Have a great Day!

@kellenmace
Copy link

I had a similar experience and had to format the completion_answer line like this to get it to work:
completion_answer = completion.choices[0].message.content

@nheingit
Copy link
Author

nheingit commented Feb 2, 2024

Updated with y'alls feedback.

Thank you @Jakolo121 & @kellenmace

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment