Applications of GenAI App Integration Using Segmind API and Postman

Mobarak Inuwa Last Updated : 29 Sep, 2023
9 min read

Introduction

Integrating Artificial Intelligence (AI) into our applications is becoming increasingly necessary for staying competitive in business. Adding these AI features enhances user experiences, automates tasks, and provides valuable insights. There are possibilities since we have diverse GenAI models available. However, integrating AI into your app can be complex. Especially the new trend with GenAI, where many processes are still being experimented with. So, suppose you want to see how you can integrate GenAI into your personal application or software, like a fashion app. In that case, this article aims to simplify the process by integrating the GenAI App integration using Segmind API and Postman.

Learning Objectives

  • Understanding Segmind models and APIs
  • Understanding GenAI Integration API with Segmind
  • Using Postman with Segmind API

This article was published as a part of the Data Science Blogathon.

Understanding the Segmind Models API

To understand Segmind’s GenAI API comprehensively, you must understand its purpose, capabilities, and benefits. Some potential use cases to highlight include image recognition for e-commerce apps, fashion design, animation, background removal, artwork, painting, comics, etc. Apart from the ease of use, Segmind AI provides GenAI models available through the API and playground on the website at https://www.segmind.com/models. In this article, we will use API inference calls. Selecting a model that suits your tasks with an available API script is easy. Below is an example of a Stable Diffusion 1.5 Outpainting model available at https://www.segmind.com/models/sd1.5-outpaint/api.

import requests
from base64 import b64encode

def toB64(imgUrl):
    return str(b64encode(requests.get(imgUrl).content))[2:-1]


api_key = "YOUR API-KEY"
url = "https://api.segmind.com/v1/sd1.5-outpaint"

# Request payload
data = {
  "image": toB64('https://www.segmind.com/image5.png'),
  "prompt": "streets in italy",
  "negative_prompt": "NONE",
  "scheduler": "DDIM",
  "num_inference_steps": 25,
  "img_width": 1024,
  "img_height": 1024,
  "scale": 1,
  "strength": 1,
  "offset_x": 256,
  "offset_y": 256,
  "guidance_scale": 7.5,
  "mask_expand": 8,
  "seed": 124567
}

response = requests.post(url, json=data, headers={'x-api-key': api_key})
print(response)

Signing Up for Segmind AI

The beauty of Segmind is that they provide an option to use it with free prompts and have very cost-effective paid inferences for your API calls. This requires a sign-up to have access to generate API keys. You can get an utterly Free API with some limitations to try it out. Note that free accounts get 100 Free API calls per day. You can check out their pricing page if you need more API calls. Especially if you integrate a model into your personal app to ensure free flow.

The sign-up process takes just a few clicks using a valid email address. Once you sign up, you will see the landing page below:

GenAI App Integration | Segmind API | Postman

You need a profile key. Go on to click on the “Create New API Key” button. If you do not find this option to create a key after signing up, go to https://cloud.segmind.com/ and access your dashboard. You need to set the number of days for the expiration of your new API. Failure to do so will use a default lifetime duration. For this tutorial, I set mine to 7 days. Click “Confirm” and continue.

GenAI App Integration | Segmind API | Postman

After generating your API key, locate the model we will be using at https://www.segmind.com/models/sd1.5-revanimated/api note that we will be using API for this tutorial, but go ahead and play with the playground and see how it works.

Setting Up Postman

Now that you have signed up on Segmind and Generated an API key let us walk through the process of setting up Postman. Postman is a perfect tool since it makes the process easy. Go to https://www.postman.com/. Sign up, and you should find the landing page below.

Step 1: Create a Workspace

By the top left, you should see the header containing the “Workspace.” Select it and select “Create Workspace” to add a new workspace. You will see the “Next” button at the bottom left. Select it to continue. Fill in the information and click on Create. My workspace name is Segmind Demo. Wait for your new workspace to be created.

GenAI App Integration | Segmind API | Postman
 Workspace | GenAI App Integration | Segmind API | Postman
Workspace

Step 2: Create a Collection

The next thing is to create collections. Select the collections button at the left and give it a name. I call it ‘revanimated’ since this is the model I will be demoing. The next thing we need now is to create a request.

"

Step 3: Creating a Request

Now, this is an aspect to note to avoid errors. Every API has its specifications, including the Segmind models’ APIs. One thing to note is that the models use an API query token of an x-api-key header on all API queries. We will see this in a moment.

"

The default value is “GET,” but change it to “POST”. The next thing besides POST is a URL.

Connecting Postman to Segmind API

One design focus of Segmind is to focus on simplicity and ease. All the URLs (endpoints) follow a similar pattern to https://api.segmind.com/v1/{endpoint}. Just replace the curly bracket with the name of the model. No need to memorize this since it is available in every model on https://www.segmind.com/models. Now, let us see the model we are demoing.

import requests

api_key = "YOUR API-KEY"
url = "https://api.segmind.com/v1/sd1.5-revanimated"

# Request payload
data = {
  "prompt": "advanced aircraft, gundam, dark black robot, spaceship, long, giant guns, futuristic design, scifi, in space, supernova, stars, planets, (8k, RAW photo, best quality, ultra high res, photorealistic, masterpiece, ultra-detailed, Unreal Engine),best quality, warrior,((cinematic look)), insane details, advanced weapon, fight, battle, epic, power, combat, shoot, shooting, missiles, bombs, explosions, rockets, jetpack, defence, attacking,wide angle",
  "negative_prompt": "boring, poorly drawn, bad artist, (worst quality:1.4), simple background, uninspired, (bad quality:1.4), monochrome, low background contrast, background noise, duplicate, crowded, (nipples:1.2), big breasts",
  "samples": 1,
  "scheduler": "ddim",
  "num_inference_steps": 25,
  "guidance_scale": 9,
  "seed": 3426017487234,
  "img_width": 512,
  "img_height": 768,
  "base64": False
}

response = requests.post(url, json=data, headers={'x-api-key': api_key})
print(response)

You can find the above script in the API tab on the page for the model we use: https://www.segmind.com/models/sd1.5-revanimated/api. You can choose between Python, bash, or Javascript. The above script is Python.

The two below are going to be used for our API call.

api_key = "YOUR API-KEY"

url = "https://api.segmind.com/v1/sd1.5-revanimated"

Going back to Postman, copy the above URL (https://api.segmind.com/v1/sd1.5-revanimated) and paste it into the URL space beside POST.

API Authorization

Before we go on, let us see security best practices for securing your API credentials:

  • Store your API keys and tokens in a secure location, such as environment variables or a dedicated secrets management service.
  • Never expose your API credentials in public repositories or share them in plaintext. Utilize tools like environment files or secrets management to keep them confidential.
  • Only provide access to API keys and tokens to team members who require them. Implement role-based access controls when possible.
  • Regularly rotate your API keys and tokens to minimize the risk of unauthorized access.
  • Implement monitoring and auditing mechanisms to track API usage and promptly detect suspicious activity.

Now, select the “Authorization” tab and click the drop-down menu after “Type,” and select “API Key.”

"

Now, fill in details about the API key you want to use. For the Key, fill in x-api-key, copy the API key you created, or create a new one and paste it into the value field. Let “Add to” be set to header.

Setting the Headers

For the header, you are to provide a key and a value. For the key, select “Content-Type,” and the value should be “application/json” shown below.

"

Setting API body

The body is the most interesting thing. This is where to provide your prompt!

Before you go on, understand the limitations of Free API accounts. It’s essential to manage your expectations when using a free API account. While it offers an excellent opportunity for exploration, there are limitations to be aware of, such as rate limits on API requests. These rate limits may affect the volume and speed of API requests you can make. To fully leverage GenAI in high-demand applications, consider upgrading to a premium plan to access higher rate limits and additional features from Segmind.

Create an intricate, stunning 3D rendering of a futuristic space battle between advanced aircraft and dark black robots mesmerizing supernova explosion. The scene should feature long, giant guns and spaceships with an ultra-detailed, photorealistic design. The spacecraft should be armed with weapons like missiles, bombs, rockets, and jetpacks, engaged in epic combat, shooting, and defending against the menacing robots. The wide-angle view should capture the battle, emphasizing the power and sophistication of the warriors. The cinematic look should add drama to the scene, making it an unforgettable masterpiece of sci-fi art.

You can set other parameters like seed, scheduler, etc. Below is the snippet of what I used.

"samples":1,"scheduler":"ddim","num_inference_steps":25,"guidance_scale":9,"seed":7567182154,"img_width":512,"img_height":768,"base64":false

Under the body, select ‘raw’ and enclose all the parameters above as key-value pairs in curly braces in the request’s body.

"

Click on Send to create a request. This should show your generated output image. You could change it to ‘send and download’ to download a copy of the image generated.

"

Now, you can go on to integrate with your local app. You can switch to a model of your choice and follow the same process.

Real-World Examples for GenAI

Before we conclude, let’s explore some real-world scenarios where GenAI models can enhance user experiences:

  1. E-commerce: GenAI models can improve product recommendation systems, helping users discover products tailored to their preferences and browsing history.
  2. Content Creation: Content generation models can assist content creators by generating text for articles, blog posts, or social media posts, saving time and boosting productivity.
  3. Healthcare: GenAI can assist medical professionals by analyzing medical images for faster and more accurate diagnosis and treatment planning.
  4. Gaming: In the gaming industry, AI can enhance character animations, generate realistic landscapes, and even adapt gameplay based on a player’s actions, providing more immersive experiences.

Challenges and Best Practices

Optimizing the use of GenAI models in applications can present challenges. Some potential challenges include managing large data volumes, effectively handling rate limits, and ensuring that your application remains responsive even during AI processing. Best practices for overcoming these challenges include:

  • Caching Results: Cache AI responses when applicable to reduce redundant API calls and improve response times.
  • Load Balancing: Distribute AI requests across multiple servers or instances to avoid overloading a single server.
  • Rate Limit Monitoring: Implement rate limit monitoring to dynamically adjust API requests based on the current rate limit status.
  • Data Management: Efficiently manage and preprocess data to ensure it aligns with the input requirements of GenAI models, optimizing the AI integration process.

Conclusion

We have seen a clear understanding of the Segmind GenAI API, the power of Postman, and the careful integration process. This can enhance your applications with AI, with improved user experiences and staying competitive in the modern tech landscape. By addressing the challenges and implementing these best practices, you can ensure that your GenAI integration remains efficient and reliable in your application. You now have a solid understanding of the API, security practices, limitations of free accounts, real-world applications, and strategies for optimization.

Key Takeaways

  • Simplified GenAI integration with an application is made easy through the Segmind API and Postman.
  • Segmind API leverages powerful AI capabilities without a complex setup.
  • Postman is a versatile tool for testing and integrating APIs, allowing you to create, send, and analyze APIs easily.

Frequently Asked Questions

Q1: What is the GenAI API by Segmind, and how can it better my application?

A2: The GenAI API provides access to AI models for image generation tasks including text-to-image, image-to-image, image alteration, etc., enhancing your app’s capabilities.

Q2: Why should I use Postman for API integration?

A2: Postman offers an interface for creating and testing API with the simplicity of Segmind, it is a valuable tool for developers and integrators.

Q3: How do I secure Segmind API credentials?

A3: Follow best practices for securing API keys and tokens, storing them in safe environments, and not exposing them in public repositories.

Q4: What are some common challenges when integrating AI into applications, and how can I troubleshoot them?

A4: Challenges may include handling large volumes of data, managing API rate limits, and addressing unexpected errors. Troubleshooting involves thorough testing, error analysis, and effective debugging techniques. Using Segmind removes the need for personal training or handling large volumes of data and OFM errors.

Q5: How can I ensure my application’s long-term success in AI integration?

A5: To ensure ongoing success, focus on optimizing API usage for cost-effectiveness and performance, monitoring unusual activity, and maintaining code modularity. Stay updated on new versions and upgrades.

References

The media shown in this article is not owned by Analytics Vidhya and is used at the Author’s discretion.

I am an AI Engineer with a deep passion for research, and solving complex problems. I provide AI solutions leveraging Large Language Models (LLMs), GenAI, Transformer Models, and Stable Diffusion.

Responses From Readers

We use cookies essential for this site to function well. Please click to help us improve its usefulness with additional cookies. Learn about our use of cookies in our Privacy Policy & Cookies Policy.

Show details