medisearch-client


Namemedisearch-client JSON
Version 0.3.8 PyPI version JSON
download
home_pagehttps://github.com/MediSearch/medisearch_client_python
SummaryA Python client for the MediSearch medical information API
upload_time2025-02-28 21:03:41
maintainerNone
docs_urlNone
authorMichal Pandy
requires_python>=3.7
licenseNone
keywords medical healthcare api search research medisearch
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # MediSearch API Client

<div align="center">
  <h3>Python client for interacting with the <a href="https://medisearch.io/developers">MediSearch API</a></h3>
</div>

## Overview

The **MediSearch API Client** provides a Python interface to the [MediSearch API](https://medisearch.io/developers), enabling developers to integrate MediSearch into their applications. The client supports both synchronous and asynchronous operations, real-time streaming responses, and customizable search parameters.

### Key Features

- **Medical Knowledge**: Access evidence-based medical information from peer-reviewed journals, health guidelines, and trusted sources
- **Synchronous & Asynchronous APIs**: Choose between blocking and non-blocking requests
- **Real-time Streaming**: Get responses as they are generated
- **Customizable Filters**: Refine searches by source type, publication year, and more
- **Multilingual Support**: Interact with the API in multiple languages
- **Conversation Context**: Maintain context across multiple turns of conversation
- **Pro Answers**: Use the [MediSearch Pro](https://medisearch.io/announcements/pro_release) model to generate answers

## Installation

```bash
pip install medisearch-client
```

## Core Concepts

The MediSearch client architecture consists of several key components:

1. **MediSearchClient**: Main client class handling API communication
2. **Settings**: Configuration for language preferences and model selection
3. **Filters**: Criteria for refining search results
4. **ResponseHandler**: Callbacks for processing different response types

The API uses an event-based communication model with the following event types:
- **llm_response**: Text content from the AI
- **articles**: Bibliographic information about source articles
- **error**: Error conditions with associated error codes

## Authentication

The MediSearch API uses API key authentication:

```python
from medisearch_client import MediSearchClient

# Initialize with your API key
client = MediSearchClient(api_key="your_api_key_here")
```

You can obtain an API key from the [MediSearch Developer Portal](https://medisearch.io/developers).

## Quick Start

```python
from medisearch_client import MediSearchClient

# Initialize client
client = MediSearchClient(api_key="your_api_key")

# Send a query
responses = client.send_message(
    conversation=["What are the symptoms of type 2 diabetes?"],
    conversation_id="diabetes-symptoms-query"
)

# Process responses
for response in responses:
    if response["event"] == "llm_response":
        print("Answer:", response["data"])
    elif response["event"] == "articles":
        print(f"Sources: {len(response['data'])} articles found")
        for i, article in enumerate(response['data'][:3], 1):
            print(f"{i}. {article['title']} ({article.get('year', 'N/A')})")
```

## Basic Usage


### Simple Query Example

```python
from medisearch_client import MediSearchClient

client = MediSearchClient(api_key="your_api_key")

# Send a medical query
responses = client.send_message(
    conversation=["What are the common symptoms of type 2 diabetes?"],
    conversation_id="diabetes-symptoms-query"
)

# Process the responses
for response in responses:
    if response["event"] == "llm_response":
        print("Answer:", response["data"])
    elif response["event"] == "articles":
        print(f"Sources ({len(response['data'])} articles):")
        for i, article in enumerate(response['data'][:3], 1):
            print(f"{i}. {article['title']})
```

### Parameter Explanation

- **conversation**: List of strings representing the conversation history
- **conversation_id**: Unique identifier for the conversation
- **should_stream_response**: Boolean to enable/disable streaming (default: False)
- **settings**: Optional Settings object for language, model type, and filters
- **response_handler**: Optional ResponseHandler for custom callbacks

## Advanced Usage

### Conversation Management

The `conversation` parameter is a list of strings where user and AI messages alternate, with the user's message always being the last.

**Important**: Always use the same conversation ID for all messages in a single conversation. This maintains both conversation context and article context on the backend, ensuring relevant medical information is preserved across multiple turns.

```python
import uuid
from medisearch_client import MediSearchClient

client = MediSearchClient(api_key="your_api_key")

# Generate a unique UUID for the conversation
conversation_id = str(uuid.uuid4())  # e.g., "f47ac10b-58cc-4372-a567-0e02b2c3d479"
conversation = ["What are the symptoms of type 2 diabetes?"]

# Send the first message
first_responses = client.send_message(
    conversation=conversation,
    conversation_id=conversation_id
)

# Extract the AI's response
ai_response = None
for response in first_responses:
    if response["event"] == "llm_response":
        ai_response = response["data"]

# Follow-up question
if ai_response:
    conversation.append(ai_response)
    conversation.append("How is it diagnosed?")
    
    # Send the follow-up question with the SAME conversation_id
    followup_responses = client.send_message(
        conversation=conversation,
        conversation_id=conversation_id
    )
```

### Streaming Responses

Streaming provides real-time feedback while responses are being generated.

```python
from medisearch_client import MediSearchClient

client = MediSearchClient(api_key="your_api_key")

print("Response: ", end="", flush=True)

# Enable streaming with should_stream_response=True
for response in client.send_message(
    conversation=["What are the treatment options for COVID-19?"],
    conversation_id="covid-treatment-stream",
    should_stream_response=True
):
    if response["event"] == "llm_response":
        # Print each chunk as it arrives
        print(response["data"], end="", flush=True)
    elif response["event"] == "articles":
        print(f"\n\nBased on {len(response['data'])} medical sources")
```

### Asynchronous Operations

For non-blocking operations, use the asynchronous methods.

```python
import asyncio
from medisearch_client import MediSearchClient

async def medical_query():
    client = MediSearchClient(api_key="your_api_key")
    
    # Async request
    responses = await client.send_message_async(
        conversation=["What are the cardiovascular effects of COVID-19?"],
        conversation_id="covid-cardio-async"
    )
    
    # Process responses
    for response in responses:
        if response["event"] == "llm_response":
            print(f"Answer: {response['data'][:100]}...")

# Run the async function
asyncio.run(medical_query())
```

#### Async Streaming

```python
import asyncio
from medisearch_client import MediSearchClient

async def stream_response():
    client = MediSearchClient(api_key="your_api_key")
    
    print("Response: ", end="", flush=True)
    
    # Get streaming response asynchronously
    response_stream = await client.send_message_async(
        conversation=["What are the side effects of statins?"],
        conversation_id="statin-side-effects",
        should_stream_response=True
    )
    
    # Process streaming response
    async for response in response_stream:
        if response["event"] == "llm_response":
            print(response["data"], end="", flush=True)
        elif response["event"] == "articles":
            print(f"\n\nBased on {len(response['data'])} medical sources")

# Run the async streaming function
asyncio.run(stream_response())
```

### Response Handlers

Response handlers provide a way to process different types of responses with custom callbacks.

```python
from medisearch_client import MediSearchClient, ResponseHandler

client = MediSearchClient(api_key="your_api_key")

# Track the accumulated response
accumulated_response = ""
article_count = 0

# Define handler functions
def handle_llm_response(response):
    global accumulated_response
    chunk = response["data"]
    accumulated_response += chunk
    print(chunk, end="", flush=True)

def handle_articles(response):
    global article_count
    articles = response["data"]
    article_count = len(articles)
    print(f"\n\nFound {article_count} relevant medical articles")

def handle_error(response):
    error_code = response["data"]
    print(f"\nError occurred: {error_code}")

# Create response handler
handler = ResponseHandler(
    on_llm_response=handle_llm_response,
    on_articles=handle_articles,
    on_error=handle_error
)

# Send message with the response handler
client.send_message(
    conversation=["What are recent advances in breast cancer treatment?"],
    conversation_id="breast-cancer-treatment",
    response_handler=handler
)
```

### Working with Filters

The `Filters` class allows you to customize search behavior for more targeted results.

```python
from medisearch_client import MediSearchClient, Filters, Settings

client = MediSearchClient(api_key="your_api_key")

# Create filters
filters = Filters(
    # Specify which sources to search
    sources=[
        "scientificArticles",      # Peer-reviewed scientific literature
        "internationalHealthGuidelines"  # Guidelines from health organizations
    ],
    # Limit to recent publications
    year_start=2020,
    year_end=2023,
    # Only include high-quality sources
    only_high_quality=True,
    # Specific article types
    article_types=[
        "metaAnalysis",   # Meta-analyses
        "clinicalTrials"  # Clinical trials
    ]
)

# Apply filters through settings
settings = Settings(
    language="English",
    filters=filters,
    model_type="pro"  # Use the professional model
)

# Send a message with custom settings
responses = client.send_message(
    conversation=["What are the latest advancements in Alzheimer's treatment?"],
    conversation_id=str(uuid.uuid4()),
    settings=settings
)
```

#### Available Source Types

- `scientificArticles`: Peer-reviewed scientific literature
- `internationalHealthGuidelines`: Guidelines from international health organizations
- `medicineGuidelines`: Guidelines related to drugs
- `healthline`: Content from Healthline
- `books`: Medical textbooks and references

#### Article Types for Scientific Articles

- `metaAnalysis`: Meta-analyses that combine results from multiple studies
- `reviews`: Review articles that summarize current knowledge
- `clinicalTrials`: Reports of clinical trials
- `other`: Other types of scientific articles

#### Year Filtering Options

The year filters allow you to specify the publication date range:

- `year_start`: The earliest publication year to include (e.g., 2018)
- `year_end`: The latest publication year to include (e.g., 2023)

These filters are particularly useful for:
- Finding the most recent research on rapidly evolving topics
- Excluding outdated medical information
- Focusing on specific time periods for historical research

#### High Quality Option

The `only_high_quality` parameter (default: False) determines whether to restrict results to high-quality sources:

- When set to `True`: Only includes articles from reputable journals with high citation indices and recognized health guidelines
- When set to `False`: Includes a broader range of sources

This option is useful when you need the most authoritative information for clinical decision support.

### Language Support

MediSearch supports queries in any language without constraints:

```python
from medisearch_client import MediSearchClient, Settings

client = MediSearchClient(api_key="your_api_key")

# Create language-specific settings
settings = Settings(language="Spanish")

# Send query in Spanish
responses = client.send_message(
    conversation=["¿Cuáles son los síntomas de la diabetes?"],
    conversation_id=str(uuid.uuid4()),
    settings=settings
)
```

The MediSearch API can process queries in any language and will respond in the same language as the query. There are no restrictions on supported languages, making it suitable for global applications.

### Model Selection

MediSearch offers two model types that correspond directly to those available on the MediSearch.io platform:

```python
from medisearch_client import MediSearchClient, Settings

client = MediSearchClient(api_key="your_api_key")

# Use standard model
settings = Settings(model_type="standard")
responses = client.send_message(
    conversation=["What are the treatments for rheumatoid arthritis?"],
    conversation_id=str(uuid.uuid4()),
    settings=settings
)
```

Model options:
- `pro`: Enhanced model with advanced capabilities - identical to the Pro model on medisearch.io
- `standard`: Standard model suitable for most queries (default) - identical to the Standard model on medisearch.io

The Pro model offers more comprehensive answers with deeper medical insights, while the Standard model provides solid medical information for common queries at potentially faster response times.

## Response Structure

The MediSearch API returns responses with three main event types:

### LLM Response Event

Contains text content generated by the AI:

```json
{
  "event": "llm_response",
  "data": "Text content from the AI..."
}
```

In streaming mode, multiple `llm_response` events will be received as chunks. In non-streaming mode, you'll receive a list that will contain a single consolidated `llm_response` event.

### Articles Event

Contains bibliographic information about source articles, ordered by citation index (more authoritative sources appear first):

```json
{
  "event": "articles",
  "data": [
    {
      "title": "Article Title",
      "authors": ["Author 1", "Author 2"],
      "year": 2023,
      "journal": "Journal Name",
      "url": "https://example.com/article",
      "score": 0.92,
      "article_type": "metaAnalysis"
    },
    ...
  ]
}
```

The articles are automatically sorted by the model's citation index. 

### Error Event

Indicates an error condition with the following structure:

```json
{
  "event": "error",
  "id": "conversation_id",
  "data": "error_code_here"
}
```

The `id` field contains the conversation ID that was used in the request, and the `data` field contains the specific error code.

## Error Handling

The MediSearch API may return error events in various situations:

### Error Event Codes

- `error_not_enough_articles`: Not enough relevant articles found. Try rephrasing the question to be more medical in nature or more specific.
- `error_out_of_tokens`: Conversation exceeded maximum allowed length. Start a new conversation or simplify your query.
- `error_internal`: Internal server error that occurred during processing.
- `error_llm`: Error occurred in the language model processing.

### HTTP Errors

Other errors (like authentication issues, rate limiting, etc.) are returned as standard HTTP errors over SSE, not as error events. These include:

- 403: Unable to query due to authentication issues
- 429: Rate limit exceeded
- 500: General server error

### Error Handling Example

```python
from medisearch_client import MediSearchClient

client = MediSearchClient(api_key="your_api_key")

try:
    responses = client.send_message(
        conversation=["What are the best treatments for seasonal allergies?"],
        conversation_id=str(uuid.uuid4())
    )
    
    for response in responses:
        if response["event"] == "error":
            error_code = response["data"]
            if error_code == "error_not_enough_articles":
                print("Not enough medical articles found. Try a more specific question.")
            elif error_code == "error_out_of_tokens":
                print("Conversation is too long. Please start a new one.")
            elif error_code == "error_internal":
                print("Internal server error occurred. Please try again later.")
            elif error_code == "error_llm":
                print("Language model processing error. Please try rephrasing your question.")
            else:
                print(f"An error occurred: {error_code}")
        elif response["event"] == "llm_response":
            print("Answer:", response["data"])
except Exception as e:
    # Handle HTTP errors here
    print(f"Request failed: {str(e)}")
```

## License

MIT License - See LICENSE file for details.

For help or questions, contact us at [founders@medisearch.io](mailto:founders@medisearch.io).

For detailed API documentation, visit [MediSearch API Docs](https://medisearch.io/developers).

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/MediSearch/medisearch_client_python",
    "name": "medisearch-client",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.7",
    "maintainer_email": null,
    "keywords": "medical, healthcare, api, search, research, medisearch",
    "author": "Michal Pandy",
    "author_email": "founders@medisearch.io",
    "download_url": "https://files.pythonhosted.org/packages/c2/01/81239b82339d4c1f1de50a01101e6bf44cb011f79f3a814d0fed4eafe95a/medisearch_client-0.3.8.tar.gz",
    "platform": null,
    "description": "# MediSearch API Client\n\n<div align=\"center\">\n  <h3>Python client for interacting with the <a href=\"https://medisearch.io/developers\">MediSearch API</a></h3>\n</div>\n\n## Overview\n\nThe **MediSearch API Client** provides a Python interface to the [MediSearch API](https://medisearch.io/developers), enabling developers to integrate MediSearch into their applications. The client supports both synchronous and asynchronous operations, real-time streaming responses, and customizable search parameters.\n\n### Key Features\n\n- **Medical Knowledge**: Access evidence-based medical information from peer-reviewed journals, health guidelines, and trusted sources\n- **Synchronous & Asynchronous APIs**: Choose between blocking and non-blocking requests\n- **Real-time Streaming**: Get responses as they are generated\n- **Customizable Filters**: Refine searches by source type, publication year, and more\n- **Multilingual Support**: Interact with the API in multiple languages\n- **Conversation Context**: Maintain context across multiple turns of conversation\n- **Pro Answers**: Use the [MediSearch Pro](https://medisearch.io/announcements/pro_release) model to generate answers\n\n## Installation\n\n```bash\npip install medisearch-client\n```\n\n## Core Concepts\n\nThe MediSearch client architecture consists of several key components:\n\n1. **MediSearchClient**: Main client class handling API communication\n2. **Settings**: Configuration for language preferences and model selection\n3. **Filters**: Criteria for refining search results\n4. **ResponseHandler**: Callbacks for processing different response types\n\nThe API uses an event-based communication model with the following event types:\n- **llm_response**: Text content from the AI\n- **articles**: Bibliographic information about source articles\n- **error**: Error conditions with associated error codes\n\n## Authentication\n\nThe MediSearch API uses API key authentication:\n\n```python\nfrom medisearch_client import MediSearchClient\n\n# Initialize with your API key\nclient = MediSearchClient(api_key=\"your_api_key_here\")\n```\n\nYou can obtain an API key from the [MediSearch Developer Portal](https://medisearch.io/developers).\n\n## Quick Start\n\n```python\nfrom medisearch_client import MediSearchClient\n\n# Initialize client\nclient = MediSearchClient(api_key=\"your_api_key\")\n\n# Send a query\nresponses = client.send_message(\n    conversation=[\"What are the symptoms of type 2 diabetes?\"],\n    conversation_id=\"diabetes-symptoms-query\"\n)\n\n# Process responses\nfor response in responses:\n    if response[\"event\"] == \"llm_response\":\n        print(\"Answer:\", response[\"data\"])\n    elif response[\"event\"] == \"articles\":\n        print(f\"Sources: {len(response['data'])} articles found\")\n        for i, article in enumerate(response['data'][:3], 1):\n            print(f\"{i}. {article['title']} ({article.get('year', 'N/A')})\")\n```\n\n## Basic Usage\n\n\n### Simple Query Example\n\n```python\nfrom medisearch_client import MediSearchClient\n\nclient = MediSearchClient(api_key=\"your_api_key\")\n\n# Send a medical query\nresponses = client.send_message(\n    conversation=[\"What are the common symptoms of type 2 diabetes?\"],\n    conversation_id=\"diabetes-symptoms-query\"\n)\n\n# Process the responses\nfor response in responses:\n    if response[\"event\"] == \"llm_response\":\n        print(\"Answer:\", response[\"data\"])\n    elif response[\"event\"] == \"articles\":\n        print(f\"Sources ({len(response['data'])} articles):\")\n        for i, article in enumerate(response['data'][:3], 1):\n            print(f\"{i}. {article['title']})\n```\n\n### Parameter Explanation\n\n- **conversation**: List of strings representing the conversation history\n- **conversation_id**: Unique identifier for the conversation\n- **should_stream_response**: Boolean to enable/disable streaming (default: False)\n- **settings**: Optional Settings object for language, model type, and filters\n- **response_handler**: Optional ResponseHandler for custom callbacks\n\n## Advanced Usage\n\n### Conversation Management\n\nThe `conversation` parameter is a list of strings where user and AI messages alternate, with the user's message always being the last.\n\n**Important**: Always use the same conversation ID for all messages in a single conversation. This maintains both conversation context and article context on the backend, ensuring relevant medical information is preserved across multiple turns.\n\n```python\nimport uuid\nfrom medisearch_client import MediSearchClient\n\nclient = MediSearchClient(api_key=\"your_api_key\")\n\n# Generate a unique UUID for the conversation\nconversation_id = str(uuid.uuid4())  # e.g., \"f47ac10b-58cc-4372-a567-0e02b2c3d479\"\nconversation = [\"What are the symptoms of type 2 diabetes?\"]\n\n# Send the first message\nfirst_responses = client.send_message(\n    conversation=conversation,\n    conversation_id=conversation_id\n)\n\n# Extract the AI's response\nai_response = None\nfor response in first_responses:\n    if response[\"event\"] == \"llm_response\":\n        ai_response = response[\"data\"]\n\n# Follow-up question\nif ai_response:\n    conversation.append(ai_response)\n    conversation.append(\"How is it diagnosed?\")\n    \n    # Send the follow-up question with the SAME conversation_id\n    followup_responses = client.send_message(\n        conversation=conversation,\n        conversation_id=conversation_id\n    )\n```\n\n### Streaming Responses\n\nStreaming provides real-time feedback while responses are being generated.\n\n```python\nfrom medisearch_client import MediSearchClient\n\nclient = MediSearchClient(api_key=\"your_api_key\")\n\nprint(\"Response: \", end=\"\", flush=True)\n\n# Enable streaming with should_stream_response=True\nfor response in client.send_message(\n    conversation=[\"What are the treatment options for COVID-19?\"],\n    conversation_id=\"covid-treatment-stream\",\n    should_stream_response=True\n):\n    if response[\"event\"] == \"llm_response\":\n        # Print each chunk as it arrives\n        print(response[\"data\"], end=\"\", flush=True)\n    elif response[\"event\"] == \"articles\":\n        print(f\"\\n\\nBased on {len(response['data'])} medical sources\")\n```\n\n### Asynchronous Operations\n\nFor non-blocking operations, use the asynchronous methods.\n\n```python\nimport asyncio\nfrom medisearch_client import MediSearchClient\n\nasync def medical_query():\n    client = MediSearchClient(api_key=\"your_api_key\")\n    \n    # Async request\n    responses = await client.send_message_async(\n        conversation=[\"What are the cardiovascular effects of COVID-19?\"],\n        conversation_id=\"covid-cardio-async\"\n    )\n    \n    # Process responses\n    for response in responses:\n        if response[\"event\"] == \"llm_response\":\n            print(f\"Answer: {response['data'][:100]}...\")\n\n# Run the async function\nasyncio.run(medical_query())\n```\n\n#### Async Streaming\n\n```python\nimport asyncio\nfrom medisearch_client import MediSearchClient\n\nasync def stream_response():\n    client = MediSearchClient(api_key=\"your_api_key\")\n    \n    print(\"Response: \", end=\"\", flush=True)\n    \n    # Get streaming response asynchronously\n    response_stream = await client.send_message_async(\n        conversation=[\"What are the side effects of statins?\"],\n        conversation_id=\"statin-side-effects\",\n        should_stream_response=True\n    )\n    \n    # Process streaming response\n    async for response in response_stream:\n        if response[\"event\"] == \"llm_response\":\n            print(response[\"data\"], end=\"\", flush=True)\n        elif response[\"event\"] == \"articles\":\n            print(f\"\\n\\nBased on {len(response['data'])} medical sources\")\n\n# Run the async streaming function\nasyncio.run(stream_response())\n```\n\n### Response Handlers\n\nResponse handlers provide a way to process different types of responses with custom callbacks.\n\n```python\nfrom medisearch_client import MediSearchClient, ResponseHandler\n\nclient = MediSearchClient(api_key=\"your_api_key\")\n\n# Track the accumulated response\naccumulated_response = \"\"\narticle_count = 0\n\n# Define handler functions\ndef handle_llm_response(response):\n    global accumulated_response\n    chunk = response[\"data\"]\n    accumulated_response += chunk\n    print(chunk, end=\"\", flush=True)\n\ndef handle_articles(response):\n    global article_count\n    articles = response[\"data\"]\n    article_count = len(articles)\n    print(f\"\\n\\nFound {article_count} relevant medical articles\")\n\ndef handle_error(response):\n    error_code = response[\"data\"]\n    print(f\"\\nError occurred: {error_code}\")\n\n# Create response handler\nhandler = ResponseHandler(\n    on_llm_response=handle_llm_response,\n    on_articles=handle_articles,\n    on_error=handle_error\n)\n\n# Send message with the response handler\nclient.send_message(\n    conversation=[\"What are recent advances in breast cancer treatment?\"],\n    conversation_id=\"breast-cancer-treatment\",\n    response_handler=handler\n)\n```\n\n### Working with Filters\n\nThe `Filters` class allows you to customize search behavior for more targeted results.\n\n```python\nfrom medisearch_client import MediSearchClient, Filters, Settings\n\nclient = MediSearchClient(api_key=\"your_api_key\")\n\n# Create filters\nfilters = Filters(\n    # Specify which sources to search\n    sources=[\n        \"scientificArticles\",      # Peer-reviewed scientific literature\n        \"internationalHealthGuidelines\"  # Guidelines from health organizations\n    ],\n    # Limit to recent publications\n    year_start=2020,\n    year_end=2023,\n    # Only include high-quality sources\n    only_high_quality=True,\n    # Specific article types\n    article_types=[\n        \"metaAnalysis\",   # Meta-analyses\n        \"clinicalTrials\"  # Clinical trials\n    ]\n)\n\n# Apply filters through settings\nsettings = Settings(\n    language=\"English\",\n    filters=filters,\n    model_type=\"pro\"  # Use the professional model\n)\n\n# Send a message with custom settings\nresponses = client.send_message(\n    conversation=[\"What are the latest advancements in Alzheimer's treatment?\"],\n    conversation_id=str(uuid.uuid4()),\n    settings=settings\n)\n```\n\n#### Available Source Types\n\n- `scientificArticles`: Peer-reviewed scientific literature\n- `internationalHealthGuidelines`: Guidelines from international health organizations\n- `medicineGuidelines`: Guidelines related to drugs\n- `healthline`: Content from Healthline\n- `books`: Medical textbooks and references\n\n#### Article Types for Scientific Articles\n\n- `metaAnalysis`: Meta-analyses that combine results from multiple studies\n- `reviews`: Review articles that summarize current knowledge\n- `clinicalTrials`: Reports of clinical trials\n- `other`: Other types of scientific articles\n\n#### Year Filtering Options\n\nThe year filters allow you to specify the publication date range:\n\n- `year_start`: The earliest publication year to include (e.g., 2018)\n- `year_end`: The latest publication year to include (e.g., 2023)\n\nThese filters are particularly useful for:\n- Finding the most recent research on rapidly evolving topics\n- Excluding outdated medical information\n- Focusing on specific time periods for historical research\n\n#### High Quality Option\n\nThe `only_high_quality` parameter (default: False) determines whether to restrict results to high-quality sources:\n\n- When set to `True`: Only includes articles from reputable journals with high citation indices and recognized health guidelines\n- When set to `False`: Includes a broader range of sources\n\nThis option is useful when you need the most authoritative information for clinical decision support.\n\n### Language Support\n\nMediSearch supports queries in any language without constraints:\n\n```python\nfrom medisearch_client import MediSearchClient, Settings\n\nclient = MediSearchClient(api_key=\"your_api_key\")\n\n# Create language-specific settings\nsettings = Settings(language=\"Spanish\")\n\n# Send query in Spanish\nresponses = client.send_message(\n    conversation=[\"\u00bfCu\u00e1les son los s\u00edntomas de la diabetes?\"],\n    conversation_id=str(uuid.uuid4()),\n    settings=settings\n)\n```\n\nThe MediSearch API can process queries in any language and will respond in the same language as the query. There are no restrictions on supported languages, making it suitable for global applications.\n\n### Model Selection\n\nMediSearch offers two model types that correspond directly to those available on the MediSearch.io platform:\n\n```python\nfrom medisearch_client import MediSearchClient, Settings\n\nclient = MediSearchClient(api_key=\"your_api_key\")\n\n# Use standard model\nsettings = Settings(model_type=\"standard\")\nresponses = client.send_message(\n    conversation=[\"What are the treatments for rheumatoid arthritis?\"],\n    conversation_id=str(uuid.uuid4()),\n    settings=settings\n)\n```\n\nModel options:\n- `pro`: Enhanced model with advanced capabilities - identical to the Pro model on medisearch.io\n- `standard`: Standard model suitable for most queries (default) - identical to the Standard model on medisearch.io\n\nThe Pro model offers more comprehensive answers with deeper medical insights, while the Standard model provides solid medical information for common queries at potentially faster response times.\n\n## Response Structure\n\nThe MediSearch API returns responses with three main event types:\n\n### LLM Response Event\n\nContains text content generated by the AI:\n\n```json\n{\n  \"event\": \"llm_response\",\n  \"data\": \"Text content from the AI...\"\n}\n```\n\nIn streaming mode, multiple `llm_response` events will be received as chunks. In non-streaming mode, you'll receive a list that will contain a single consolidated `llm_response` event.\n\n### Articles Event\n\nContains bibliographic information about source articles, ordered by citation index (more authoritative sources appear first):\n\n```json\n{\n  \"event\": \"articles\",\n  \"data\": [\n    {\n      \"title\": \"Article Title\",\n      \"authors\": [\"Author 1\", \"Author 2\"],\n      \"year\": 2023,\n      \"journal\": \"Journal Name\",\n      \"url\": \"https://example.com/article\",\n      \"score\": 0.92,\n      \"article_type\": \"metaAnalysis\"\n    },\n    ...\n  ]\n}\n```\n\nThe articles are automatically sorted by the model's citation index. \n\n### Error Event\n\nIndicates an error condition with the following structure:\n\n```json\n{\n  \"event\": \"error\",\n  \"id\": \"conversation_id\",\n  \"data\": \"error_code_here\"\n}\n```\n\nThe `id` field contains the conversation ID that was used in the request, and the `data` field contains the specific error code.\n\n## Error Handling\n\nThe MediSearch API may return error events in various situations:\n\n### Error Event Codes\n\n- `error_not_enough_articles`: Not enough relevant articles found. Try rephrasing the question to be more medical in nature or more specific.\n- `error_out_of_tokens`: Conversation exceeded maximum allowed length. Start a new conversation or simplify your query.\n- `error_internal`: Internal server error that occurred during processing.\n- `error_llm`: Error occurred in the language model processing.\n\n### HTTP Errors\n\nOther errors (like authentication issues, rate limiting, etc.) are returned as standard HTTP errors over SSE, not as error events. These include:\n\n- 403: Unable to query due to authentication issues\n- 429: Rate limit exceeded\n- 500: General server error\n\n### Error Handling Example\n\n```python\nfrom medisearch_client import MediSearchClient\n\nclient = MediSearchClient(api_key=\"your_api_key\")\n\ntry:\n    responses = client.send_message(\n        conversation=[\"What are the best treatments for seasonal allergies?\"],\n        conversation_id=str(uuid.uuid4())\n    )\n    \n    for response in responses:\n        if response[\"event\"] == \"error\":\n            error_code = response[\"data\"]\n            if error_code == \"error_not_enough_articles\":\n                print(\"Not enough medical articles found. Try a more specific question.\")\n            elif error_code == \"error_out_of_tokens\":\n                print(\"Conversation is too long. Please start a new one.\")\n            elif error_code == \"error_internal\":\n                print(\"Internal server error occurred. Please try again later.\")\n            elif error_code == \"error_llm\":\n                print(\"Language model processing error. Please try rephrasing your question.\")\n            else:\n                print(f\"An error occurred: {error_code}\")\n        elif response[\"event\"] == \"llm_response\":\n            print(\"Answer:\", response[\"data\"])\nexcept Exception as e:\n    # Handle HTTP errors here\n    print(f\"Request failed: {str(e)}\")\n```\n\n## License\n\nMIT License - See LICENSE file for details.\n\nFor help or questions, contact us at [founders@medisearch.io](mailto:founders@medisearch.io).\n\nFor detailed API documentation, visit [MediSearch API Docs](https://medisearch.io/developers).\n",
    "bugtrack_url": null,
    "license": null,
    "summary": "A Python client for the MediSearch medical information API",
    "version": "0.3.8",
    "project_urls": {
        "Documentation": "https://docs.medisearch.io",
        "Homepage": "https://github.com/MediSearch/medisearch_client_python",
        "Issues": "https://github.com/MediSearch/medisearch_client_python/issues",
        "Source": "https://github.com/MediSearch/medisearch_client_python"
    },
    "split_keywords": [
        "medical",
        " healthcare",
        " api",
        " search",
        " research",
        " medisearch"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "c65f0b2ec0b64966a721176159bcf1754eb9ec0f206e66d3e4eab5ebff975efd",
                "md5": "2d9acde03c76925226ef55ce87d43668",
                "sha256": "91835a7399d4034645a361204ef736b05b3a91c50e78a9116bb15773fb5eedd7"
            },
            "downloads": -1,
            "filename": "medisearch_client-0.3.8-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "2d9acde03c76925226ef55ce87d43668",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.7",
            "size": 17490,
            "upload_time": "2025-02-28T21:03:39",
            "upload_time_iso_8601": "2025-02-28T21:03:39.378156Z",
            "url": "https://files.pythonhosted.org/packages/c6/5f/0b2ec0b64966a721176159bcf1754eb9ec0f206e66d3e4eab5ebff975efd/medisearch_client-0.3.8-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "c20181239b82339d4c1f1de50a01101e6bf44cb011f79f3a814d0fed4eafe95a",
                "md5": "31392470f2bbcc7b68557c2229ff3564",
                "sha256": "63533b1945b749685b2fbe54ce74bce30c0ae6a8f822b3a6aeea6c890c50d226"
            },
            "downloads": -1,
            "filename": "medisearch_client-0.3.8.tar.gz",
            "has_sig": false,
            "md5_digest": "31392470f2bbcc7b68557c2229ff3564",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.7",
            "size": 21531,
            "upload_time": "2025-02-28T21:03:41",
            "upload_time_iso_8601": "2025-02-28T21:03:41.089032Z",
            "url": "https://files.pythonhosted.org/packages/c2/01/81239b82339d4c1f1de50a01101e6bf44cb011f79f3a814d0fed4eafe95a/medisearch_client-0.3.8.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-02-28 21:03:41",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "MediSearch",
    "github_project": "medisearch_client_python",
    "github_not_found": true,
    "lcname": "medisearch-client"
}
        
Elapsed time: 0.42644s