HomeGuidesRecipesAPI EndpointsRelease NotesCommunity
Log In

Asking Questions of a Single Document

Part I. Set Up

Import Dependencies

To start, let's import our dependencies.

# add dependencies
import json
import time

import layar_api
from layar_api.rest import ApiException

Configure Authentication

Next, we'll want to configure our session with our authentication keys. Copy the following commands and only swap out the strings for base_host, client_id, and client_secret. The base_host is the Layar instance you're working within (e.g. 'demo.vyasa.com'), and the client ID and secret are your provided authentication keys.

To learn how to get your authentication keys, please reference this document.

# set up your authentication credentials
base_host = 'BASE_URL' # your Layar instance (e.g. 'demo.vyasa.com')
client_id = 'AbcDEfghI3' # example developer API key
client_secret = '1ab23c4De6fGh7Ijkl8mNoPq9' #example developer API secret

# configure oauth access token for authorization
configuration = layar_api.Configuration()
configuration.host = f"https://{base_host}"
configuration.access_token = configuration.fetch_access_token(
    client_id, client_secret)

# Make your life easier for the next task: instantiating APIs!
client = layar_api.ApiClient(configuration)

Instantiate Your APIs

Finally, we'll want to instantiate the APIs we are going to call in future commands. We'll be using the SourceDocumentApi and SavedListApi.

# Instantiate APIs
sourceDocApi = layar_api.SourceDocumentApi(client)
questionApi = layar_api.QuestionApi(client)

Part 2. Create the QA Request

Identify Your Document

In this use case, we aren't attempting to locate an answer wherever it may exist in the fabric. Instead, we are looking to interrogate a specific document. This document may be one that has been found/created previously, or a document that matches specific search criteria.

# Find the document you wish to interrogate
document = sourceDocApi.search_documents(body=layar_api.SourceDocumentSearchCommand(rows=1, q="\"JAK inhibitors\""), x_vyasa_data_providers="master-pubmed.vyasa.com")[0]
# Or use the document ID if you already know it
document = {"id": "pubmed_36681073"}


Pro Tip

If you're interested in section aware question answering, such as asking a question of a specific set of PDF sections like methods or inclusion criteria, you can use the sourceDocument parameter section_searches to specify which sections you're interested in asking QA of! For more details, check out this tutorial here.

Build the Request Body

The body needed when calling the create_question endpoint is the Question, which includes three required parameters: the question you're asking (query_string), the document you're asking the question of (search), and the type of search you're asking (single document, defined in the type_of_search).

# Create the question request
questions = layar_api.QuestionApi(client)
question = layar_api.Question(
    query_string="What is the disease or indication being studied?",

Submit Your Question

Now that you have your request body prepped (question), it's time to submit your API request! Make a call to the questionApi class using the create_question endpoint (see SDK documentation).

# Submit Question
    # submit a request to ask a batch of questions
		question = questions.create_question(body=question, x_vyasa_data_providers=f"master-pubmed.vyasa.com")
		print(f"Question created with id: {question.id}")
except ApiException as e:
    print("Exception when calling QuestionApi->create_question: %s\n" % e)

Console Response

You should see the following as a console response. The question has now been submitted to the work queue and will be completed according to available resources and server load.

Question created with id: AYXmF1-JEs8gbQkuEVKE

Part 3. Check Question Status

To retrieve the status of the question make a call using the get_question endpoint (see SDK documentation).

    # Poll for status on that question
    while not question.complete:
      print("sleeping for 1s while the question is being answered")
      question = questions.get_question(question.id)
except ApiException as e:
    print("Exception when calling QuestionApi->get_question: %s\n" % e)

After the question completes, a best_answers property will be populated on the Question with the text of the highest ranked answer.

# The question itself contains the best answer text
if question.best_answers:
    print(f"Found answers. The best are:")
    for answer in question.best_answers:


Pro Tip

More answers may have been found, and more details are available than simply the answer text! To retrieve answer details, issue a query to the search_answer endpoint of the AnswerApi.

Using the search_answer endpoint of the AnswerApi, we're going to get all of the answers for this question.

You will use the AnswerSearchCommand parameters to specify criteria that an answer must meet in order to be returned as a result. Here we specify the question_ids parameter to match the ID of the question we just created.

# Retrieve more context/details, if desired.
    answersApi = layar_api.AnswerApi(client)
    answers = answersApi.search_answer(body=layar_api.AnswerSearchCommand(sort="probability", sort_order="desc", rows=5, question_ids=[question.id]))
    for answer in answers:
        best_evidence = sorted(answer.evidence, key= lambda evidence: evidence.probability, reverse=True)[0]
            "text": answer.text,
            "probability": best_evidence.probability,
            "context": best_evidence.context
except ApiException as e:
    print("Exception when calling AnswerApi->search_answer: %s\n" % e)