Passing input arguments to your QiskitFunction

In this document, we will learn how to pass arguments to our function.

Let’s create another file with our function ./source_files/function_with_arguments.py.

Instead of having the circuit defined inside the function (like we did in the first example), we will pass it as an argument. We will also save the results, so we can access them later by calling save_result.

Here is the function:

from qiskit_serverless import get_arguments, save_result
from qiskit.primitives import Sampler

# get all arguments passed to this function
arguments = get_arguments()

# get specific argument that we are interested in
circuit = arguments.get("circuit")

sampler = Sampler()

quasi_dists = sampler.run(circuit).result().quasi_dists

print(f"Quasi distribution: {quasi_dists[0]}")

# saving results of the execution
save_result({
    "quasi_dists": quasi_dists[0]
})

As you can see, the circuit construction is not inside the function anymore. Instead, we parse the arguments by calling the get_arguments function.

First, we will create circuit that we want to pass as an argument to the function.

[1]:
from qiskit import QuantumCircuit

circuit = QuantumCircuit(2)
circuit.h(0)
circuit.cx(0, 1)
circuit.measure_all()
circuit.draw()
[1]:
        ┌───┐      ░ ┌─┐
   q_0: ┤ H ├──■───░─┤M├───
        └───┘┌─┴─┐ ░ └╥┘┌─┐
   q_1: ─────┤ X ├─░──╫─┤M├
             └───┘ ░  ║ └╥┘
meas: 2/══════════════╩══╩═
                      0  1 

Now let’s create and configure our client

⚠ This provider is set up with default credentials to a test cluster intended to run on your machine. For information on setting up infrastructure on your local machine, check out the guide on local infrastructure setup.

[ ]:
from qiskit_serverless import ServerlessClient
import os

client = ServerlessClient(
    token=os.environ.get("GATEWAY_TOKEN", "awesome_token"),
    host=os.environ.get("GATEWAY_HOST", "http://localhost:8000"),
    # If you are using the kubernetes approach the URL must be http://localhost
)
client
<gateway-client>
[3]:
from qiskit_serverless import QiskitFunction

function = QiskitFunction(
    title="function-with-arguments",
    entrypoint="function_with_arguments.py",
    working_dir="./source_files/",
)

client.upload(function)
[3]:
QiskitFunction(function-with-arguments)

Run the function using the run method and by passing arguments.

[4]:
my_function = client.get("function-with-arguments")
my_function
[4]:
QiskitFunction(function-with-arguments)
[5]:
job = my_function.run(circuit=circuit)
job
[5]:
<Job | a2cfbcdc-f503-4be3-9bcf-8914ee110bb2>

Retrieve the results from the client

[6]:
job.result()
[6]:
{'quasi_dists': {'11': 524, '00': 500}}