Skip to main content

pollinations-python

A Python wrapper for accessing Pollinations AI API endpoints.

Installation

pip install pypollinations

API documentation

API documentation

Usage

Image Generation

Code Example

import asyncio
from pypollinations import ImageClient, ImageGenerationRequest
from PIL import Image
from io import BytesIO

Client Setup and Image Generation

async def generate_image(
    save_image_path: str = "./examples/generated_images/", 
    image_name: str = "image.png"
):
    client = ImageClient()
    try:
        request = ImageGenerationRequest(
            prompt="A beautiful sunset over mountains with snow peaks",
            width=1024,
            height=768,
            model="flux",
            nologo=True,
        )
        response = await client.generate(request)
        print(f"Image URL: {response.url}")
        print(f"Seed: {response.seed}")

Image Saving

        image_data = response.image_bytes
        try:
            image_data = Image.open(BytesIO(image_data))
            image_data.save(save_image_path + image_name)
            print(f"Image saved to {save_image_path}")
        except Exception as e:
            print(f"Error: {e}")

Model Listing and Main Execution

        models = await client.list_models()
        print("\nAvailable models:")
        print("\n".join(models))

    except Exception as e:
        print(f"Error: {e}")
    finally:
        await client.close()

if __name__ == "__main__":
    asyncio.run(generate_image())

Output Generated Image

Text Generation

Basic Setup

import asyncio
from pypollinations import TextClient, TextGenerationRequest
from pypollinations.models.base import Message
from pypollinations.exceptions import PollinationsError

Text Generation Implementation

async def generate_text():
    client = TextClient()
    try:
        request = TextGenerationRequest(
            messages=[Message(role="user", content="What is artificial intelligence?")],
            model="openai",
            jsonMode=True,
            seed=41,
            temperature=0.5,
            frequency_penalty=0.0,
            presence_penalty=0.0,
            top_p=1.0,
            system="You are a helpful AI assistant.",
        )

Response Handling

        print("Generating response...\n")
        try:
            response = await client.generate(request)
            print(f"Response: {response.content}")
            print(f"Model: {response.model}")
            print(f"Seed: {response.seed}")
            print(f"Temperature: {response.temperature}")
            print(f"Frequency penalty: {response.frequency_penalty}")
            print(f"Presence penalty: {response.presence_penalty}")
            print(f"Top p: {response.top_p}")

Error Handling and Model Listing

        except Exception as e:
            print(f"Failed to generate response: {e}")
            raise

        print("\nFetching available models...")
        try:
            models = await client.list_models()
            print("\nAvailable models:")
            for model in models:
                print(f"- {model['name']}: {model.get('type', 'unknown')}")
        except Exception as e:
            print(f"Failed to fetch models: {e}")

    except PollinationsError as e:
        print(f"API Error: {e}")
    except Exception as e:
        print(f"Unexpected error: {type(e).__name__}: {e}")
    finally:
        await client.close()

if __name__ == "__main__":
    asyncio.run(generate_text())

Output

Generating response...

Response: Artificial Intelligence (AI) is a broad field of computer science dedicated to creating smart machines capable of performing tasks that typically require human intelligence. These tasks include learning, reasoning, problem-solving, perception, and language understanding. Here are some key aspects of AI:

1. **Machine Learning (ML)**: A subset of AI that involves training algorithms to learn from data, make predictions, or improve performance over time.

2. **Deep Learning (DL)**: A subset of machine learning that uses neural networks with many layers to analyze and classify data, often used for tasks like image and speech recognition.

3. **Natural Language Processing (NLP)**: A branch of AI focused on enabling computers to understand, interpret, and generate human language.

4. **Computer Vision**: A field of AI that deals with enabling computers to interpret and understand the visual world, often using data from cameras and sensors.

5. **Robotics**: AI is used to develop robots that can perform tasks autonomously or with guidance, often incorporating computer vision and other AI subfields.

6. **Expert Systems**: These are AI systems that use knowledge and inference rules to provide explanations or make decisions in specific domains.

AI has a wide range of applications, from voice assistants like Siri and Alexa to self-driving cars, medical diagnosis, fraud detection, and more. The goal of AI is to augment and enhance human capabilities, automate routine tasks, and solve complex problems efficiently.
Model: openai
Seed: 41
Temperature: 0.5
Frequency penalty: 0.0
Presence penalty: 0.0
Top p: 1.0

Fetching available models...

Available models:
- openai: chat
- mistral: chat
- mistral-large: chat
- llama: completion
- command-r: chat
- unity: chat
- midijourney: chat
- rtist: chat
- searchgpt: chat
- evil: chat
- qwen-coder: chat
- p1: chat

Features

  • Easy integration with Pollinations AI services
  • Support for various AI models
  • Asynchronous requests support

License

This project is licensed under the Apache License 2.0.

Metadata

Release files for pypollinations 0.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pypollinations 0.2.0
File Size Uploaded
pypollinations-0.2.0.tar.gz 11.4 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for pypollinations 0.2.0
File Interpreter ABI Platform
pypollinations-0.2.0-py3-none-any.whl Python 3 none any Details

Total release size: 24.0 kB

Release files / pypollinations-0.2.0.tar.gz

Download URL pypollinations-0.2.0.tar.gz
Size 11.4 kB
Tags Source
SHA-256 checksum
How to use checksums
03027ce4929514b14a2f4e4457a3a4b23eb40327db7fe08d104f748ead428be7
BLAKE2b-256 checksum
How to use checksums
80b4333a69819ecfc6806420e2d6fc74ffd07ac0312b581d131a2f244db44215
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.8.5 CPython/3.12.8 Linux/6.5.0-1025-azure

Release files / pypollinations-0.2.0-py3-none-any.whl

Download URL pypollinations-0.2.0-py3-none-any.whl
Size 12.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
3e63db3738816c6eba827e57a4cdba7068e0634410c3b3ffb86f075e41bc90d3
BLAKE2b-256 checksum
How to use checksums
615dfa135dbcc2a2eb50f2c0950bc99342be49b4e0513cf3d04b6871a3bd68df
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.8.5 CPython/3.12.8 Linux/6.5.0-1025-azure

Release history Release notifications | RSS feed

This release

0.2.0 This release

2 release files

0.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page