shuhayas commited on
Commit
a06e639
·
verified ·
1 Parent(s): 0aa2e57

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +75 -0
app.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # main.py
2
+
3
+ import streamlit as st
4
+ import aiohttp
5
+ import asyncio
6
+ import json
7
+
8
+ # Function to asynchronously generate text using the OpenAI API
9
+ async def generate_text(api_key, prompt, model, temperature, max_tokens, top_p, frequency_penalty, presence_penalty):
10
+ headers = {
11
+ "Content-Type": "application/json",
12
+ "Authorization": f"Bearer {api_key}"
13
+ }
14
+ data = {
15
+ "model": model,
16
+ "messages": [{"role": "user", "content": prompt}],
17
+ "temperature": temperature,
18
+ "max_tokens": max_tokens,
19
+ "top_p": top_p,
20
+ "frequency_penalty": frequency_penalty,
21
+ "presence_penalty": presence_penalty,
22
+ "stream": True
23
+ }
24
+
25
+ async with aiohttp.ClientSession() as session:
26
+ async with session.post("https://api.openai.com/v1/chat/completions", headers=headers, json=data) as response:
27
+ if response.status == 200:
28
+ result_area = st.empty()
29
+ generated_text = ""
30
+ async for chunk in response.content.iter_chunked(1024):
31
+ chunk = chunk.decode('utf-8')
32
+ lines = chunk.split('\n')
33
+ for line in lines:
34
+ if line.strip() == "":
35
+ continue
36
+ if line.startswith("data:"):
37
+ try:
38
+ data = json.loads(line[5:])
39
+ if data["choices"][0]["finish_reason"] is None:
40
+ delta = data["choices"][0]["delta"].get("content", "")
41
+ generated_text += delta
42
+ result_area.markdown(generated_text)
43
+ else:
44
+ break
45
+ except json.JSONDecodeError as e:
46
+ print(f"JSONDecodeError: {e}")
47
+ continue
48
+ return generated_text
49
+ else:
50
+ raise Exception(f"API request failed with status code {response.status}: {await response.text()}")
51
+
52
+ # Main function to setup Streamlit UI and handle user inputs
53
+ def main():
54
+ st.title("GPT-4 Text Generation App")
55
+ api_key = st.text_input("OpenAI API Key", type="password")
56
+ system_prompt = st.text_area("System Prompt", value="You are a helpful assistant.")
57
+ user_prompts = st.text_area("User Prompts (one per line)", value="What is the capital of France?\nExplain the concept of machine learning.").split("\n")
58
+ assistant_prompt = st.text_area("Assistant Prompt", value="Here is the information you requested:")
59
+
60
+ model = "gpt-4-turbo-preview"
61
+ temperature = st.slider("Temperature", 0.0, 1.0, 1.0, 0.1)
62
+ max_tokens = st.number_input("Max Tokens", 1, 4000, 256)
63
+ top_p = st.slider("Top P", 0.0, 1.0, 1.0, 0.1)
64
+ frequency_penalty = st.slider("Frequency Penalty", 0.0, 2.0, 0.0, 0.1)
65
+ presence_penalty = st.slider("Presence Penalty", 0.0, 2.0, 0.0, 0.1)
66
+
67
+ if st.button("Generate"):
68
+ if not api_key:
69
+ st.error("Please enter your OpenAI API key.")
70
+ else:
71
+ with st.spinner("Generating text..."):
72
+ asyncio.run(generate_text(api_key, f"{system_prompt}\nUser: {user_prompts[0]}\nAssistant: {assistant_prompt}", model, temperature, max_tokens, top_p, frequency_penalty, presence_penalty))
73
+
74
+ if __name__ == "__main__":
75
+ main()