AI 故事讲述的力量:利用 OpenAI 构建一个 Streamlit 应用程序
重新开始学习Python,并对ChaatGPT Prompt Engineering着迷,下面是我与ChatGPT、OpenAI API和Streamlit的下一步计划。
一个简单的网络应用程序,利用OpenAI的文本生成能力,根据用户提供的提示生成引人入胜的故事。
- 工具:Python,Streamlit构建用户界面和OpenAI API
import streamlit as st
import json
from openai import OpenAI
# Authenticate with OpenAI API (replace with your key)
open_ai_client = OpenAI()
# Function to call OpenAI API for structured generation
def structured_generator(openai_model, prompt):
"""
Calls the OpenAI API to generate text in a structured format.
Args:
openai_model (str): The name of the OpenAI model to use.
prompt (str): The prompt to provide for text generation.
Returns:
dict: The JSON response from the OpenAI API, containing generated text.
"""
result = open_ai_client.chat.completions.create(
model=openai_model,
messages=[{"role": "user", "content": f"{prompt}, output must be in json the object returned must a json with title and description"}]
)
return result
# ---- UI Layout and Components ----
st.title("StoryBoard: Unleash Your Creativity")
st.write("Craft captivating stories and poems with the power of AI.")
# Input section for topic and content type
col1, col2 = st.columns(2)
with col1:
selected_input_topic = st.selectbox("Choose a Theme:", ["Enchanted Forests", "Magical Creatures", "Faraway Adventures"])
with col2:
selected_input_type = st.selectbox("Choose a Format:", ["Story", "Poem"])
# Button to trigger generation with visual feedback
if st.button("Let the Magic Begin"):
with st.spinner("Weaving Words of Wonder..."):
prompt = f"Generate a 3 to 5 line {selected_input_type} about {selected_input_topic}"
openai_model = "gpt-3.5-turbo" # Replace with your preferred model
result = structured_generator(openai_model, prompt)
# Process and display generated content
data = json.loads(result.choices[0].message.content)
# Display all key-value pairs dynamically
for key, value in data.items():
if isinstance(value, list):
st.subheader(key.upper())
for item in value:
if isinstance(item, dict) and "image" in item: # Check for nested images
st.image(item["image"])
else:
st.write(item)
elif isinstance(value, dict):
st.subheader(key.upper())
for sub_key, sub_value in value.items():
if isinstance(sub_value, list): # Handle lists within nested dictionaries
for item in sub_value:
st.write(item)
else:
st.write(f"**{sub_key.upper()}:** {sub_value}")
else:
st.write(f"**{key.upper()}:** {value}")