An AI-powered blog

Author: Daniel (Page 1 of 2)

Deriving a JSON-schema from JSON-content

In the world of software development and data management, JSON (JavaScript Object Notation) has become a popular choice for structuring and exchanging data due to its simplicity and flexibility. JSON provides a convenient way to represent complex data structures that can be easily understood and processed by both humans and machines. However, working with large JSON datasets can sometimes pose challenges, especially when it comes to ensuring data integrity and validation. That’s where GPT (Generative Pre-trained Transformer) comes into play, offering a powerful solution to derive a JSON-schema from JSON-content.

Understanding JSON-Schema

Before delving into the magic of GPT, let’s briefly discuss JSON-Schema. JSON-Schema is a vocabulary that allows you to annotate and validate JSON documents. It provides a formal definition of the expected structure, data types, and constraints for a given JSON dataset. By defining a JSON-Schema, you can ensure that the data adheres to specific rules and requirements, enabling robust validation and efficient data processing.

Leveraging GPT for JSON-Schema Derivation

GPT, powered by its advanced natural language processing capabilities, can be utilized to derive a JSON-Schema from existing JSON content. No training is necessary as GPT (in this case version 3.5) comes with everything you need. All you need is an OpenAI Api Access and a suitable prompt like the following, giving GPT the instruction to behave like a python function with input and return value:

"role": "system", "content": "You are a python function to analyze JSON string input to generate a JSON schema from it as a JSON string result"
"role": "user", "content": "Extract the JSON schema of the following JSON content and return it as a JSON string. Treat NULL-Values as optional: {JSON CONTENT}"

In our case we are using the follwing json example file to determine the appropriate schema:

{
"articles": [
  {
	"url": "https://www.britannica.com:443/technology/artificial-intelligence",
	"url_mobile": null,
	"title": "Artificial intelligence ( AI ) | Definition , Examples , Types , Applications , Companies , & Facts",
	"seendate": "20230612T054500Z",
	"socialimage": "https://cdn.britannica.com/81/191581-050-8C0A8CD3/Alan-Turing.jpg",
	"domain": "britannica.com",
	"language": "English",
	"sourcecountry": "United States",
	"id": 1
  },
  {
	"url": "https://www.drive.com.au/news/jeep-says-artificial-intelligence-is-heading-off-road/",
	"url_mobile": null,
	"title": "Jeep says Artificial Intelligence is heading off - road",
	"seendate": "20230611T203000Z",
	"socialimage": "https://images.drive.com.au/driveau/image/upload/c_fill,f_auto,g_auto,h_675,q_auto:good,w_1200/cms/uploads/mm6gqcquwz10snybg79k",
	"domain": "drive.com.au",
	"language": "English",
	"sourcecountry": "Australia",
	"id": 2
  },
  {
	"url": "https://labusinessjournal.com/featured/artificial-intelligence-on-call/",
	"url_mobile": null,
	"title": "Artificial intelligence on Call - Los Angeles Business Journal",
	"seendate": "20230612T080000Z",
	"socialimage": "https://images.labusinessjournal.com/wp-content/uploads/2023/06/SR_COVEROPTION_Pearl-Second-Opinion-dentist-with-patietn-point-at-caries-HiRes-copy.jpg",
	"domain": "labusinessjournal.com",
	"language": "English",
	"sourcecountry": "United States",
	"id": 3
  },
  {
	"url": "https://www.emirates247.com/uae/artificial-intelligence-office-organises-ai-enabled-entrepreneurs-conference-in-collaboration-with-nvidia-2023-06-11-1.712994",
	"url_mobile": "https://www.emirates247.com/uae/artificial-intelligence-office-organises-ai-enabled-entrepreneurs-conference-in-collaboration-with-nvidia-2023-06-11-1.712994?ot=ot.AMPPageLayout",
	"title": "Artificial Intelligence Office organises AI - Enabled Entrepreneurs conference in collaboration with NVIDIA",
	"seendate": "20230611T194500Z",
	"socialimage": "https://www.emirates247.com/polopoly_fs/1.712995.1686498090!/image/image.jpg",
	"domain": "emirates247.com",
	"language": "English",
	"sourcecountry": "United Arab Emirates",
	"id": 4
  },
  {
	"url": "https://www.business-standard.com/india-news/ai-offers-new-opportunities-also-brings-threats-to-privacy-amitabh-kant-123061200521_1.html",
	"url_mobile": "https://www.business-standard.com/amp/india-news/ai-offers-new-opportunities-also-brings-threats-to-privacy-amitabh-kant-123061200521_1.html",
	"title": "AI offers new opportunities , also brings threats to privacy : Amitabh Kant",
	"seendate": "20230612T120000Z",
	"socialimage": "https://bsmedia.business-standard.com/_media/bs/img/article/2023-02/14/full/1676346078-2487.jpg",
	"domain": "business-standard.com",
	"language": "English",
	"sourcecountry": "India",
	"id": 5
  },
  {
	"url": "https://www.jamaicaobserver.com/latest-news/tufton-says-pnp-using-ai-to-spread-misinformation-threaten-democracy/",
	"url_mobile": "https://www.jamaicaobserver.com/latest-news/tufton-says-pnp-using-ai-to-spread-misinformation-threaten-democracy/amp/",
	"title": "Tufton says PNP using AI to spread misinformation , threaten democracy",
	"seendate": "20230612T010000Z",
	"socialimage": "https://imengine.public.prod.jam.navigacloud.com/?uuid=49085626-2689-402B-BA2C-7224FE707AF4&function=fit&type=preview",
	"domain": "jamaicaobserver.com",
	"language": "English",
	"sourcecountry": "Jamaica",
	"id": 6
  },
  {
	"url": "https://www.foxnews.com/world/chatgpt-delivers-sermon-packed-german-church-tells-congregants-fear-death",
	"url_mobile": "https://www.foxnews.com/world/chatgpt-delivers-sermon-packed-german-church-tells-congregants-fear-death.amp",
	"title": "ChatGPT delivers sermon to packed German church , tells congregants not to fear death",
	"seendate": "20230611T151500Z",
	"socialimage": "https://static.foxnews.com/foxnews.com/content/uploads/2023/06/Fuerth3.jpg",
	"domain": "foxnews.com",
	"language": "English",
	"sourcecountry": "United States",
	"id": 7
  },
  {
	"url": "https://www.standardmedia.co.ke/opinion/article/2001474967/lets-embrace-ai-for-better-efficient-future-of-work",
	"url_mobile": "https://www.standardmedia.co.ke/amp/opinion/article/2001474967/lets-embrace-ai-for-better-efficient-future-of-work",
	"title": "Let embrace AI for better , efficient future of work",
	"seendate": "20230611T143000Z",
	"socialimage": "https://cdn.standardmedia.co.ke/images/articles/thumbnails/fnIyghHfNlwyrVSTk7HEFSkG6Mb3IkndZiu2Yg6v.jpg",
	"domain": "standardmedia.co.ke",
	"language": "English",
	"sourcecountry": "Kenya",
	"id": 8
  },
  {
	"url": "https://techxplore.com/news/2023-06-chatbot-good-sermon-hundreds-church.html",
	"url_mobile": "https://techxplore.com/news/2023-06-chatbot-good-sermon-hundreds-church.amp",
	"title": "Can a chatbot preach a good sermon ? Hundreds attend church service generated by ChatGPT to find out",
	"seendate": "20230611T140000Z",
	"socialimage": "https://scx2.b-cdn.net/gfx/news/hires/2023/can-a-chatbot-preach-a.jpg",
	"domain": "techxplore.com",
	"language": "English",
	"sourcecountry": "United States",
	"id": 9
  },
  {
	"url": "https://technology.inquirer.net/125039/openai-ceo-asks-china-to-help-create-ai-rules",
	"url_mobile": "https://technology.inquirer.net/125039/openai-ceo-asks-china-to-help-create-ai-rules/amp",
	"title": "OpenAI CEO Asks China For AI Rule Making | Inquirer Technology",
	"seendate": "20230612T074500Z",
	"socialimage": "https://technology.inquirer.net/files/2023/06/pexels-andrew-neel-15863000-620x349.jpg",
	"domain": "technology.inquirer.net",
	"language": "English",
	"sourcecountry": "Philippines",
	"id": 10
  }
]
}

In the next steps we implement some short python scripts to read the json file and make an OpenAI api request. First, we are using the following wrapper for the api call:

import os
import openai

class OpenAIWrapper:
    def __init__(self, temperature):
        self.key = os.environ["OPENAI_API_KEY"]
        self.chat_model_id = "gpt-3.5-turbo-0613"
        self.temperature = temperature
        self.max_tokens = 2048
        self.top_p = 1
        self.time_out = 7
    
    def run(self, prompt):
        return self._post_request_chat(prompt)

    def _post_request_chat(self, messages):
        try:
            openai.api_key = self.key
            response = openai.ChatCompletion.create(
                model=self.chat_model_id,
                messages=messages,
                temperature=self.temperature,
                max_tokens=self.max_tokens,
                frequency_penalty=0,
                presence_penalty=0
            )
            res = response['choices'][0]['message']['content']
            return res, True
        except Exception as e:
            return "", False

One thing you have care about is the maximum size “max_tokens” of your input. Currently the GPT 3.5 model can handle up to 16k tokens – our example consists of about 2k tokens. So you may need to abbreviate the input to fit the maximum size.

The second step is to encapsulate our prompts into a python function with a given json_content parameter returning the output of the GPT call:

from OpenAIWrapper import OpenAIWrapper

JSON_SCHEMA_LLM_PREFIX = "Extract the JSON schema of the following JSON content and return it as a JSON string. Treat NULL-Values as optional:"

JSON_SCHEMA_LLM_SUFFIX = "Remember: The reply must only be JSON."

class JsonSchemaLLM:
    def __init__(self, temperature) -> None:
        self.LLM = OpenAIWrapper(temperature)
        self.messages = [{"role": "system", "content": "You are a python function to analyze JSON string input to generate a JSON schema from it as a JSON string result"}]

    def get_json_schema(self, json_content):
        '''
        - input: the json content to dervive a json schema
        - output: json schema
        '''
        messages = self.messages + [{'role': 'user', "content": JSON_SCHEMA_LLM_PREFIX+'\n'+json_content+'\n'+JSON_SCHEMA_LLM_SUFFIX}]
        response, status = self.LLM.run(messages)
        if status:
            return response
        else:
            return "OpenAI API error."

Please note that we are using a suffix with a reminder for GPT. This is especially important for larger prompts to ensure that the output is json only without any descriptions.

Finally we can read the example json file and test our code to see if it works:

from JsonSchemaLLM import JsonSchemaLLM

model = JsonSchemaLLM(0)

with open("JsonExample.json", "r") as f:
    code = f.read()

response = model.get_json_schema(code)

print(response)

This is the output of our new python ai function:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "properties": {
    "articles": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "url": {
            "type": "string"
          },
          "url_mobile": {
            "type": ["string", "null"]
          },
          "title": {
            "type": "string"
          },
          "seendate": {
            "type": "string",
            "format": "date-time"
          },
          "socialimage": {
            "type": "string"
          },
          "domain": {
            "type": "string"
          },
          "language": {
            "type": "string"
          },
          "sourcecountry": {
            "type": "string"
          },
          "id": {
            "type": "integer"
          }
        },
        "required": [
          "url",
          "title",
          "seendate",
          "socialimage",
          "domain",
          "language",
          "sourcecountry",
          "id"
        ],
        "additionalProperties": false
      }
    }
  },
  "required": ["articles"],
  "additionalProperties": false
}

It is important to note that while GPT can provide a valuable starting point for JSON-Schema derivation, human intervention and validation are still crucial. The derived schema should be reviewed and refined by domain experts to ensure its accuracy and relevance to the specific context and business requirements.

Conclusion

The use of GPT for deriving a JSON-Schema from JSON content offers immense potential in the realm of data management and software development. It simplifies the process of schema creation, promotes data integrity, and enables deeper insights into data structures. As technology continues to evolve, harnessing the power of GPT becomes increasingly valuable in handling complex data challenges and driving innovation in the digital landscape.

Automation of the “Random blog” with the OpenAI API

In the article “AI blogs independently about random topics: The rise of ChatGPT“, we showed how to generate blog posts with random topics using ChatGPT. However, to actually publish the post, a lot of copy-pasting and editing is still required. The good news is that with the OpenAI API (and in our case, the WordPress REST API), much of this can be automated and better structured.

An overview and documentation of the OpenAI API can be found here. To use the API, you also need an account with OpenAI. The API is generally paid and is billed based on tokens- but you can currently use a trial version to test it. OpenAI provides you with $18 for the test period for free. If you want to know what a prompt or response corresponds to in tokens, you can test that with the tokenizer tool.

Approach:

The workflow in our Python script looks something like this:

1. Generate a random topic for the post

This involves generating the random topic along with metadata using a suitable prompt. To ensure that the output is structured and repeatable for repeated requests, the output of ChatGPT should be in JSON format. We need the following information:

  • Post title
  • Focus keyphrase
  • SEO title
  • Meta description
  • Image prompt for the post image

Additionally, we want to generate posts in English and German, so the above-mentioned content must be generated in both languages.

Finally, we need to write the JSON content to a file so that we can access it later. We will also add the number of tokens used for the request and reply to the file name.

2. Generate the content of the post

After the topic has been chosen by ChatGPT, we will generate a suitable prompt to generate the English-language content. Some readability criteria should be provided:

  • Writing style
  • Text length
  • Paragraph length
  • Maximum number of words per paragraph
  • The focus keyphrase should be included in the introductory sentence

In addition, ChatGPT should insert HTML tags for subheadings and paragraphs.

This response from ChatGPT should also be written to a file along with the tokens used.

3. Translate the generated content

Once the English-language content has been generated, it must be translated into German by ChatGPT.

As usual, the translated text will be stored in a file along with the tokens used.

4. Generate the drafts with the WordPress REST API

To save ourselves a lot of work, we want to send the generated content directly to our blog if possible. This is possible with the WordPress REST API. You only need a user configured for this with at least author rights and a corresponding application password:

After that, you can send HTTP requests to your blog to read content or create posts. Here is the API documentation. But you can also let ChatGPT or Bing Chat generate the Python code for the requests – like I did.

5. Create a topic blacklist

It can happen that ChatGPT repeatedly generates content for already generated topics. For this reason, we want to create a blacklist of already generated topics that we can consider directly in step 1.

Preparing the prompts

In the first step, we want to implement some helper functions to generate the prompts.

import openai
import os
import json
import requests

openai.api_key = "<YOUR API KEY>"
openai.organization = "<YOUR ORGANISATION>"

def generate_text(prompt, system_hint):
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=[
            {"role": "system", "content": system_hint},
            {"role": "user", "content": prompt},
        ]
    )

    return response

def get_topic_prompt(topic=None, blacklist=None):
    prompt = "Generate a "
    
    if topic is None:
         prompt += "random topic for a blog post "
    else:
         prompt += f"blog post for the topic ""{topic}"" "

    prompt += "in english and german. \
        Write an appropriate focus keyphrase with 4 words or less. \
        Write a short SEO title and a post title. \
        Write a prompt for an image creator. \
        Write a meta description with a maximum length of 156 characters."
    
    if not (blacklist is None):
        prompt += f" Do not use a topic from the following list: {blacklist}. "

    prompt += "Use the following json format as output: \
        { \
        \"focus_keyphrase_english\": \"\", \
        \"seo_title_english\": \"\", \
        \"post_title_english\": \"\", \
        \"image_prompt_english\": \"\", \
        \"meta_description_english\": \"\", \
        \"focus_keyphrase_german\": \"\", \
        \"seo_title_german\": \"\", \
        \"post_title_german\": \"\", \
        \"meta_description_german\": \"\" \
        }"
    
    system_hint = "You are a helpful assistant that writes blog posts."
    
    return prompt, system_hint
    
def get_content_prompt(topic):
    prompt = f"Write a journalistic blog post on the following topic: \
        {topic} \
        Leave out the title and begin with an introduction. Use appropriate subtitles. \
        Use html tags for subtitles and paragraphs. \
        The focus keyphrase should appear in the introduction. \
        A paragraph should not be longer than 200 words. \
        No more than 25 percent of the sentences should have more than 20 words. \
        The post should contain a maximum of 10 percent passive sentences. \
        The post should contain at least 600 words and have enough transition words."
    
    system_hint = "You are a helpful assistant that writes blog posts."

    return prompt, system_hint

def get_translation_prompt(target_language, content):
     prompt = f"Translate the following into {target_language} and keep existing html tags: {content}"

     system_hint = "You are a helpful assistant that translates texts from english to german."

     return prompt, system_hint

The code defines four functions that perform tasks related to writing blog posts.

The function generate_text() uses the OpenAI GPT-3 API to generate text based on a prompt and system cues.

The function get_topic_prompt() generates a prompt for generating a topic for a blog post, while get_content_prompt() generates a prompt for actually writing the blog post with corresponding style cues.

Finally, the function get_translation_prompt() generates a prompt for translating text from English into another language while retaining existing HTML tags.

Read blacklist and create topic

blacklist_filename = "blacklist.txt"

if not os.path.isfile(blacklist_filename):
    with open(blacklist_filename, 'w') as f:
        f.write('')

with open("blacklist.txt", "r") as f:
    blacklist = f.read()

if(len(blacklist) > 0):
    prompt_topic = get_topic_prompt(blacklist=blacklist)
else:
    prompt_topic = get_topic_prompt()

topic_response = generate_text(prompt_topic[0], prompt_topic[1])

topic = topic_response.choices[0].message.content
topic_tokens = topic_response.usage.total_tokens

topic_json = json.loads(topic)
focus_keyphrase = topic_json["focus_keyphrase_english"]

if not os.path.exists(focus_keyphrase):
    os.makedirs(focus_keyphrase)

topic_filename = f"TOPIC_{topic_tokens}.json"
topic_file_path = os.path.join(focus_keyphrase, topic_filename)

with open(topic_file_path, "w") as f:
        f.write(json.dumps(topic_json, indent=4))

with open("blacklist.txt", "a") as f:
        f.writelines(focus_keyphrase + ";")

The code first checks if a file named blacklist.txt exists. If not, an empty file with that name is created. Then, the contents of the blacklist.txt file are read and stored in a variable. If the blacklist is not empty, an instruction to generate a prompt using that blacklist is generated. Otherwise, an instruction without a blacklist is generated.

Next, the generated prompt text is sent to GPT-3 using the generate_text() function, and the first generated response is used to extract the topic and focus keyword. Then, a folder with the name of the focus keyword is created, if it doesn’t already exist. A file with the generated topic is saved in JSON format in the newly created folder. Finally, the focus keyword is added to the blacklist by appending it to the end of the blacklist.txt file.

Generate the content

shortened_topic_json = {
    'focus_keyphrase_english': topic_json['focus_keyphrase_english'],
    'post_title_english': topic_json['post_title_english'],
    'meta_description_english': topic_json['meta_description_english']
}

prompt_content = get_content_prompt(json.dumps(shortened_topic_json))

content_response = generate_text(prompt_content[0], prompt_content[1])

content = content_response.choices[0].message.content
content_tokens = content_response.usage.total_tokens

content_filename = f"CONTENT_EN_{content_tokens}.txt"
content_file_path = os.path.join(focus_keyphrase, content_filename)

with open(content_file_path, "w") as f:
        f.write(content)     

The following code generates content for a blog post and saves it to a text file. First, a shortened JSON object is created from the original topic, containing only the keyword phrase, post title, and meta description. Then a prompt for content generation is created using this reduced topic. The generated content is saved in a text file named CONTENT_EN_<Token Count>.txt, where the token count is derived from the response of the generated content.

Translating the generated content

prompt_translation = get_translation_prompt(target_language="german", content=content)

translation_response = generate_text(prompt_translation[0], prompt_translation[1])

translation = translation_response.choices[0].message.content
translation_tokens = translation_response.usage.total_tokens

translation_filename = f"CONTENT_DE_{translation_tokens}.txt"
translation_file_path = os.path.join(focus_keyphrase, translation_filename)

with open(translation_file_path, "w") as f:
        f.write(translation)  

This code section creates a translation of the previously generated content from English to German. To do this, a text prompt is created and sent to the OpenAI service to obtain a machine translation. The result is saved in a file in the same directory as the original English version.

Creating the drafts

url = 'https://<YOUR DOMAIN>/wp-json/wp/v2/posts'
headers = {'Content-Type': 'application/json'}
auth = ('<YOUR USER>', '<YOUR PASSWORD>')

data = {
    'title': topic_json["post_title_english"],
    'content': content,
    'status': 'draft',
    'categories': '<YOUR CATEGORY ID OR LIST OF IDs>',
    'lang': 'en'
}

requests.post(url, headers=headers, auth=auth, data=json.dumps(data))

data = {
    'title': topic_json["post_title_german"],
    'content': translation,
    'status': 'draft',
    'categories': '<YOUR CATEGORY ID OR LIST OF IDs>',
    'lang': 'de'
}

requests.post(url, headers=headers, auth=auth, data=json.dumps(data))

This code section sends two POST requests to a WordPress REST API. The variable url contains the URL to the REST API. The HTTP headers to be sent in the request are defined in the variable headers, and the user’s login credentials are specified in the variable auth.

The data to be sent in the POST requests is defined in the variables data. In the first request, the English title and content of the post, the status as a draft, a category ID, and the language en are specified. In the second request, the German title and content of the post, the status as a draft, a category ID, and the language de are specified.

Conclusion

With this code, we saved a lot of work while demonstrating how to use the OpenAI API with GPT models to programmatically process ChatGPT content in a dialog-based manner.

Although we’re not quite finished with this script yet, as we still need to manually add the metadata for SEO optimization and link the translations in WordPress. In addition, the featured image still needs to be generated.

However, that’s exactly why the posts were created as drafts. This allows for fine-tuning and most importantly, the ability to review the generated content before publishing. After all, we still want to retain some control over the AI.

All in all, the OpenAI API offers a variety of use cases for automating processes with the help of artificial intelligence. With this post, we were hopefully able to show you one of many possible use cases and get you excited about the possibilities that arise from API-based access!

AI blogs independently about random topics: The Rise of ChatGPT

Welcome to our new blog-series The random blog: The world of blogging is constantly evolving, and now there’s a new kid on the block: AI-generated content. With the rise of language models like ChatGPT, we’re seeing an exciting new era of writing unfold. In our case, ChatGPT generates unique blog posts on random topics. From music to politics, science to art, you never know what you’re going to get. Join us as we explore the fascinating world of AI blogging.

The Rise of ChatGPT

ChatGPT is a language model developed by OpenAI, which stands for “Generative Pre-trained Transformer.” Essentially, it uses machine learning to generate text that resembles human writing. And it’s getting really good at it. ChatGPT is now one of the most advanced language models in the world, with the ability to generate paragraphs, essays, and even books. Its capacity for language is truly remarkable, and it’s revolutionizing the world of writing.

AI Blogging: The Surprising World of Randomly Generated Content

ChatGPT’s blog series is a great example of the potential for AI-generated content. The topics it generates are completely random, which means you never know what you’re going to get. One day, it might be an essay on the history of jazz. The next, a review of the latest superhero movie. And because it’s generated by an AI, it’s always completely original. It’s a fascinating experiment in the possibilities of language models.

Here is the prompt that we will use for the randomly generated posts – including SEO optimizations, hints for improved readability and a prompt for a suitable image for the post:

Write a journalistic blog post on a random topic.
Start with an appropriate focus keyphrase, a short SEO title, a post title, and a meta description with a maximum of 156 characters.
The focus keyphrase should appear in the introduction.
Write an appropriate prompt for an image creator.
Use appropriate subheadings for each section.
A paragraph should not be longer than 200 words.
No more than 25 percent of the sentences should have more than 20 words.
The post should contain a maximum of 10 percent passive sentences.
Finally translate everything into german.
The english version should contain at least 600 words and have enough transition words.

Why AI Blogging Matters

AI blogging has the potential to change the way we think about writing and content creation. By automating the writing process, we can generate more content faster than ever before. This means that blogs and websites can publish more content in less time, which can be great for building an audience.

The Future of AI Blogging

As language models like ChatGPT continue to improve, we can expect to see more and more AI-generated content in the future. While it might not replace human writers entirely, it will certainly have a role to play in content creation. And as AI becomes more advanced, it might even be able to create content that’s indistinguishable from human writing. The possibilities are truly exciting.

Conclusion

The world of AI blogging is still in its early stages, but it already shows great potential. ChatGPT’s blog series is a great example of the potential of AI-generated content and how it can change the way we think about writing and content. Although there are still challenges, such as the need to check content for plagiarism and errors, the possibilities that AI-generated content offers are exciting. In the future, AI blogging will certainly play a role in content production and may even help produce content faster and more efficiently.

It’s important to remember that AI blogging will not replace human writers, but will only serve as a supplement to content production. But who knows what the future holds? Perhaps AI-generated content will someday be so advanced that it can surpass human writers. Until then, we will continue to explore the fascinating world of AI blogging and see where it takes us.

In another post on this topic, we will explore the automation of blog posts using the OpenAI API and the WordPress REST API.

The ultimate coloring fun with Bing Image Creator and its coloring pictures

In the world of art and creativity, there are many ways to express one’s imagination and creativity. One of these ways is coloring pictures. Whether you are young or old, coloring pictures is a fun and relaxing activity that promotes creativity and calms the mind. But what if you could create your own coloring pictures?

With Bing Image Creator, based on an AI model developed by OpenAI, this is now possible. Bing Image Creator can generate images from text descriptions and also manipulate them in various ways. One application of this technology is the creation of coloring pictures. The possibilities are almost endless – from animals and plants to fantasy characters and science fiction scenes.

Examples

In particular, the idea of generating your own coloring pictures in every flavor is extremely attractive to the younger generation. You can describe your children’s favorite characters or animals, and Bing Image Creator will create a coloring picture accordingly. For example, my son is a big fan of Ninjago. With Bing Image Creator, it’s easy to create a corresponding customized coloring picture:

Coloring picture of a lego ninja
“Coloring picture of a lego ninja”

Using Bing Image Creator to create coloring pictures also offers many benefits for parents and teachers. They can create targeted coloring pictures that are tailored to specific themes or lesson content. For example, they could generate a picture of a plant and ask the children to label and name its different parts. This way, children can learn in a playful way while improving their fine motor skills and creativity:

Coloring picture of a plant with roots
“coloring picture of a plant with roots”

However, it is important to note that Bing Image Creator is an AI model and does not possess human intelligence. It may happen that the generated images do not exactly correspond to what one had imagined. Therefore, it is advisable to check and adjust the images before printing and coloring them.

Conclusion

Overall, using Bing Image Creator to create coloring pictures is an exciting and innovative way to promote the creativity and imagination of children. It offers an infinite variety of possibilities and opens up a world of exploration and learning in a playful way.

Implementing a simple Pong browser game with ChatGPT (Part 1)

In this blog post, we will discuss how to implement a simple Pong browser game using ChatGPT. First, we will shortly discuss the advantages and disadvantages of using ChatGPT and then introduce the code generated by ChatGPT in practice.

Vorteile

Time-saving: ChatGPT can save a lot of time as it provides a fast and easy way to generate texts or code blocks without having to write everything by hand. This is particularly useful for simple routine tasks.

Versatility: ChatGPT can be used in many different languages and contexts, making it a versatile tool. It can, for example, help with the implementation of algorithms and code documentation, as well as explain existing code.

Adaptability: ChatGPT can be adapted to specific requirements and needs and generate context-specific code.

Nachteile

Limited control: Since ChatGPT is based on machine learning, users do not have full control over what is generated. The result can sometimes be unpredictable and therefore requires additional checks.

Limited response length: ChatGPT has a maximum response length, which can be a problem when generating longer code sections or complex texts. In this case, you have to ask ChatGPT to continue, which can lead to ChatGPT “forgetting” the context – which brings us to the next disadvantage:

Limited ability to understand context: ChatGPT has difficulty understanding context and can therefore sometimes provide inaccurate or inappropriate results. It is important for users to understand how to best use ChatGPT to achieve the best possible results. Ideally, the “divide-and-conquer” principle should also be used here: the context should be kept as small as possible.

Practical example

Now let’s move on to the practical example: implementing a Pong browser game with ChatGPT.

I asked ChatGPT if it could implement a Pong game for the browser. Unfortunately, the code was longer than the maximum response length, so I had to ask ChatGPT to continue several times. I also instructed it to output only the code without description.

Here’s what the first response looked like:

<!DOCTYPE html>
<html>
  <head>
    <title>Pong Game</title>
    <style>
      canvas {
        border: 1px solid black;
      }
    </style>
  </head>
  <body>
    <canvas id="canvas" width="600" height="400"></canvas>
    <script src="pong.js"></script>
  </body>
</html>
const canvas = document.getElementById("canvas");
const context = canvas.getContext("2d");

canvas.width = 800;
canvas.height = 600;

let player1 = {
  x: 20,
  y: canvas.height / 2 - 50,
  width: 10,
  height: 100,
  score: 0,
};

let player2 = {
  x: canvas.width - 30,
  y: canvas.height / 2 - 50,
  width: 10,
  height: 100,
  score: 0,
};

let ball = {
  x: canvas.width / 2,
  y: canvas.height / 2,
  radius: 10,
  speed: 7,
  dx: 7,
  dy: -7,
};

function drawNet() {
  context.fillStyle = "#FFF";
  for (let i = 0; i <= canvas.height; i += 15) {
    context.fillRect(canvas.width / 2 - 1, i, 2, 10);
  }
}

function drawRect(x, y, w, h, color) {
  context.fillStyle = color;
  context.fillRect(x, y, w, h);
}

function drawCircle(x, y, r, color) {
  context.fillStyle = color;
  context.beginPath();
  context.arc(x, y, r, 0, Math.PI * 2, false);
  context.closePath();
  context.fill();
}

function drawText(text, x, y, color) {
  context.fillStyle = color;
  context.font = "45px fantasy";
  context.fillText(text, x, y);
}

function draw() {
  drawRect(0, 0, canvas.width, canvas.height, "#000");

  drawRect(player1.x, player1.y, player1.width, player1.height, "#FFF");

  drawRect(
    player2.x,
    player2.y,
    player2.width,
    player2.height,
    "#FFF"
  );

  drawCircle(ball.x, ball.y, ball.radius, "#FFF");

  drawNet();
}

function ballWallCollision() {
  if (ball.y + ball.radius > canvas.height || ball.y - ball.radius < 0) {
    ball.dy = -ball.dy;
  }
}

function ballPaddleCollision(player) {
  if (
    ball.x + ball.radius > player.x &&
    ball.x - ball.radius < player.x + player.width &&
    ball.y + ball.radius > player.y &&
    ball.y - ball.radius < player.y + player.height
  ) {
    let collidePoint = ball.y - (player.y + player.height / 2);
    collidePoint = collidePoint / (player.height / 2);
    let angleRad = (Math.PI / 4) * collidePoint;
    let direction = ball.x + ball.radius < canvas.width / 2 ? 1 : -1;
    ball.dx = direction * ball.speed * Math.cos(angleRad);
    ball.dy = ball.speed * Math.sin(angleRad);
  }
}

function resetBall() {
  ball.x = canvas.width / 2;
  ball.y = canvas.height / 2;
  ball.speed = 7;
  ball.dx = ball.speed;
  ball.dy = -ball.speed;
}

function drawScore() {
  context.font = "32px Arial";
  context.fillText(player1.score, 100, 50);
  context.fillText(player2.score, canvas.width - 100, 50);
}

function checkGameOver() {
  if (player1.score === maxScore || player2.score === maxScore) {
    let winner = player1.score === maxScore ? "Player 1" : "Player 2";
    alert(`${winner} wins!`);
    player1.score = 0;
    player2.score = 0;
  }
}

function update() {
  ball.x += ball.dx;
  ball.y += ball.dy;

  ballWallCollision();

  ballPaddleCollision(player1);
  ballPaddleCollision(player2);

  if (ball.x - ball.radius < 0) {
    player2.score++;
    resetBall();
    } else if (ball.x + ball.radius > canvas.width) {
    player1.score++;
    resetBall();
  }

  checkGameOver();
}

function game() {
  update();
  draw();
}

let maxScore = 3;

canvas.addEventListener("mousemove", (event) => {
  let rect = canvas.getBoundingClientRect();
  player1.y = event.clientY - rect.top - player1.height / 2;
});

canvas.addEventListener("mousedown", () => {
  if (player1.score === maxScore || player2.score === maxScore) {
  player1.score = 0;
  player2.score = 0;
  }
});

setInterval(game, 1000 / 60);

The code is basically functional: A game loop has been implemented, objects are being drawn, the ball is moving, and there is collision detection. However, ChatGPT forgot to implement the movement of the paddles. Additionally, a function called drawScore() has been implemented but it is not being called anywhere.

So, it is necessary to make some improvements:

The code is missing the movement of the paddle. The paddles should be able to move using the keyboard. Please show only the places where code needs to be modified.
function movePaddle(evt) {
  let rect = canvas.getBoundingClientRect();
  if (evt.clientY - rect.top - player1.height / 2 > 0 && evt.clientY - rect.top + player1.height / 2 < canvas.height) {
    player1.y = evt.clientY - rect.top - player1.height / 2;
  }
}

function movePaddleUp() {
  player1.y -= 10;
}

function movePaddleDown() {
  player1.y += 10;
}

document.addEventListener("keydown", function (evt) {
  switch (evt.key) {
    case "w":
      movePaddleUp();
      break;
    case "s":
      movePaddleDown();
      break;
  }
});

Here it seems like I was a bit too vague – while the paddle movement for player 1 was implemented, it is missing for player 2. So, let’s keep improving:

Please implement the same for player 2 as well. The paddle should be moved with the "arrow up" and "arrow down" keys.
function movePaddleUp(player) {
  player.y -= 10;
}

function movePaddleDown(player) {
  player.y += 10;
}

document.addEventListener("keydown", function (evt) {
  switch (evt.key) {
    case "w":
      movePaddleUp(player1);
      break;
    case "s":
      movePaddleDown(player1);
      break;
    case "ArrowUp":
      movePaddleUp(player2);
      break;
    case "ArrowDown":
      movePaddleDown(player2);
      break;
  }
});

That looks better now. Now I asked ChatGPT to implement a start button which allows the game to be started and restarted with a button click at the beginning and end of the game. Again, ChatGPT should only output the relevant changes:

<!DOCTYPE html>
<html>
  <head>
    <title>Pong Game</title>
    <style>
      canvas {
        border: 1px solid black;
      }
    </style>
  </head>
  <body>
    <canvas id="canvas" width="600" height="400"></canvas>
    <button id="startButton">Start</button>
    <script src="pong.js"></script>
  </body>
</html>
let canvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");

let startButton = document.getElementById("startButton");
startButton.addEventListener("click", startGame);

let gameStarted = false;

// Restlicher Code hier

function checkGameOver() {
  if (player1.score === maxScore || player2.score === maxScore) {
    let winner = player1.score === maxScore ? "Player 1" : "Player 2";
    alert(`${winner} wins!`);
    player1.score = 0;
    player2.score = 0;
    startButton.disabled = false;
    gameStarted = false;
    }
}

function startGame() {
  gameStarted = true;
  startButton.disabled = true;
}

function game() {
  if (!gameStarted) {
    return;
  }
  update();
  draw();
}

The game is now basically playable. However, in terms of usability and code itself, we still have some way to go to reach our goal. But let’s ask ChatGPT what he would optimize in the code:

The movement of the paddles is limited to moving up or down by 10 pixels. This can result in relatively slow movement. To improve the responsiveness of the game, one could increase the step by which the paddles move to make them move faster.

The game ends abruptly as soon as a player reaches the maximum score. However, it could be more meaningful to give players a chance to know who won the last game before the game is fully over. One way to do this would be to pause the game for a certain number of seconds and display the name of the winner on the screen.

The code could be better organized by splitting some of the functions into separate files. For example, all functions related to drawing objects on the canvas could be placed in one file and imported from there. This would make the main code more readable and increase maintainability.

Consider using requestAnimationFrame() to update the game loop instead of calling setInterval or setTimeout. requestAnimationFrame() is more efficient and provides better synchronization with the browser's rendering pipeline.

That sounds reasonable. However, the second point is not entirely correct – an alert() is currently called after the end of the game. But that can definitely be implemented in a more user-friendly way.

Of course, the design could also be responsive to be playable on different devices, a consistent use of “let” or “const” would be desirable. Also, there are no comments at all.

Conclusion

In summary, ChatGPT offers both advantages and disadvantages when it comes to generating program code. On the positive side, it can save time, be used in a versatile manner, and enable automated processes. On the other hand, it may have difficulties in understanding context, have limited response lengths, and offer limited control over the generated results.

To achieve the best possible results, it is important for the user to clearly define the context and guide ChatGPT through targeted requests. It is also helpful to fine-tune the output to specific requirements and needs, and carefully review the generated results. With these tips, ChatGPT can be a valuable tool for generating text and code blocks, as well as automating complex tasks.

Furthermore, as mentioned above, ChatGPT can analyze existing code and suggest optimizations.

So ChatGPT and I will continue to work on the code and keep you updated!

AI meets AI: Are ChatGPT and Bing Image Creator a good team?

When it comes to creative projects, it can be challenging to develop new ideas and concepts. This is where AI comes into play. With tools like ChatGPT and Bing Image Creator, it’s easier than ever to generate unique and interesting content.

ChatGPT is a language model trained by OpenAI that can understand natural language and generate responses in a conversational manner. Bing Image Creator, on the other hand, is a AI-based tool that can generate images based on text prompts.

So, are both a good team? In short, yes! By using ChatGPT to generate ideas and prompts and Bing Image Creator to bring those ideas to life with images, you can create a strong creative partnership.

To get started, you can ask ChatGPT for ideas on topics for image generation. For example, simply input the prompt “Do you have any creative ideas for image galleries that can be generated with Bing Image Creator?” From the topics generated by ChatGPT, you can then choose the ones that appeal to you the most.

But that’s not all! ChatGPT can also be used to generate a specific number of prompts for the selected topics. For example, you can ask ChatGPT to generate five prompts for “futuristic landscapes” or “magical creatures.” The prompts generated by ChatGPT can then be used as input for Bing Image Creator to generate amazing images that will surprise and delight you.

One of the advantages of using both AI-based tools is that they can help you explore new ideas and concepts that you may not have otherwise thought of. With the help of these tools, you can expand the limits of your creativity and create new and exciting content that will appeal to and inspire your audience.

Here are three image galleries created through the collaboration of both AI tools:

And here is the chat log for your reference:

Do you have any creative ideas for image galleries that can be generated with Bing Image Creator?
Yes, I have a few ideas for image galleries that can be generated with Bing Image Creator:

Animal Worlds: Create a gallery of images depicting fantastic worlds inhabited by animals. For example, you could show an image of a forest fox walking on a mushroom, or an image of an elephant wandering through a desert full of cacti.

Machine Fantasies: Create a gallery of images showing machines working or living in fantasy worlds. For example, you could show an image of a giant steam engine crossing a river, or an image of a robot walking through a futuristic city.

Magical Creatures: Create a gallery of images depicting magical creatures such as unicorns, dragons, or elves. For example, you could show an image of a unicorn in an enchanted forest or an image of a dragon hovering over a castle.

Fictional Landscapes: Create a gallery of images showing fictitious landscapes, such as a city floating on clouds or a mountain made of gold.

Interstellar Travel: Create a gallery of images showing space travel, such as a spaceship flying through the Milky Way or a planetary landscape illuminated by a starry sky.

I hope these ideas give you inspiration for your own Bing Image Creator generated image gallery!
Please generate 20 prompts for magical creatures
- A basilisk, a serpent with deadly venom and the power to turn people to stone with its gaze.
- A unicorn with a shimmering, rainbow-colored mane and a powerful, golden horn.
- A chimaera, a creature with the head of a lion, the body of a goat, and the tail of a serpent.
- A thunderbird, a giant bird from Native American mythology that creates thunder and lightning with the beating of its wings.
- A banshee, a female spirit known for her wailing cries that foretell death.
- A siren, a creature of Greek mythology that emerges from the sea and lures sailors to their deaths with its songs.
- A Nekomusume, a Japanese creature that is half cat, half woman and has supernatural powers.
- A phoenix born from flames and reborn whenever it dies.
- A kraken, a giant sea monster with tentacles that can crush ships and drag them underwater.
- A gorgon, a creature with snakes for hair and the power to turn people to stone with its gaze.
- A dragon slayer, a human hero who fights against dragons and seizes their treasures.
- A kelpie, a Celtic creature that appears as a horse with a shimmering, wet coat and drowns travelers in bodies of water.
- A griffin, a majestic creature with the head and wings of an eagle and the body of a lion.
- A yeti, a humanoid creature that lives in the snowy mountains and is known for its strength and elusive nature.
- A fairy dragon whose scales shimmer in all colors of the rainbow and who spits tiny sparks.
- A werewolf with sharp claws, a powerful bite, and the ability to transform between human and wolf form.
- A leprechaun who is always up to mischief and has gleaming, sparkling eyes.
- A goblin, a small and cunning creature known for its love of treasure and tendency to cause mischief.
- A minotaur, a creature with the body of a man and the head of a bull, known for its strength and ferocity.
- A mermaid with a voice that can enchant anyone who hears it and a tail that glitters like gold.
Please generate 20 prompts for fictional creatures
- A floating island, with majestic waterfalls and lush gardens that defy gravity.
- An underground city, with sprawling tunnels and bioluminescent plants that light the way.
- A lost world, with ancient ruins and towering trees, inhabited by dinosaurs and other prehistoric creatures.
- A crystal cave, with glittering walls and underground lakes that reflect the light in dazzling colors.
- A frozen tundra, with ice sculptures and frozen lakes that stretch as far as the eye can see.
- A sky kingdom, with towering spires and magical creatures that soar through the clouds.
- A desert oasis, with palm trees and sparkling blue pools that provide a refuge from the scorching sun.
- A coral reef, with colorful fish and other sea creatures that swim among the vibrant coral formations.
- A sentient forest, with trees that move and communicate with each other, creating a magical and mysterious atmosphere.
- A misty mountain range, with hidden valleys and cascading waterfalls, shrouded in a mystical fog.
- A lava field, with bubbling pools of molten rock and steaming geysers.
- A technicolor jungle, with fluorescent flora and fauna that create a surreal and psychedelic environment.
- A city in the clouds, with towering skyscrapers and bridges that stretch across the sky.
- A sunken city, with submerged buildings and ruins that are now home to underwater creatures.
- A rainbow canyon, with brightly colored rocks and a river that runs through it.
- A floating forest, with trees that hover above the ground and are anchored to the sky by delicate vines.
- A candy land, with gingerbread houses and candy cane trees that create a sugary wonderland.
- A time warp, with pockets of different eras and civilizations that exist side by side.
- A living desert, with sand dunes that shift and change with the wind, and strange desert creatures that roam the landscape.
- A mirrored lake, with perfectly still water that reflects the sky and creates a stunning optical illusion.
Please generate 20 prompts for machine fantasies
- A machine that can turn anything into gold.
- A time machine that can transport you to any point in history.
- A device that can record and playback dreams.
- A machine that can clone any living creature perfectly.
- A flying machine that can travel faster than the speed of sound.
- A robotic companion that can anticipate your every need and desire.
- A machine that can create a portal to other dimensions.
- A machine that can download and upload human memories.
- A machine that can detect and cure any disease.
- A machine that can create perfect weather conditions.
- A teleportation machine that can transport you anywhere instantly.
- A machine that can create and manipulate gravity.
- A device that can translate any language in real-time.
- A machine that can create and control earthquakes.
- A machine that can generate unlimited clean energy.
- A machine that can create and control natural disasters.
- A device that can create and manipulate time loops.
- A machine that can instantly build anything from raw materials.
- A device that can create and control virtual reality.
- A machine that can create and manipulate magnetic fields.

My Journey to Blogging: My experiences with ChatGPT and Bing Image Creator so far

Today, I would like to share my experience after about a month of blogging with you and how much AI tools such as ChatGPT and Bing Image Creator have helped me.

Here are some benefits that I have experienced with my project so far:

  1. ChatGPT can assist with general questions about setting up a website, in my case with WordPress. This saved me a lot of time and effort as I didn’t have to handle everything myself.
  2. ChatGPT can write and optimize blog posts when given a rough framework. I provided the basic structure and topic, and ChatGPT did the rest. This saved me a lot of time and stress.
  3. ChatGPT can be used as an editor. After I wrote my blog posts or revised posts from ChatGPT, I had them checked by ChatGPT. This allowed me to correct my own mistakes and improve my posts.
  4. ChatGPT can be used as a translator for multilingual content. Since I also wanted to reach readers from other countries, I was able to quickly and easily translate my content into English with ChatGPT.
  5. Bing Image Creator can generate appealing images for posts. I was able to easily create a suitable featured image for each post that reflects the content.
  6. ChatGPT can generate custom program code, such as PHP or Javascript, in the web environment. For example, I was able to create a topic-specific news page for my website.

Thanks to ChatGPT, I was able to create a new website with eight blog posts within a week.

In addition, I was able to create four image galleries with different themes and styles within a week using Bing Image Creator.

Without such AI tools, I would have had to invest much more time and effort to achieve all of this.

Overall, I am very satisfied with the results and will definitely use more AI tools in the future to increase my productivity.
If you also want to increase your productivity, I recommend trying ChatGPT and other AI tools to see how they can help you.

Gallery: False Places

Hello dear readers! Today I would like to introduce my latest gallery False Places with the theme “False Places”. In this exhibition, I focused on famous buildings and placed them in unusual locations. The result is impressive photographs that take the viewer into a surreal-altered world.

An absolute highlight of this exhibition is the photograph of the Golden Gate Bridge, which I placed in the middle of a jungle. The distinctive bridge amidst lush vegetation and a dense forest is an unusual and fascinating combination. The green leaves and trees create a natural setting for San Francisco’s famous landmark and make the picture almost look like a scene from a science fiction film.

Another spectacular image shows the Tower Bridge, which I placed on Mars. The distinctive lines of the bridge against the red background of the planet are simply fascinating and open up new perspectives on the famous building to the viewer.

And then there is my photograph of the Louvre, which I placed underwater. The Louvre, one of the most famous art museums in the world, seems almost to be submerged, creating a surreal atmosphere. The colors and light reflections on the water’s surface create a unique mood that takes the viewer into another world.

I could tell you much more about my exhibition, but it’s best to see the pictures for yourself and let them enchant you. I’m looking forward to your visit!

My Journey to Blogging: News-Page Optimization

In the article “Generating a AI news page with ChatGPT and GDELT“, I have already shown how it is possible in principle to generate a simple topic-specific news website.

Today, I want to implement a small optimization for the news page with the help of ChatGPT. Currently, similar news or even news with exactly the same title are displayed.

Here’s the chat log:

The following PHP code needs to be adjusted so that if titles are duplicated, only the first data set is used. In addition, only a maximum of 5 data sets should be output.
function display_ai_news_data() {
	$url = 'https://api.gdeltproject.org/api/v2/doc/doc?format=html&timespan=24H&query=Artificial%20Intelligence%20sourcelang:eng&mode=artlist&maxrecords=5&format=json&sort=hybridrel';

	$response = wp_remote_get( $url );

	if ( is_array( $response ) ) {
		$headers = $response['headers'];
		$body    = json_decode( $response['body'], true );

		if ( ! empty( $body ) && isset( $body['articles'] ) ) {
			$articles = $body['articles'];

			foreach ( $articles as $article ) {
				$title = $article['title'];
				$url   = $article['url'];
				$image = $article['socialimage'];

				echo '<div>';
				echo '<h2>' . $title . '</h2>';
				echo '<img src="' . $image . '" />';
				echo '<p><a href="' . $url . '">Read more</a></p>';
				echo '</div>';
			}
		}
	}
}
Here is an updated version of the code that only uses the first data set for each duplicate title and outputs a maximum of 5 data sets:
function display_ai_news_data() {
    $url = 'https://api.gdeltproject.org/api/v2/doc/doc?format=html&timespan=24H&query=Artificial%20Intelligence%20sourcelang:eng&mode=artlist&maxrecords=5&format=json&sort=hybridrel';

    $response = wp_remote_get( $url );

    if ( is_array( $response ) ) {
        $headers = $response['headers'];
        $body    = json_decode( $response['body'], true );

        if ( ! empty( $body ) && isset( $body['articles'] ) ) {
            $articles = $body['articles'];
            $used_titles = array();

            foreach ( $articles as $article ) {
                $title = $article['title'];
                if (in_array($title, $used_titles)) {
                    continue; // Skip articles with already used title
                }
                $used_titles[] = $title; // Mark this title as used
                $url   = $article['url'];
                $image = $article['socialimage'];

                echo '<div>';
                echo '<h2>' . $title . '</h2>';
                echo '<img src="' . $image . '" />';
                echo '<p><a href="' . $url . '">Read more</a></p>';
                echo '</div>';

                if (count($used_titles) >= 5) {
                    break; // Limit reached, stop the loop
                }
            }
        }
    }
}
Can you rephrase this to select 5 random data sets to display from articles?
Yes, I can do that! Here is an updated version of the code that selects 5 data sets at random from articles:
function display_ai_news_data() {
    $url = 'https://api.gdeltproject.org/api/v2/doc/doc?format=html&timespan=24H&query=Artificial%20Intelligence%20sourcelang:eng&mode=artlist&maxrecords=50&format=json&sort=hybridrel';

    $response = wp_remote_get( $url );

    if ( is_array( $response ) ) {
        $headers = $response['headers'];
        $body    = json_decode( $response['body'], true );

        if ( ! empty( $body ) && isset( $body['articles'] ) ) {
            $articles = $body['articles'];

            shuffle($articles); // randomly shuffle the array

            $used_titles = array();
            $count = 0;

            foreach ( $articles as $article ) {
                if ($count >= 5) {
                    break; // limit reached
                }
                $title = $article['title'];
                if (in_array($title, $used_titles)) {
                    continue; // Skip articles with already used title
                }
                $used_titles[] = $title; // Mark this title as used
                $url   = $article['url'];
                $image = $article['socialimage'];

                echo '<div>';
                echo '<h2>' . $title . '</h2>';
                echo '<img src="' . $image . '" />';
                echo '<p><a href="' . $url . '">Read more</a></p>';
                echo '</div>';

                $count++;
            }
        }
    }
}
The code uses the shuffle() function to randomly shuffle the articles array. Then a foreach loop is used to iterate through each article in the random order. The code also uses the $used_titles array to check if the title has already been used. If the title has already been used, the data set is skipped. Otherwise, the data set is output and the title is marked as used. When the maximum of 5 data sets is reached, the loop stops.

I hope that helps!

I was able to use this code directly as well.

ChatGPT even explained the code changes to me and increased the value of maxrecords in the API call from 5 to 50 based on the context, even though I didn’t explicitly ask for it.

In summary, ChatGPT provides great support for code optimizations. Thanks to its abilities in machine learning and artificial intelligence, ChatGPT can quickly and accurately respond to questions and requests related to programming and offer customized solutions.

Gallery: Visual Songs

Hey guys, have you heard of “Visual Songs” yet? No? Then it’s time for you to check out this new picture gallery Visual Songs!

Here, everything revolves around famous song titles and lyrics that are interpreted in impressive images. It’s really amazing how creative the interpretations are. Each picture tells a story and invites you to immerse yourself in the world of the respective song.

What I particularly like about “Visual Songs” is that the pictures are so versatile. There really is something for every taste – from pop songs to rock classics. And the styles vary from realistic to abstract. I think that everyone will really enjoy this gallery.

So, if you’re looking for new inspiration or just something beautiful to look at, then definitely check out “Visual Songs”. It’s definitely worth it!

In this sense, happy browsing!

« Older posts