PaLM API based Article Generator isn't working

280 Views Asked by At

I have made a Medium Article Generator Using PaLM API, but it isn't working. Have tried debugging it from the last 2 days, but its still not working. I think the error lies in this part of the code. Help me debug it.The part where I think the error lies.[Error Message.](https://i.stack.imgur.com/brDx2.png)

import streamlit as st
import requests
import json

PALM_API_ENDPOINT = "https://api.palm.ai/v1/generate"
PALM_API_KEY = "AIzaSyB5ol5ILDVJ-mmi-VBV5EYUD0918__WGrI"

def generate_medium_article(topic):
    """Generates a Medium article on the given topic using the PaLM API."""

    payload = {
        "prompt": """Write a Medium article on the topic {}.""".format(topic),
        "temperature": 0.7,
        "max_tokens": 2000,
    }

    headers = {
        "Authorization": "Bearer {}".format(PALM_API_KEY)
    }

    response = requests.post(PALM_API_ENDPOINT, json=payload, headers=headers)
    response.raise_for_status()

    article = json.loads(response.content)["generated_text"]

    return article

def generate_hashtags(topic):
  """Generates hashtags for the given topic using the PaLM API."""

  payload = {
    "prompt": """Generate hashtags for the topic {}.""".format(topic),
    "temperature": 0.7,
    "max_tokens": 5,
  }

  headers = {
    "Authorization": "Bearer {}".format(PALM_API_KEY),
    "Accept": "*/*"
  }

  response = requests.post(PALM_API_ENDPOINT, json=payload, headers=headers)
  response.raise_for_status()

  hashtags = json.loads(response.content)["generated_text"].split(",")

  return hashtags

def main():
    """StreamLit app for generating Medium articles and hashtags."""

    st.title("Medium Article Generator and Hashtag Generator")

    topic = st.text_input("Enter a topic:")

    if st.button("Generate Medium article"):
        article = generate_medium_article(topic)
        st.write(article)

    if st.button("Generate hashtags"):
        hashtags = generate_hashtags(topic)
        st.write(hashtags)

if __name__ == "__main__":
    main()

2

There are 2 best solutions below

0
On

You have sevral issues

First your endpoint is wrong.

PALM_API_ENDPOINT = "https://generativelanguage.googleapis.com/v1beta2/models/text-bison-001:generateText"

Second the format of the payload is wrong

payload = {
    'model': 'models/text-bison-001',
    "prompt": {
        "text": 'Generate hashtags for the topic "' + topic + "'"
    },
    "temperature": 1.0,
    "candidateCount": 1}

Third the api key is NOT a bearer token so should not be sent as an authorization header.

headers = {
    "contentType": "'application/json'"
}    

response = requests.post(PALM_API_ENDPOINT + "?key=" + PALM_API_KEY, json=payload, headers=headers)
0
On

You can send the API key using the ?key=AIzaApiKeyGoesHere URL parameter.

But since you're writing in Python, it'd be even better to use the client library directly.