pypollinations


Namepypollinations JSON
Version 0.2.0 PyPI version JSON
download
home_pageNone
SummaryPython client for Pollinations AI API
upload_time2024-12-14 20:12:08
maintainerNone
docs_urlNone
authorKrishnatejaswi S
requires_python<4.0,>=3.10
licenseApache-2.0
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # pollinations-python

A Python wrapper for accessing Pollinations AI API endpoints.

## Installation

```bash
pip install pypollinations
```

## API documentation

[API documentation](docs/api.md)

## Usage

### Image Generation

#### Code Example
```python
import asyncio
from pypollinations import ImageClient, ImageGenerationRequest
from PIL import Image
from io import BytesIO
```

#### Client Setup and Image Generation
```python
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
```python
        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
```python
        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](./examples/generated_images/image.png)](./examples/generated_images/image.png)

### Text Generation

#### Basic Setup
```python
import asyncio
from pypollinations import TextClient, TextGenerationRequest
from pypollinations.models.base import Message
from pypollinations.exceptions import PollinationsError
```

#### Text Generation Implementation
```python
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
```python
        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
```python
        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

```text
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](LICENSE).

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "pypollinations",
    "maintainer": null,
    "docs_url": null,
    "requires_python": "<4.0,>=3.10",
    "maintainer_email": null,
    "keywords": null,
    "author": "Krishnatejaswi S",
    "author_email": null,
    "download_url": "https://files.pythonhosted.org/packages/80/b4/333a69819ecfc6806420e2d6fc74ffd07ac0312b581d131a2f244db44215/pypollinations-0.2.0.tar.gz",
    "platform": null,
    "description": "# pollinations-python\n\nA Python wrapper for accessing Pollinations AI API endpoints.\n\n## Installation\n\n```bash\npip install pypollinations\n```\n\n## API documentation\n\n[API documentation](docs/api.md)\n\n## Usage\n\n### Image Generation\n\n#### Code Example\n```python\nimport asyncio\nfrom pypollinations import ImageClient, ImageGenerationRequest\nfrom PIL import Image\nfrom io import BytesIO\n```\n\n#### Client Setup and Image Generation\n```python\nasync def generate_image(\n    save_image_path: str = \"./examples/generated_images/\", \n    image_name: str = \"image.png\"\n):\n    client = ImageClient()\n    try:\n        request = ImageGenerationRequest(\n            prompt=\"A beautiful sunset over mountains with snow peaks\",\n            width=1024,\n            height=768,\n            model=\"flux\",\n            nologo=True,\n        )\n        response = await client.generate(request)\n        print(f\"Image URL: {response.url}\")\n        print(f\"Seed: {response.seed}\")\n```\n\n#### Image Saving\n```python\n        image_data = response.image_bytes\n        try:\n            image_data = Image.open(BytesIO(image_data))\n            image_data.save(save_image_path + image_name)\n            print(f\"Image saved to {save_image_path}\")\n        except Exception as e:\n            print(f\"Error: {e}\")\n```\n\n#### Model Listing and Main Execution\n```python\n        models = await client.list_models()\n        print(\"\\nAvailable models:\")\n        print(\"\\n\".join(models))\n\n    except Exception as e:\n        print(f\"Error: {e}\")\n    finally:\n        await client.close()\n\nif __name__ == \"__main__\":\n    asyncio.run(generate_image())\n```\n\n> Output\n> [![Generated Image](./examples/generated_images/image.png)](./examples/generated_images/image.png)\n\n### Text Generation\n\n#### Basic Setup\n```python\nimport asyncio\nfrom pypollinations import TextClient, TextGenerationRequest\nfrom pypollinations.models.base import Message\nfrom pypollinations.exceptions import PollinationsError\n```\n\n#### Text Generation Implementation\n```python\nasync def generate_text():\n    client = TextClient()\n    try:\n        request = TextGenerationRequest(\n            messages=[Message(role=\"user\", content=\"What is artificial intelligence?\")],\n            model=\"openai\",\n            jsonMode=True,\n            seed=41,\n            temperature=0.5,\n            frequency_penalty=0.0,\n            presence_penalty=0.0,\n            top_p=1.0,\n            system=\"You are a helpful AI assistant.\",\n        )\n```\n\n#### Response Handling\n```python\n        print(\"Generating response...\\n\")\n        try:\n            response = await client.generate(request)\n            print(f\"Response: {response.content}\")\n            print(f\"Model: {response.model}\")\n            print(f\"Seed: {response.seed}\")\n            print(f\"Temperature: {response.temperature}\")\n            print(f\"Frequency penalty: {response.frequency_penalty}\")\n            print(f\"Presence penalty: {response.presence_penalty}\")\n            print(f\"Top p: {response.top_p}\")\n```\n\n#### Error Handling and Model Listing\n```python\n        except Exception as e:\n            print(f\"Failed to generate response: {e}\")\n            raise\n\n        print(\"\\nFetching available models...\")\n        try:\n            models = await client.list_models()\n            print(\"\\nAvailable models:\")\n            for model in models:\n                print(f\"- {model['name']}: {model.get('type', 'unknown')}\")\n        except Exception as e:\n            print(f\"Failed to fetch models: {e}\")\n\n    except PollinationsError as e:\n        print(f\"API Error: {e}\")\n    except Exception as e:\n        print(f\"Unexpected error: {type(e).__name__}: {e}\")\n    finally:\n        await client.close()\n\nif __name__ == \"__main__\":\n    asyncio.run(generate_text())\n```\n\n> Output\n\n```text\nGenerating response...\n\nResponse: 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:\n\n1. **Machine Learning (ML)**: A subset of AI that involves training algorithms to learn from data, make predictions, or improve performance over time.\n\n2. **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.\n\n3. **Natural Language Processing (NLP)**: A branch of AI focused on enabling computers to understand, interpret, and generate human language.\n\n4. **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.\n\n5. **Robotics**: AI is used to develop robots that can perform tasks autonomously or with guidance, often incorporating computer vision and other AI subfields.\n\n6. **Expert Systems**: These are AI systems that use knowledge and inference rules to provide explanations or make decisions in specific domains.\n\nAI 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.\nModel: openai\nSeed: 41\nTemperature: 0.5\nFrequency penalty: 0.0\nPresence penalty: 0.0\nTop p: 1.0\n\nFetching available models...\n\nAvailable models:\n- openai: chat\n- mistral: chat\n- mistral-large: chat\n- llama: completion\n- command-r: chat\n- unity: chat\n- midijourney: chat\n- rtist: chat\n- searchgpt: chat\n- evil: chat\n- qwen-coder: chat\n- p1: chat\n```\n\n## Features\n\n- Easy integration with Pollinations AI services\n- Support for various AI models\n- Asynchronous requests support\n\n## License\n\nThis project is licensed under the [Apache License 2.0](LICENSE).\n",
    "bugtrack_url": null,
    "license": "Apache-2.0",
    "summary": "Python client for Pollinations AI API",
    "version": "0.2.0",
    "project_urls": null,
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "615dfa135dbcc2a2eb50f2c0950bc99342be49b4e0513cf3d04b6871a3bd68df",
                "md5": "50976625fadb3e70b4040c3c468590b1",
                "sha256": "3e63db3738816c6eba827e57a4cdba7068e0634410c3b3ffb86f075e41bc90d3"
            },
            "downloads": -1,
            "filename": "pypollinations-0.2.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "50976625fadb3e70b4040c3c468590b1",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": "<4.0,>=3.10",
            "size": 12533,
            "upload_time": "2024-12-14T20:12:06",
            "upload_time_iso_8601": "2024-12-14T20:12:06.649668Z",
            "url": "https://files.pythonhosted.org/packages/61/5d/fa135dbcc2a2eb50f2c0950bc99342be49b4e0513cf3d04b6871a3bd68df/pypollinations-0.2.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "80b4333a69819ecfc6806420e2d6fc74ffd07ac0312b581d131a2f244db44215",
                "md5": "ff0b7723219d51dc4df259623bb262ce",
                "sha256": "03027ce4929514b14a2f4e4457a3a4b23eb40327db7fe08d104f748ead428be7"
            },
            "downloads": -1,
            "filename": "pypollinations-0.2.0.tar.gz",
            "has_sig": false,
            "md5_digest": "ff0b7723219d51dc4df259623bb262ce",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": "<4.0,>=3.10",
            "size": 11425,
            "upload_time": "2024-12-14T20:12:08",
            "upload_time_iso_8601": "2024-12-14T20:12:08.710268Z",
            "url": "https://files.pythonhosted.org/packages/80/b4/333a69819ecfc6806420e2d6fc74ffd07ac0312b581d131a2f244db44215/pypollinations-0.2.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-12-14 20:12:08",
    "github": false,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "lcname": "pypollinations"
}
        
Elapsed time: 1.55292s