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:
pip install medisearch-client
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.
from medisearch_client import MediSearchClientimport uuid# Initialize client with your API keyapi_key = "your_api_key"client = MediSearchClient(api_key=api_key)# Generate a unique conversation IDconversation_id = str(uuid.uuid4())# Send a queryresponses = 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.
# Process responsesfor response in responses:if response["event"] == "llm_response":# The AI-generated answerprint("Answer:", response["data"])elif response["event"] == "articles":# Supporting articles and citationsarticles = 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.
# Enable streaming with should_stream_response=Truefor 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 arrivesprint(response["data"], end="", flush=True)elif response["event"] == "articles":print(f"Based on {len(response['data'])} medical sources")
Follow-up Questions
Maintain conversation context by including the full conversation history when asking follow-up questions.
# Initial queryconversation = ["What are the symptoms of type 2 diabetes?"]conversation_id = str(uuid.uuid4()) # Use the same ID for the entire conversation# Send first messagefirst_responses = client.send_message(conversation=conversation,conversation_id=conversation_id)# Get the AI's response to include in conversation historyai_response = Nonefor 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 conversationif ai_response:conversation.append(ai_response)conversation.append("How is it diagnosed?")# Send follow-up with complete conversation historyfollowup_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.
from medisearch_client import Filters, Settings# Create filters for customized searchfilters = Filters(# Specify which sources to searchsources=["scientificArticles","internationalHealthGuidelines"],# Limit to recent publicationsyear_start=2020,# Only include high-quality sourcesonly_high_quality=True,# Specific article typesarticle_types=["metaAnalysis","clinicalTrials"])# Apply filters through settingssettings = Settings(language="English",filters=filters,model_type="pro")# Send message with custom settingsresponses = 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.
from medisearch_client import ResponseHandler# Define handler functionsdef 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 handlerhandler = ResponseHandler(on_llm_response=handle_llm_response,on_articles=handle_articles,on_error=handle_error)# Send message with the response handlerclient.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.
import asynciofrom medisearch_client import MediSearchClientasync def main():client = MediSearchClient(api_key="your_api_key")# Async requestresponses = await client.send_message_async(conversation=["What are the cardiovascular effects of COVID-19?"],conversation_id=str(uuid.uuid4()))# Process responsesfor response in responses:if response["event"] == "llm_response":print(f"Answer: {response['data']}")# Run the async functionasyncio.run(main())
Multilingual Support
Send queries in any language and receive responses in the same language.
from medisearch_client import Settings# Create settings with Spanish language preferencesettings = Settings(language="Spanish")# Send query in Spanishclient.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.
from medisearch_client import Settings# Create settings that specify the Pro modelpro_settings = Settings(language="English",model_type="pro" # Explicitly request the Pro model)# Complex medical query that benefits from Pro modelresponses = 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.
from medisearch_client import Settings# Create settings with a custom system prompt focused on style and simplicitycustom_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 promptresponses = client.send_message(conversation=["What's the current approach to managing hypertension in patients with diabetes?"],conversation_id=str(uuid.uuid4()),settings=custom_settings)
Ready to start building?
Get your API key and start integrating MediSearch into your application.
Get API Key