Code Examples

Get started quickly with our API using these code examples. Choose your preferred language and follow along.

Installation

First, install the MediSearch Python client using pip:

python
pip install medisearch-client

Run in Google Colab

Try this example interactively in a Colab without any setup required.

Learn more

PyPI Package

Learn about our official MediSearch Python client.

Learn more

Quick Start

After installing, you can start using MediSearch with just a few lines of code. For a detailed understanding of request and response formats, refer to our API Documentation.

python
from medisearch_client import MediSearchClient
import uuid
# Initialize client with your API key
api_key = "your_api_key"
client = MediSearchClient(api_key=api_key)
# Generate a unique conversation ID
conversation_id = str(uuid.uuid4())
# Send a query
responses = client.send_message(
conversation=["What are the symptoms of COVID-19?"],
conversation_id=conversation_id
)

Handling Responses

Process the responses from MediSearch to extract answers and references. The response includes different event types that you can handle appropriately. See our output format documentation for details on all possible events.

python
# Process responses
for response in responses:
if response["event"] == "llm_response":
# The AI-generated answer
print("Answer:", response["data"])
elif response["event"] == "articles":
# Supporting articles and citations
articles = response["data"]
print(f"Found {len(articles)} supporting articles")
for i, article in enumerate(articles[:3], 1):
print(f"{i}. {article['title']} ({article.get('year', 'N/A')})")

Streaming Responses

Enable real-time streaming responses to get results as they are generated.

python
# Enable streaming with should_stream_response=True
for response in client.send_message(
conversation=["What are the treatment options for COVID-19?"],
conversation_id=str(uuid.uuid4()),
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"Based on {len(response['data'])} medical sources")

Asking Follow-up Questions

Maintain conversation context by including the full conversation history when asking follow-up questions.

python
# Initial query
conversation = ["What are the symptoms of type 2 diabetes?"]
conversation_id = str(uuid.uuid4()) # Use the same ID for the entire conversation
# Send first message
first_responses = client.send_message(
conversation=conversation,
conversation_id=conversation_id
)
# Get the AI's response to include in conversation history
ai_response = None
for response in first_responses:
if response["event"] == "llm_response":
ai_response = response["data"]
# Add the AI's response and a follow-up question to the conversation
if ai_response:
conversation.append(ai_response)
conversation.append("How is it diagnosed?")
# Send follow-up with complete conversation history
followup_responses = client.send_message(
conversation=conversation,
conversation_id=conversation_id # Same conversation ID
)

Search Filters

Refine search results by specifying article types, publication dates, and more.

python
from medisearch_client import Filters, Settings
# Create filters for customized search
filters = Filters(
# Specify which sources to search
sources=[
"scientificArticles",
"internationalHealthGuidelines"
],
# Limit to recent publications
year_start=2020,
# Specific article types
article_types=[
"metaAnalysis",
"clinicalTrials",
"observationalStudies"
]
)
# Apply filters through settings
settings = Settings(
language="English",
filters=filters,
model_type="pro"
)
# Send message with custom settings
responses = client.send_message(
conversation=["What are the latest treatments for Alzheimer's?"],
conversation_id=str(uuid.uuid4()),
settings=settings
)

Using Response Handlers

Process different types of responses with custom callback functions. The functions are called when the corresponding event type is detected in the response.

python
from medisearch_client import ResponseHandler
# Define handler functions
def handle_llm_response(response):
print(response["data"], end="", flush=True)
def handle_articles(response):
articles = response["data"]
print(f"Found {len(articles)} relevant medical articles")
for i, article in enumerate(articles[:3], 1):
print(f"{i}. {article['title']} ({article.get('year', 'N/A')})")
def handle_error(response):
error_code = response["data"]
print(f"Error 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=str(uuid.uuid4()),
response_handler=handler
)

Asynchronous API

Use async/await for non-blocking operations.

python
import asyncio
from medisearch_client import MediSearchClient
async def main():
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=str(uuid.uuid4())
)
# Process responses
for response in responses:
if response["event"] == "llm_response":
print(f"Answer: {response['data']}")
# Run the async function
asyncio.run(main())

Multilingual Support

Send queries in any language and receive responses in the same language.

python
from medisearch_client import Settings
# Create settings with Spanish language preference
settings = Settings(language="Spanish")
# Send query in Spanish
client.send_message(
conversation=["¿Cuáles son los síntomas de la diabetes?"],
conversation_id=str(uuid.uuid4()),
settings=settings,
response_handler=handler # Using the previously defined handler
)

MediSearch Pro Model

Use the Pro model for more detailed and specialized responses.

python
from medisearch_client import Settings
# Create settings that specify the Pro model
pro_settings = Settings(
language="English",
model_type="pro" # Explicitly request the Pro model
)
# Complex medical query that benefits from Pro model
responses = client.send_message(
conversation=[
"What is the current understanding of the role of microbiome in inflammatory bowel disease pathogenesis?"
],
conversation_id=str(uuid.uuid4()),
settings=pro_settings
)

Custom System Prompt

Use system prompts to control the style, format, and constraints of AI responses. This is especially useful for tailoring content for specific audiences or applications.

python
from medisearch_client import Settings
# Create settings with a custom system prompt focused on style and simplicity
custom_settings = Settings(
language="English",
model_type="pro",
system_prompt="""Please provide all responses in simple, consumer-friendly language.
Avoid medical jargon when possible, and when medical terms must be used, define them clearly.
Keep answers concise, use bullet points for clarity, and prioritize practical advice.
Limit responses to 3-4 short paragraphs maximum."""
)
# Send a query with the consumer-friendly system prompt
responses = client.send_message(
conversation=["What's the current approach to managing hypertension in patients with diabetes?"],
conversation_id=str(uuid.uuid4()),
settings=custom_settings
)

Generating Followup Suggestions

MediSearch can automatically generate relevant follow-up questions to help guide the conversation. Use the followup_count parameter to specify how many suggestions you want.

python
from medisearch_client import Settings
# Create settings with followup_count set to 3
settings = Settings(
language="English",
followup_count=3 # Will generate 3 follow-up questions
)
# Send the query with settings
responses = client.send_message(
conversation=["What are the common side effects of statins?"],
conversation_id=str(uuid.uuid4()),
settings=settings
)
# Process all responses
ai_answer = None
for response in responses:
if response["event"] == "llm_response":
ai_answer = response["data"]
print("Answer:", ai_answer)
elif response["event"] == "followups":
# Handle suggested follow-up questions
print("Suggested follow-up questions:")
for i, question in enumerate(response["data"], 1):
print(f"{i}. {question}")

Ready to start building?

Get your API key and start integrating MediSearch into your application.

Get API Key