CodeGym /Java Course /Python SELF EN /Working with AI API

Working with AI API

Python SELF EN
Level 24 , Lesson 4
Available

10.1 ChatGPT

Wait, what am I talking about? We live in a world created by artificial intelligence. Let's try to work with it. And of course, we'll start with ChatGPT.

Example of working with OpenAI API (ChatGPT)

To work with the OpenAI API, you need to register on the platform, get an API key, and use it for authentication when making requests.

Then you need to install the openai library — it's their official client.


pip install openai

Now let's send them a request:


import openai

# Your OpenAI API key
api_key = 'YOUR_OPENAI_API_KEY'

# Authentication
openai.api_key = api_key

# Request to the ChatGPT model
response = openai.Completion.create(
    engine="text-davinci-003",
    prompt="Tell me an interesting fact about space.",
    max_tokens=500
)

# Print the response
print(response.choices[0].text.strip())

You need to register on their official website and get a key. If you're a new user (your phone number is not in their base), you'll get a bonus of $20.

10.2 Google Cloud Vision API

Google Cloud Vision API provides capabilities for image analysis, including object, text, face recognition, and other elements. So far, the Google Bard API is not publicly available and requires authentication through Google Cloud Platform.

Step 1. Start by installing the google-cloud-vision library.


pip install google-cloud-vision

Step 2. Set up authentication using a Service Account Key.

Code example for image analysis:


from google.cloud import vision
import io

# Initialize the client
client = vision.ImageAnnotatorClient()

# Load the image
file_name = 'path/to/your/image.jpg'
with io.open(file_name, 'rb') as image_file:
    content = image_file.read()

image = vision.Image(content=content)

# Object detection
response = client.object_localization(image=image)
objects = response.localized_object_annotations

# Output detected objects
for object_ in objects:
    print(f'Object name: {object_.name}')
    print(f'Score: {object_.score}') 

This code recognizes an image and outputs a list of detected objects. You can easily add it to your project to create a cool web service or app.

10.3 Microsoft Text Analytics API

Azure Cognitive Services provides an API for text analysis, including language detection, sentiment analysis, key phrase extraction, and entity recognition.

Sentiment analysis is the process of determining the emotional tone of the text (positive, negative, or neutral). This can be useful for analyzing customer reviews, monitoring social media, or evaluating reactions to specific events or products.

Installation and Authentication

Step 1. Install the Azure library:


pip install azure-ai-textanalytics

Step 2. Set up authentication using the API key and endpoint.

Code example for sentiment analysis:


from azure.ai.textanalytics import TextAnalyticsClient
from azure.core.credentials import AzureKeyCredential

# Initialize the client
endpoint = "YOUR_AZURE_ENDPOINT"
api_key = "YOUR_AZURE_API_KEY"
credential = AzureKeyCredential(api_key)
client = TextAnalyticsClient(endpoint=endpoint, credential=credential)

# Texts for analysis
documents = ["I love programming in Python!", "I'm feeling very happy today!"]

# Sentiment analysis
response = client.analyze_sentiment(documents=documents)

# Output results
for doc in response:
    print(f"Sentiment: {doc.sentiment}")
    print(f"Confidence Scores: {doc.confidence_scores}")

10.4 DeepAI (Text Summarization API)

DeepAI provides an API for various machine learning tasks, including text summarization.

Text summarization is the process of creating a concise summary of a large body of text, preserving its key ideas and main content. It's useful for quickly familiarizing yourself with long documents, automatically creating annotations, or processing large volumes of text information.

Installation and Authentication

Step 1. Install the requests library:


pip install requests

Step 2. Use the API key for authentication.

Code example for text summarization:


import requests

# Your DeepAI API key
api_key = 'YOUR_DEEPAI_API_KEY'

# Text for summarization
text = "Artificial intelligence (AI) is intelligence demonstrated by machines, in contrast to the natural intelligence displayed by humans and animals. Leading AI textbooks define the field as the study of 'intelligent agents': any device that perceives its environment and takes actions that maximize its chance of successfully achieving its goals."

# API request
response = requests.post(
    "https://api.deepai.org/api/summarization",
    data={'text': text},
    headers={'api-key': api_key}
)

# Get the response
data = response.json()

# Output the summary
print(data['output'])

Possible Output

If you run the above code with the correct API key, you'll get something like:


Artificial intelligence (AI) is the intelligence shown by machines, unlike natural intelligence in humans and 
animals. AI studies 'intelligent agents': devices that perceive their environment and act to achieve their 
goals.

This summary will include the key points from the original text, reducing it to a more concise version. Note that the exact result may vary depending on the algorithm and model version used in DeepAI.

2
Task
Python SELF EN, level 24, lesson 4
Locked
OpenAI API
OpenAI API
2
Task
Python SELF EN, level 24, lesson 4
Locked
Google Cloud Vision API
Google Cloud Vision API
1
Опрос
Networking Basics,  24 уровень,  4 лекция
недоступен
Networking Basics
Networking Basics
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION