실습

Cloud 9 에 환경을 만들고 다음 코드를 참고하여 실행해보기

환경 만드는 방법은 여기 참고

2-1. AWS Cloud9 - Hello World API

11/15 기준 최신 버전

pip install openai==1.2.4 streamlit==1.28.2

main.py

from openai import OpenAI
import streamlit as st

client = None
api_key = st.text_input('openai api key', 'your_openai_api_key')
if api_key:
    client = OpenAI(api_key=api_key)

lang_list = ('영어', '중국어', '일본어', '아랍어', '한국어')

st.header('번역기')

col1, col2 = st.columns(2)
result = ''
with col1:
    option = st.selectbox('Lang', lang_list)
    q = st.text_area('From')
    if client and q:
        response = client.chat.completions.create(
          model="gpt-3.5-turbo",
          messages=[
            {"role": "system", "content": f"You are a helpful translator. Translate the text sent by the user into {option}"},
            {"role": "user", "content": q}
          ]
        )

        print(response.choices[0].message.content)
        result = response.choices[0].message.content

with col2:
    st.text_area('To', value=result)

아래는 openai old 버전 입니다 == 0.28.0

main.py

import openai
import streamlit as st

api_key = st.text_input('openai api key', 'your_openai_api_key')
if api_key:
    openai.api_key = api_key

lang_list = ('영어', '중국어', '일본어', '아랍어', '한국어')

st.header('번역기')

col1, col2 = st.columns(2)
result = ''
with col1:
    option = st.selectbox('Lang', lang_list)
    q = st.text_area('From')
    if q:

				# :+:+:+:+: prompt format 을 만들어보세요 :+:+:+:+:
				# option = 영어, 중국어.. 중 하나 
				# q = 입력 문구
        prompt = q # <- 코드를 수정하세요

        response = openai.Completion.create(
            model='text-davinci-003',
            prompt=prompt,
            temperature=0,
            max_tokens=100,
            top_p=1,
        )
        print(response.choices[0].text.strip())
        result = response.choices[0].text.strip()

with col2:
    st.text_area('To', value=result)