import streamlit as st import openai from langchain.docstore.document import Document from langchain.text_splitter import CharacterTextSplitter from langchain.chains.summarize import load_summarize_chain from langchain.llms import OpenAI def generate_response(txt, openai_api_key): try: # Set up OpenAI API key openai.api_key = openai_api_key # Split text into chunks text_splitter = CharacterTextSplitter() texts = text_splitter.split_text(txt) # Create documents from the text chunks docs = [Document(page_content=t) for t in texts] # Instantiate the OpenAI LLM model llm = OpenAI(temperature=0, openai_api_key=openai_api_key) # Create the summarization chain and summarize the documents chain = load_summarize_chain(llm=llm, chain_type='map_reduce') return chain.run(docs) except Exception as e: st.error(f"An error occurred during summarization: {str(e)}") return None # Page title and layout st.set_page_config(page_title='🦜🔗 Text Summarization App') st.title('🦜🔗 Text Summarization App') # Text input area for user to input text txt_input = st.text_area('Enter your text', '', height=200) # Form to accept the user's text input for summarization response = None with st.form('summarize_form', clear_on_submit=True): openai_api_key = st.text_input('OpenAI API Key', type='password', disabled=not txt_input) submitted = st.form_submit_button('Submit') if submitted and openai_api_key.startswith('sk-'): with st.spinner('Summarizing...'): response = generate_response(txt_input, openai_api_key) # Display the response if available if response: st.info(response) # Instructions for getting an OpenAI API key st.subheader("Get an OpenAI API key") st.write("You can get your own OpenAI API key by following the instructions:") st.write(""" 1. Go to [OpenAI API Keys](https://platform.openai.com/account/api-keys). 2. Click on the `+ Create new secret key` button. 3. Enter an identifier name (optional) and click on the `Create secret key` button. """)