Skip to main content

Python client for Pollinations AI API

Project description

pollinations-python

A Python wrapper for accessing Pollinations AI API endpoints.

Installation

pip install pollinations

API documentation

API documentation

Usage

Image Generation

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

async def generate_image(save_image_path: str = './examples/generated_images/',image_name: str = 'image.png'):
    # Initialize client
    client = ImageClient()

    try:
        # Create request
        request = ImageGenerationRequest(
            prompt="A beautiful sunset over mountains with snow peaks",
            width=1024,
            height=768,
            model="flux",
            nologo=True
        )

        # Generate image
        response = await client.generate(request)
        print(f"Image URL: {response.url}")
        print(f"Seed: {response.seed}")
        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}")



        # List available models
        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())

Text Generation

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


async def generate_text():
    # Initialize client
    client = TextClient()

    try:
        request = TextGenerationRequest(
            messages=[
                Message(role="system", content="You are a helpful assistant"),
                Message(role="user", content="What is artificial intelligence?")
            ],
            model="openai",
            jsonMode=True,
            seed=42

        )

        # Generate text
        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}")

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

        # List available models
        print("\nFetching available models...")
        try:
            models = await client.list_models()
            print("\n")
            print(models)
            print("\n")
            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())

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.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pypollinations-0.1.0.tar.gz (9.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pypollinations-0.1.0-py3-none-any.whl (11.1 kB view details)

Uploaded Python 3

File details

Details for the file pypollinations-0.1.0.tar.gz.

File metadata

  • Download URL: pypollinations-0.1.0.tar.gz
  • Upload date:
  • Size: 9.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.5 CPython/3.12.8 Linux/6.5.0-1025-azure

File hashes

Hashes for pypollinations-0.1.0.tar.gz
Algorithm Hash digest
SHA256 d4929fea7e8aac049e9f3a1fecd2188d3ab63eac189a630f86080e575556d3cd
MD5 c9d2e57054692eda5d5d1ffb9fc9393b
BLAKE2b-256 9f59be41babef202c8ca9090fce102f2283f774fd8e4fa94a5136b1472ccd595

See more details on using hashes here.

File details

Details for the file pypollinations-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: pypollinations-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 11.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.8.5 CPython/3.12.8 Linux/6.5.0-1025-azure

File hashes

Hashes for pypollinations-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 8ad706ca2ed9cdd5e7f7c417a30e17538179770aad6f3df0082a0e4ffd6e6431
MD5 8a2622ad4f3471646df0c84536d0128c
BLAKE2b-256 f6ffe2807c2815739c71a122fc1b5543b41ee8a1d910c5026d455b8779331d7c

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page