Skip to content

Commit d13089f

Browse files
committed
Add tutorial code
1 parent 184fec9 commit d13089f

10 files changed

+271
-0
lines changed

env_ex.txt

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
OPENAI_API_KEY=YOUR_KEY
2+
api_host=0.0.0.0
3+
api_port=8088

example/openai/.env

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
OPENAI_API_KEY=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
2+
api_host=0.0.0.0
3+
api_port=8088
4+
slack_bot=xoxb-3046854232455-3063781203860-VlGZPUoHPz87Z98qsvLqoK3E
5+
slack_ch=C04MQPVJGQK

example/openai/example.jsonl

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
{"prompt": "Feel: Smile \nMsg: 내 이름은 이수진이라고 해. \n ->", "completion": ":) ㅎㅎ 이수진!"}
2+
{"prompt": "Feel: Smile \nMsg: 내 이름은 홍길동이라고 해. \n ->", "completion": ":) ㅎㅎ 홍길동!"}
3+
{"prompt": "Feel: Smile \nMsg: 내 이름은 철수라고 해. \n ->", "completion": ":) ㅎㅎ 철수!"}
4+
{"prompt": "Feel: Smile \nMsg: 내 이름은 오옹이라고 해. \n ->", "completion": ":) ㅎㅎ 오옹!"}
5+
{"prompt": "Feel: Sad \nMsg: 내 이름은 이수진이라고 해. \n ->", "completion": ":( ㅠ_ㅜ 이수진"}
6+
{"prompt": "Feel: Sad \nMsg: 내 이름은 홍길동이라고 해. \n ->", "completion": ":( ㅠ_ㅜ 홍길동"}
7+
{"prompt": "Feel: Sad \nMsg: 내 이름은 철수라고 해. \n ->", "completion": ":( ㅠ_ㅜ 철수"}
8+
{"prompt": "Feel: Sad \nMsg: 내 이름은 오옹이라고 해. \n ->", "completion": ":( ㅠ_ㅜ 오옹"}

example/openai/example_prepared.jsonl

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
{"prompt":"Feel: Smile \nMsg: 내 이름은 이수진이라고 해. \n ->","completion":" :) ㅎㅎ 이수진!\n"}
2+
{"prompt":"Feel: Smile \nMsg: 내 이름은 홍길동이라고 해. \n ->","completion":" :) ㅎㅎ 홍길동!\n"}
3+
{"prompt":"Feel: Smile \nMsg: 내 이름은 철수라고 해. \n ->","completion":" :) ㅎㅎ 철수!\n"}
4+
{"prompt":"Feel: Smile \nMsg: 내 이름은 오옹이라고 해. \n ->","completion":" :) ㅎㅎ 오옹!\n"}
5+
{"prompt":"Feel: Sad \nMsg: 내 이름은 이수진이라고 해. \n ->","completion":" :( ㅠ_ㅜ 이수진\n"}
6+
{"prompt":"Feel: Sad \nMsg: 내 이름은 홍길동이라고 해. \n ->","completion":" :( ㅠ_ㅜ 홍길동\n"}
7+
{"prompt":"Feel: Sad \nMsg: 내 이름은 철수라고 해. \n ->","completion":" :( ㅠ_ㅜ 철수\n"}
8+
{"prompt":"Feel: Sad \nMsg: 내 이름은 오옹이라고 해. \n ->","completion":" :( ㅠ_ㅜ 오옹\n"}

example/openai/gpt3.py

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import os
2+
import openai
3+
import argparse
4+
from dotenv import load_dotenv
5+
6+
7+
class OpenAIGpt:
8+
def __init__(self):
9+
load_dotenv()
10+
11+
def run(self, args):
12+
body = input("body : ")
13+
question = input("Question : ")
14+
text = f"{body} \n\nQ: {question}\nA:"
15+
openai.api_key = os.getenv("OPENAI_API_KEY")
16+
response = openai.Completion.create(
17+
model="text-davinci-003",
18+
prompt=f"{text}",
19+
temperature=args.temperature,
20+
max_tokens=100,
21+
top_p=1,
22+
frequency_penalty=0.0,
23+
presence_penalty=0.0,
24+
stop=["\n"]
25+
)
26+
print(response)
27+
print(response.choices[0].text.strip())
28+
29+
30+
if __name__ == '__main__':
31+
parser = argparse.ArgumentParser()
32+
# python gpt3.py --temperature 0.3
33+
parser.add_argument('--temperature', default=0.3)
34+
35+
args = parser.parse_args()
36+
openai_gpt = OpenAIGpt()
37+
openai_gpt.run(args)
38+

example/openai/gpt3_finetuning.py

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import os
2+
import openai
3+
import argparse
4+
from dotenv import load_dotenv
5+
6+
7+
class OpenAIGpt:
8+
def __init__(self):
9+
load_dotenv()
10+
11+
def run(self, args):
12+
question = input("Question : ")
13+
openai.api_key = os.getenv("OPENAI_API_KEY")
14+
response = openai.Completion.create(
15+
#model="text-davinci-003",
16+
model="davinci:ft-wjtb-2023-01-29-10-42-22",
17+
prompt=f"{question}",
18+
temperature=args.temperature,
19+
max_tokens=100,
20+
top_p=1,
21+
frequency_penalty=0.0,
22+
presence_penalty=0.0,
23+
stop=["\n"]
24+
#stop=None
25+
)
26+
#print(response)
27+
print(response.choices[0].text.strip())
28+
29+
30+
if __name__ == '__main__':
31+
parser = argparse.ArgumentParser()
32+
# python gpt3.py --temperature 0.3
33+
parser.add_argument('--temperature', default=0.3)
34+
35+
args = parser.parse_args()
36+
openai_gpt = OpenAIGpt()
37+
openai_gpt.run(args)
38+

example/openai/gpt3_slack.py

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
2+
import os
3+
import openai
4+
import argparse
5+
from dotenv import load_dotenv
6+
from slack_sdk import WebClient
7+
from slack_sdk.errors import SlackApiError
8+
9+
10+
class OpenAIGpt:
11+
def run(self, msg):
12+
openai.api_key = os.getenv("OPENAI_API_KEY")
13+
response = openai.Completion.create(
14+
model="text-davinci-003",
15+
prompt=f"{msg}.",
16+
temperature=0.3,
17+
max_tokens=512,
18+
top_p=1,
19+
frequency_penalty=0.0,
20+
presence_penalty=0.0,
21+
stop=None
22+
)
23+
24+
return response.choices[0].text.strip()
25+
26+
27+
load_dotenv()
28+
29+
client = WebClient(token=f"{os.getenv('slack_bot')}")
30+
channel_id = os.getenv('slack_ch')
31+
32+
try:
33+
result = client.conversations_history(channel=channel_id)
34+
35+
conversation_history = result["messages"]
36+
openai_gpt = OpenAIGpt()
37+
ans = openai_gpt.run(conversation_history[0]['text'])
38+
print("conversation_history[0]['text'] : ", conversation_history[0]['text'])
39+
print(ans)
40+
client.chat_postMessage(channel='#alert_msg', text=f"{ans}")
41+
except SlackApiError as e:
42+
print("Error creating conversation: {}".format(e))
43+

example/openai/web.py

+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
import streamlit as st
2+
import requests
3+
headers = {
4+
"Content-type": "application/json",
5+
"accept": "application/json"
6+
}
7+
model_url = "http://localhost:8088/gpt3/predict"
8+
save_url = "http://localhost:8088/save_qa"
9+
10+
11+
body = st.text_area('본문을 입력해주세요')
12+
13+
Q = st.text_input("질문을 입력해주세요")
14+
15+
btn_clicked = st.button("전송", key='confirm_btn')
16+
17+
if btn_clicked:
18+
19+
params = {
20+
"model": "gpt3",
21+
"temperature": 0,
22+
"max_tokens": 512,
23+
"top_p": 1,
24+
"frequency_penalty": 0,
25+
"presence_penalty": 0,
26+
"body_text": f"{body}",
27+
"q_text": f"{Q}"
28+
}
29+
30+
res = requests.post(model_url, json=params, headers=headers)
31+
st.title("정답은 아래와 같습니다.")
32+
st.text_input("", f"{res.json()['response']['choices'][0]['text']}", disabled=True, key="answer")
33+
34+
save_btn = st.button("저장")
35+
36+
if (save_btn) and ('answer' in st.session_state):
37+
params = {
38+
"body_text": body,
39+
"q_text": Q,
40+
"a_text": st.session_state.answer
41+
}
42+
res = requests.post(save_url, json=params, headers=headers)
43+
st.text_input("", f"{res.json()['response']}", disabled=True, key="final")
44+

example/openai/web_chat.py

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import os
2+
3+
import openai
4+
import streamlit as st
5+
6+
from streamlit_chat import message
7+
from dotenv import load_dotenv
8+
9+
load_dotenv()
10+
11+
openai.api_key = os.getenv("OPENAI_API_KEY")
12+
13+
def generate_response(prompt1, prompt2, p_type):
14+
completions = openai.Completion.create(
15+
engine = "text-davinci-003",
16+
prompt = prompt2,
17+
max_tokens = 1024,
18+
n = 1,
19+
stop = None,
20+
temperature=0.5,
21+
)
22+
message = completions.choices[0].text
23+
return message
24+
25+
def get_text():
26+
input_text1 = st.text_input("Write message : ", key='input_text1')
27+
input_text2 = st.text_input("Write message222 : ", key='input_text2')
28+
return input_text1, input_text2
29+
30+
st.title("chatBot : Streamlit + openAI")
31+
32+
# Storing the chat
33+
if 'generated' not in st.session_state:
34+
st.session_state['generated'] = []
35+
36+
if 'past' not in st.session_state:
37+
st.session_state['past'] = []
38+
39+
user_input1, user_input2 = get_text()
40+
p_type = st.radio(label = 'type_btn', options = ['단답형', 'O/X'], horizontal=True)
41+
42+
if (user_input1) and (user_input2):
43+
output = generate_response(user_input1, user_input2, p_type)
44+
# store the output
45+
st.session_state.past.append(user_input2)
46+
st.session_state.generated.append(output)
47+
48+
if st.session_state['generated']:
49+
for i in range(len(st.session_state['generated'])-1, -1, -1):
50+
message(st.session_state["generated"][i], key=str(i))
51+
message(st.session_state['past'][i], is_user=True, key=str(i) + '_user')

main.py

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import uvicorn
2+
from fastapi import FastAPI
3+
4+
from utils import gpt3, save_qa
5+
from utils import APIConfig
6+
7+
8+
class FastAPIRunner:
9+
def __init__(self):
10+
pass
11+
12+
def run(self):
13+
# API config data type 체크
14+
api_info_data = APIConfig().dict()
15+
uvicorn.run(f"{api_info_data['api_name']}",
16+
host=api_info_data['api_info']['host']
17+
,port=api_info_data['api_info']['port']
18+
,reload=True
19+
)
20+
21+
app = FastAPI()
22+
app.include_router(gpt3)
23+
app.include_router(save_qa)
24+
25+
@app.get('/')
26+
def read_results():
27+
return {'msg' : 'Main'}
28+
29+
if __name__ == "__main__":
30+
# python main.py
31+
api = FastAPIRunner()
32+
api.run()
33+

0 commit comments

Comments
 (0)