[Python] GroqCloud API Issue

Discussão em 'Python' iniciado por Stack, Março 25, 2025.

  1. Stack

    Stack Membro Participativo

    this is my python code

    import streamlit as st import pandas as pd import requests

    ---------- FUNCTION TO FETCH API DATA ----------


    def fetch_data_from_api(api_url): """Fetch data from an API and return a DataFrame if successful.""" try: response = requests.get(api_url) response.raise_for_status() # Raise an error for bad status codes

    content_type = response.headers.get("Content-Type", "").lower()

    if "application/json" in content_type:
    return pd.DataFrame(response.json()) # Convert JSON to DataFrame
    elif "text/csv" in content_type:
    from io import StringIO
    return pd.read_csv(StringIO(response.text)) # Convert CSV to DataFrame
    else:
    st.error("Unsupported API response format. Please provide JSON or CSV data.")
    return None
    except requests.exceptions.RequestException as e:
    st.error(f"⚠️ API Request Failed: {e}")
    return None

    ---------- FUNCTION TO GENERATE ANSWER ----------


    def generate_answer(df, question): """Generate an AI-powered answer based on the DataFrame and user query.""" df_string = df.to_csv(index=False)

    prompt = f"""
    You are an expert data analyst. Analyze the following data and answer the user's question.

    DATA:
    {df_string}

    QUESTION:
    {question}
    """

    # Use the API key from Streamlit secrets
    GROQ_API_KEY = st.secrets["GROQ_API_KEY"]

    headers = {"Authorization": f"Bearer {GROQ_API_KEY}", "Content-Type": "application/json"}
    payload = {
    "model": "mixtral-8x7b-instruct",
    "messages": [
    {"role": "system", "content": "You are a helpful data analyst."},
    {"role": "user", "content": prompt}
    ],
    "temperature": 0.2
    }

    response = requests.post("https://api.groq.com/v1/chat/completions", headers=headers, json=payload)

    if response.status_code == 200:
    return response.json()["choices"][0]["message"]["content"]
    else:
    return f"⚠️ API Error: {response.text}"

    ---------- STREAMLIT UI ----------


    st.title(" Data Q&A with AI (Powered by Groq)")

    File upload option


    uploaded_file = st.file_uploader(" Upload a file (CSV, JSON, XLSX):", type=["csv", "json", "xlsx"])

    API input option


    api_url = st.text_input(" Enter an API endpoint to fetch data:")

    df = None # Initialize DataFrame

    Process file upload


    if uploaded_file: st.write(f"File type detected: {uploaded_file.type}") try: if uploaded_file.type == "text/csv": df = pd.read_csv(uploaded_file) elif uploaded_file.type == "application/json": df = pd.read_json(uploaded_file) elif uploaded_file.type == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": df = pd.read_excel(uploaded_file) else: st.error("Unsupported file type!") except Exception as e: st.error(f"Error loading file: {e}")

    Process API data fetch


    elif api_url: with st.spinner("Fetching data from API..."): df = fetch_data_from_api(api_url)

    Display data and process user question


    if df is not None: st.subheader(" Data Preview") st.write(df)

    question = st.text_input("Ask a question about your data:")

    if question:
    with st.spinner("AI is analyzing the data"):
    answer = generate_answer(df, question)
    st.success("✅ Answer Ready!")
    st.subheader(" AI's Answer:")
    st.write(answer)


    st.markdown("---") st.markdown("Made with using Groq (Mixtral-8x7B) and Streamlit")

    But The Error is when i ask any question:

    ⚠️ API Error: -[if lt IE 7]> <![endif]--> api.groq.com | 520: Web server is returning an unknown error Web server is returning an unknown error Error code 520 Visit cloudflare.com for more information. 2025-03-25 05:13:23 UTC <div class="relative mb-10 md:m-0"


    Working Karachi Cloudflare Working

    Continue reading...

Compartilhe esta Página