aisearchapi-client


Nameaisearchapi-client JSON
Version 1.0.3 PyPI version JSON
download
home_pagehttps://github.com/aisearchapi/aisearchapi-python
SummaryPython client library for AI Search API - search and retrieve intelligent responses with context awareness
upload_time2025-08-25 18:57:28
maintainerNone
docs_urlNone
authorAI Search API
requires_python>=3.8
licenseMIT License Copyright (c) 2025 aisearchapi Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
keywords ai search api llm embeddings semantic-search machine-learning
VCS
bugtrack_url
requirements requests typing-extensions
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # AI Search API Python Client

[![PyPI version](https://badge.fury.io/py/aisearchapi.svg)](https://badge.fury.io/py/aisearchapi-client)
[![Python Support](https://img.shields.io/pypi/pyversions/aisearchapi.svg)](https://pypi.org/project/aisearchapi-client/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

A Python client library for the AI Search API that provides intelligent search capabilities with context awareness and semantic understanding.

## Features

- **🔍 Intelligent Search**: Leverage advanced embedding techniques for semantic search
- **🎯 Context Awareness**: Provide conversation context to enhance search results
- **⚡ Simple API**: Easy-to-use interface with comprehensive error handling
- **🛡️ Type Safe**: Full type hints support for better development experience
- **🔄 Flexible Responses**: Support for both text and markdown formatted responses
- **💰 Balance Tracking**: Check your API credit usage

## Installation

Install the package using pip:

```bash
pip install aisearchapi-client
```

Or install from source:

```bash
git clone https://github.com/aisearchapi/aisearchapi-python.git
cd aisearchapi-python
pip install -e .
```

<!-- For development with optional dependencies: -->

<!-- ```bash
pip install -e ".[dev,test]"
``` -->

## Quick Start

### Basic Usage

```python
from aisearchapi_client import AISearchAPIClient

# Initialize the client
client = AISearchAPIClient(api_key='your-api-key-here')

# Perform a basic search
result = client.search(
    prompt='What is machine learning and how does it work?',
    response_type='markdown'
)

print("Answer:", result.answer)
print("Sources:", result.sources)
print(f"Total time: {result.total_time}ms")

# Check your account balance
balance = client.balance()
print(f"Available credits: {balance.available_credits}")

# Always close the client when done
client.close()
```

### Using Context Manager (Recommended)

```python
from aisearchapi_client import AISearchAPIClient, ChatMessage

# Use context manager for automatic resource cleanup
with AISearchAPIClient(api_key='your-api-key-here') as client:
    
    # Search with conversation context
    result = client.search(
        prompt='What are the main advantages and disadvantages?',
        context=[
            ChatMessage(role='user', content='I am researching solar energy for my home'),
            ChatMessage(role='user', content='I live in a sunny climate with high electricity costs')
        ],
        response_type='text'
    )
    
    print("Contextual Answer:", result.answer)
```

### Advanced Configuration

```python
from aisearchapi_client import AISearchAPIClient

client = AISearchAPIClient(
    api_key='your-api-key-here',
    base_url='https://api.aisearchapi.io',  # Custom base URL
    timeout=60  # Custom timeout in seconds
)
```

## API Reference

### `AISearchAPIClient`

#### Constructor

```python
AISearchAPIClient(
    api_key: str,
    base_url: str = "https://api.aisearchapi.io",
    timeout: int = 30
)
```

- **api_key** (str): Your API bearer token
- **base_url** (str, optional): Base URL for the API endpoints
- **timeout** (int, optional): Request timeout in seconds

#### Methods

##### `search(prompt, context=None, response_type=None)`

Perform an AI-powered search with optional conversation context.

**Parameters:**
- **prompt** (str): The main search query
- **context** (List[ChatMessage], optional): Conversation context for enhanced understanding
- **response_type** (str, optional): Response format ('text' or 'markdown')

**Returns:**
- **SearchResponse**: Object containing answer, sources, response_type, and total_time

**Example:**
```python
result = client.search(
    prompt='Explain quantum computing',
    context=[ChatMessage(role='user', content='I am a computer science student')],
    response_type='markdown'
)
```

##### `balance()`

Check your current account balance and available API credits.

**Returns:**
- **BalanceResponse**: Object containing available_credits

**Example:**
```python
balance = client.balance()
if balance.available_credits < 10:
    print("Warning: Low credit balance!")
```

### Data Classes

#### `ChatMessage`

```python
@dataclass
class ChatMessage:
    role: str  # Currently only 'user' is supported
    content: str  # The message content
```

#### `SearchResponse`

```python
@dataclass
class SearchResponse:
    answer: str  # AI-generated response
    sources: List[str]  # List of sources used
    response_type: str  # Format of the response
    total_time: int  # Processing time in milliseconds
```

#### `BalanceResponse`

```python
@dataclass
class BalanceResponse:
    available_credits: int  # Number of available API credits
```

## Error Handling

The client provides comprehensive error handling with custom exception types:

```python
from aisearchapi_client import AISearchAPIClient, AISearchAPIError

try:
    with AISearchAPIClient(api_key='your-api-key') as client:
        result = client.search(prompt='Your search query')
        print(result.answer)
        
except AISearchAPIError as e:
    print(f"API Error [{e.status_code}]: {e.description}")
    if e.response:
        print("Response data:", e.response)
        
except ValueError as e:
    print(f"Validation Error: {e}")
    
except Exception as e:
    print(f"Unexpected error: {e}")
```

## Error Codes

| Status Code | Error Type | Description |
|------------|------------|-------------|
| 401 | Unauthorized | Invalid API key |
| 429 | Too Many Requests | Rate limit exceeded |
| 433 | Quota Exceeded | Account message quota reached |
| 500 | Server Error | Internal server error |
| 503 | Service Unavailable | API temporarily down |

## Environment Variables

You can set your API key using environment variables:

```bash
export AI_SEARCH_API_KEY="your-api-key-here"
```

Then use it in your code:

```python
import os
from aisearchapi_client import AISearchAPIClient

api_key = os.getenv('AI_SEARCH_API_KEY')
client = AISearchAPIClient(api_key=api_key)
```

## Examples

Check out the [examples](examples/) directory for more comprehensive usage examples:

- [contextual_search.py](examples/contextual_search.py) - Using conversation context
- [error_handling.py](examples/error_handling.py) - Comprehensive error handling
- [async_usage.py](examples/async_usage.py) - Async/await patterns

## Requirements

- Python 3.8 or higher
- requests >= 2.25.0
- typing-extensions >= 4.0.0 (for Python < 3.10)

## Development

### Setting up for development

```bash
git clone https://github.com/aisearchapi/aisearchapi-python.git
cd aisearchapi-python

# Create virtual environment
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

# Install in development mode with all dependencies
pip install -e ".[dev,test]"
```

### Running tests

```bash
pytest
```

### Code formatting

```bash
# Format code
black .
isort .

# Lint code  
flake8 .
mypy .
```

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## Support

- **Documentation**: [https://docs.aisearchapi.io/](https://docs.aisearchapi.io)
- **Issues**: [GitHub Issues](https://github.com/aisearchapi/aisearchapi-python/issues)
- **Email**: admin@aisearchapi.io

## Changelog

## Acknowledgments

- Built with [requests](https://requests.readthedocs.io/) for HTTP handling
- Type hints support with [typing-extensions](https://github.com/python/typing_extensions)
- Inspired by modern API client design patterns

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/aisearchapi/aisearchapi-python",
    "name": "aisearchapi-client",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": "AI Search API <admin@aisearchapi.io>",
    "keywords": "ai, search, api, llm, embeddings, semantic-search, machine-learning",
    "author": "AI Search API",
    "author_email": "AI Search API <admin@aisearchapi.io>",
    "download_url": "https://files.pythonhosted.org/packages/f5/d0/511c068a904b88cd45872152cc93215f88db0f0ae53ec00ee5a8742ff109/aisearchapi_client-1.0.3.tar.gz",
    "platform": null,
    "description": "# AI Search API Python Client\n\n[![PyPI version](https://badge.fury.io/py/aisearchapi.svg)](https://badge.fury.io/py/aisearchapi-client)\n[![Python Support](https://img.shields.io/pypi/pyversions/aisearchapi.svg)](https://pypi.org/project/aisearchapi-client/)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n\nA Python client library for the AI Search API that provides intelligent search capabilities with context awareness and semantic understanding.\n\n## Features\n\n- **\ud83d\udd0d Intelligent Search**: Leverage advanced embedding techniques for semantic search\n- **\ud83c\udfaf Context Awareness**: Provide conversation context to enhance search results\n- **\u26a1 Simple API**: Easy-to-use interface with comprehensive error handling\n- **\ud83d\udee1\ufe0f Type Safe**: Full type hints support for better development experience\n- **\ud83d\udd04 Flexible Responses**: Support for both text and markdown formatted responses\n- **\ud83d\udcb0 Balance Tracking**: Check your API credit usage\n\n## Installation\n\nInstall the package using pip:\n\n```bash\npip install aisearchapi-client\n```\n\nOr install from source:\n\n```bash\ngit clone https://github.com/aisearchapi/aisearchapi-python.git\ncd aisearchapi-python\npip install -e .\n```\n\n<!-- For development with optional dependencies: -->\n\n<!-- ```bash\npip install -e \".[dev,test]\"\n``` -->\n\n## Quick Start\n\n### Basic Usage\n\n```python\nfrom aisearchapi_client import AISearchAPIClient\n\n# Initialize the client\nclient = AISearchAPIClient(api_key='your-api-key-here')\n\n# Perform a basic search\nresult = client.search(\n    prompt='What is machine learning and how does it work?',\n    response_type='markdown'\n)\n\nprint(\"Answer:\", result.answer)\nprint(\"Sources:\", result.sources)\nprint(f\"Total time: {result.total_time}ms\")\n\n# Check your account balance\nbalance = client.balance()\nprint(f\"Available credits: {balance.available_credits}\")\n\n# Always close the client when done\nclient.close()\n```\n\n### Using Context Manager (Recommended)\n\n```python\nfrom aisearchapi_client import AISearchAPIClient, ChatMessage\n\n# Use context manager for automatic resource cleanup\nwith AISearchAPIClient(api_key='your-api-key-here') as client:\n    \n    # Search with conversation context\n    result = client.search(\n        prompt='What are the main advantages and disadvantages?',\n        context=[\n            ChatMessage(role='user', content='I am researching solar energy for my home'),\n            ChatMessage(role='user', content='I live in a sunny climate with high electricity costs')\n        ],\n        response_type='text'\n    )\n    \n    print(\"Contextual Answer:\", result.answer)\n```\n\n### Advanced Configuration\n\n```python\nfrom aisearchapi_client import AISearchAPIClient\n\nclient = AISearchAPIClient(\n    api_key='your-api-key-here',\n    base_url='https://api.aisearchapi.io',  # Custom base URL\n    timeout=60  # Custom timeout in seconds\n)\n```\n\n## API Reference\n\n### `AISearchAPIClient`\n\n#### Constructor\n\n```python\nAISearchAPIClient(\n    api_key: str,\n    base_url: str = \"https://api.aisearchapi.io\",\n    timeout: int = 30\n)\n```\n\n- **api_key** (str): Your API bearer token\n- **base_url** (str, optional): Base URL for the API endpoints\n- **timeout** (int, optional): Request timeout in seconds\n\n#### Methods\n\n##### `search(prompt, context=None, response_type=None)`\n\nPerform an AI-powered search with optional conversation context.\n\n**Parameters:**\n- **prompt** (str): The main search query\n- **context** (List[ChatMessage], optional): Conversation context for enhanced understanding\n- **response_type** (str, optional): Response format ('text' or 'markdown')\n\n**Returns:**\n- **SearchResponse**: Object containing answer, sources, response_type, and total_time\n\n**Example:**\n```python\nresult = client.search(\n    prompt='Explain quantum computing',\n    context=[ChatMessage(role='user', content='I am a computer science student')],\n    response_type='markdown'\n)\n```\n\n##### `balance()`\n\nCheck your current account balance and available API credits.\n\n**Returns:**\n- **BalanceResponse**: Object containing available_credits\n\n**Example:**\n```python\nbalance = client.balance()\nif balance.available_credits < 10:\n    print(\"Warning: Low credit balance!\")\n```\n\n### Data Classes\n\n#### `ChatMessage`\n\n```python\n@dataclass\nclass ChatMessage:\n    role: str  # Currently only 'user' is supported\n    content: str  # The message content\n```\n\n#### `SearchResponse`\n\n```python\n@dataclass\nclass SearchResponse:\n    answer: str  # AI-generated response\n    sources: List[str]  # List of sources used\n    response_type: str  # Format of the response\n    total_time: int  # Processing time in milliseconds\n```\n\n#### `BalanceResponse`\n\n```python\n@dataclass\nclass BalanceResponse:\n    available_credits: int  # Number of available API credits\n```\n\n## Error Handling\n\nThe client provides comprehensive error handling with custom exception types:\n\n```python\nfrom aisearchapi_client import AISearchAPIClient, AISearchAPIError\n\ntry:\n    with AISearchAPIClient(api_key='your-api-key') as client:\n        result = client.search(prompt='Your search query')\n        print(result.answer)\n        \nexcept AISearchAPIError as e:\n    print(f\"API Error [{e.status_code}]: {e.description}\")\n    if e.response:\n        print(\"Response data:\", e.response)\n        \nexcept ValueError as e:\n    print(f\"Validation Error: {e}\")\n    \nexcept Exception as e:\n    print(f\"Unexpected error: {e}\")\n```\n\n## Error Codes\n\n| Status Code | Error Type | Description |\n|------------|------------|-------------|\n| 401 | Unauthorized | Invalid API key |\n| 429 | Too Many Requests | Rate limit exceeded |\n| 433 | Quota Exceeded | Account message quota reached |\n| 500 | Server Error | Internal server error |\n| 503 | Service Unavailable | API temporarily down |\n\n## Environment Variables\n\nYou can set your API key using environment variables:\n\n```bash\nexport AI_SEARCH_API_KEY=\"your-api-key-here\"\n```\n\nThen use it in your code:\n\n```python\nimport os\nfrom aisearchapi_client import AISearchAPIClient\n\napi_key = os.getenv('AI_SEARCH_API_KEY')\nclient = AISearchAPIClient(api_key=api_key)\n```\n\n## Examples\n\nCheck out the [examples](examples/) directory for more comprehensive usage examples:\n\n- [contextual_search.py](examples/contextual_search.py) - Using conversation context\n- [error_handling.py](examples/error_handling.py) - Comprehensive error handling\n- [async_usage.py](examples/async_usage.py) - Async/await patterns\n\n## Requirements\n\n- Python 3.8 or higher\n- requests >= 2.25.0\n- typing-extensions >= 4.0.0 (for Python < 3.10)\n\n## Development\n\n### Setting up for development\n\n```bash\ngit clone https://github.com/aisearchapi/aisearchapi-python.git\ncd aisearchapi-python\n\n# Create virtual environment\npython -m venv venv\nsource venv/bin/activate  # On Windows: venv\\Scripts\\activate\n\n# Install in development mode with all dependencies\npip install -e \".[dev,test]\"\n```\n\n### Running tests\n\n```bash\npytest\n```\n\n### Code formatting\n\n```bash\n# Format code\nblack .\nisort .\n\n# Lint code  \nflake8 .\nmypy .\n```\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n## Support\n\n- **Documentation**: [https://docs.aisearchapi.io/](https://docs.aisearchapi.io)\n- **Issues**: [GitHub Issues](https://github.com/aisearchapi/aisearchapi-python/issues)\n- **Email**: admin@aisearchapi.io\n\n## Changelog\n\n## Acknowledgments\n\n- Built with [requests](https://requests.readthedocs.io/) for HTTP handling\n- Type hints support with [typing-extensions](https://github.com/python/typing_extensions)\n- Inspired by modern API client design patterns\n",
    "bugtrack_url": null,
    "license": "MIT License\n        \n        Copyright (c) 2025 aisearchapi\n        \n        Permission is hereby granted, free of charge, to any person obtaining a copy\n        of this software and associated documentation files (the \"Software\"), to deal\n        in the Software without restriction, including without limitation the rights\n        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n        copies of the Software, and to permit persons to whom the Software is\n        furnished to do so, subject to the following conditions:\n        \n        The above copyright notice and this permission notice shall be included in all\n        copies or substantial portions of the Software.\n        \n        THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n        SOFTWARE.",
    "summary": "Python client library for AI Search API - search and retrieve intelligent responses with context awareness",
    "version": "1.0.3",
    "project_urls": {
        "Changelog": "https://github.com/aisearchapi/aisearchapi-python/blob/main/CHANGELOG.md",
        "Documentation": "https://aisearchapi.readthedocs.io/",
        "Homepage": "https://github.com/aisearchapi/aisearchapi-python",
        "Issues": "https://github.com/aisearchapi/aisearchapi-python/issues",
        "Repository": "https://github.com/aisearchapi/aisearchapi-python"
    },
    "split_keywords": [
        "ai",
        " search",
        " api",
        " llm",
        " embeddings",
        " semantic-search",
        " machine-learning"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "0b93e749190fb3851a60a4c73c44e42a73cf5401a2bad0563448a35424b6c54d",
                "md5": "8a7b396a0c6d9f1cc939f53321ab23af",
                "sha256": "be0c1df70b66405e7002c82b448529d0431ba95e79ee791f7ddada1a6c117cfd"
            },
            "downloads": -1,
            "filename": "aisearchapi_client-1.0.3-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "8a7b396a0c6d9f1cc939f53321ab23af",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 10475,
            "upload_time": "2025-08-25T18:57:27",
            "upload_time_iso_8601": "2025-08-25T18:57:27.220294Z",
            "url": "https://files.pythonhosted.org/packages/0b/93/e749190fb3851a60a4c73c44e42a73cf5401a2bad0563448a35424b6c54d/aisearchapi_client-1.0.3-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "f5d0511c068a904b88cd45872152cc93215f88db0f0ae53ec00ee5a8742ff109",
                "md5": "12753988981afe5373770e4e9b1edfc9",
                "sha256": "54e20faf8a8203cf9738e4a50be3d16b6267f40a9dbfbf79de0eb8ed88d2d6ed"
            },
            "downloads": -1,
            "filename": "aisearchapi_client-1.0.3.tar.gz",
            "has_sig": false,
            "md5_digest": "12753988981afe5373770e4e9b1edfc9",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 13178,
            "upload_time": "2025-08-25T18:57:28",
            "upload_time_iso_8601": "2025-08-25T18:57:28.107568Z",
            "url": "https://files.pythonhosted.org/packages/f5/d0/511c068a904b88cd45872152cc93215f88db0f0ae53ec00ee5a8742ff109/aisearchapi_client-1.0.3.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-08-25 18:57:28",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "aisearchapi",
    "github_project": "aisearchapi-python",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "requirements": [
        {
            "name": "requests",
            "specs": [
                [
                    ">=",
                    "2.25.0"
                ]
            ]
        },
        {
            "name": "typing-extensions",
            "specs": [
                [
                    ">=",
                    "4.0.0"
                ]
            ]
        }
    ],
    "lcname": "aisearchapi-client"
}
        
Elapsed time: 2.24194s