Spaces:
Build error
Build error
| import streamlit as st | |
| from openai import OpenAI | |
| import os | |
| from dotenv import load_dotenv | |
| # Load environment variables | |
| load_dotenv() | |
| # Set up OpenAI API key | |
| api_key = os.getenv("OPENAI_API_KEY") # Ensure your OpenAI API key is stored in the .env file | |
| client = OpenAI(api_key=api_key) | |
| # Function to query OpenAI for chat | |
| def chat_with_paragraph(paragraph, question, model="gpt-4o-mini"): | |
| try: | |
| response = client.chat.completions.create( | |
| model=model, | |
| messages=[ | |
| {"role": "system", "content": "You are a helpful assistant. Answer questions based on the provided paragraph in 30 words."}, | |
| {"role": "user", "content": f"Here is the paragraph: {paragraph}\n\nQuestion: {question}"} | |
| ] | |
| ) | |
| # Extract the response | |
| return response.choices[0].message.content.strip() | |
| except Exception as e: | |
| return f"Error: {e}" | |
| # Streamlit app | |
| st.title("Chat with a Paragraph") | |
| # User input for the paragraph | |
| paragraph = st.text_area("Enter a paragraph:", placeholder="Paste a paragraph here...") | |
| # User input for the question | |
| question = st.text_input("Ask a question about the paragraph:") | |
| # Handle user input and display the response | |
| if st.button("Ask"): | |
| if paragraph.strip() and question.strip(): | |
| # Get the response from OpenAI | |
| answer = chat_with_paragraph(paragraph, question) | |
| # Display the response | |
| st.subheader("Answer:") | |
| st.write(answer) | |
| else: | |
| st.warning("Please provide both a paragraph and a question.") | |