@qbraid-core/ibm-cloud
Version:
Client for interacting with IBM's Qiskit Runtime Service via the IBM Cloud API.
185 lines • 7.67 kB
JavaScript
"use strict";
// Copyright (c) 2025, qBraid Development Team
// All rights reserved.
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.IBMCloudClient = void 0;
const axios_1 = __importDefault(require("axios"));
const config_1 = require("./config");
class IBMCloudClient {
baseUrl;
client;
configManager;
constructor({ apiKey, token, crn, configManager, }) {
this.configManager = configManager || new config_1.IBMConfig();
if (apiKey)
this.configManager.setApiKey(apiKey);
if (token)
this.configManager.setBearerToken(token);
if (crn)
this.configManager.setServiceCRN(crn);
if (!this.configManager.getApiKey() && !this.configManager.getBearerToken()) {
throw new Error('Either apiKey or token must be provided');
}
if (!this.configManager.getServiceCRN()) {
throw new Error('Service CRN must be provided');
}
this.baseUrl = 'https://quantum.cloud.ibm.com/api/v1';
const headers = {
'Service-CRN': this.configManager.getServiceCRN(),
Authorization: `Bearer ${this.configManager.getBearerToken()}`,
};
const axiosInstance = axios_1.default.create({
baseURL: this.baseUrl,
headers,
});
this.client = axiosInstance;
}
async refreshBearerToken() {
try {
if (this.configManager.isBearerTokenExpired()) {
if (this.configManager.getApiKey() === '') {
throw new Error('API key is required to refresh the bearer token');
}
const newToken = await this.fetchNewBearerToken();
this.configManager.setBearerToken(newToken);
// edit the header of the client with new token
this.client.defaults.headers['Authorization'] = `Bearer ${newToken}`;
}
}
catch (error) {
console.error('Error refreshing bearer token:', error);
}
}
async fetchNewBearerToken() {
const response = await axios_1.default.post('https://iam.cloud.ibm.com/identity/token', {
grant_type: 'urn:ibm:params:oauth:grant-type:apikey',
apikey: this.configManager.getApiKey(),
}, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
});
return response.data.access_token;
}
async handleJobRequest(request) {
try {
const response = await request;
return response.data;
}
catch (error) {
if (axios_1.default.isAxiosError(error) && error.response) {
return error.response.data;
}
throw error;
}
}
// 1. GET /backends - get all backends from IBM
async getBackends() {
await this.refreshBearerToken();
const response = await this.client.get('/backends');
return response.data;
}
// 2. GET /backends/:backend_name/properties - get all properties of a specific backend
async getBackendProperties(backendName, updatedBefore // format : YYYY-MM-DDThh:mm:ssZ
) {
await this.refreshBearerToken();
const params = updatedBefore ? { updated_before: updatedBefore } : undefined;
const response = await this.client.get(`/backends/${backendName}/properties`, { params: params });
return response.data;
}
// 3. GET /backends/:backend_name/configuration - get all configuration of a specific backend
async getBackendConfiguration(backendName) {
await this.refreshBearerToken();
const response = await this.client.get(`/backends/${backendName}/configuration`);
return response.data;
}
// 4. GET /backends/:backend_name/status - get the status of a specific backend
async getBackendStatus(backendName) {
await this.refreshBearerToken();
const response = await this.client.get(`/backends/${backendName}/status`);
return response.data;
}
// 5. GET /backends/:backend_name/errors - get the gate errors of a specific backend
async getBackendErrors(backendName) {
await this.refreshBearerToken();
const backendProps = await this.getBackendProperties(backendName);
if (!backendProps.gates || backendProps.gates.length === 0) {
return { gate_errors: [] };
}
const gates = backendProps.gates;
const gateErrors = {};
for (let gate of gates) {
const gateName = gate.gate;
// check if gate is not present
if (gateErrors[gateName] === undefined) {
gateErrors[gateName] = {
name: gate.gate,
num_qubits: gate.qubits.length,
lowest: 1e6,
highest: 0,
};
}
const gateParams = gate.parameters;
for (let param of gateParams) {
if (param.name === 'gate_error') {
// update the gate errors
const error = param.value;
gateErrors[gateName].lowest = Math.min(gateErrors[gateName].lowest, error);
gateErrors[gateName].highest = Math.max(gateErrors[gateName].highest, error);
}
}
}
const errors = {
gate_errors: Object.values(gateErrors),
};
return errors;
}
// 6. GET /jobs - get all jobs from IBM
async getJobs(params) {
await this.refreshBearerToken();
return this.handleJobRequest(this.client.get('/jobs', { params }));
}
// 7. GET /jobs/:job_id - get a specific job from IBM
async getJob(jobId, excludeParams) {
await this.refreshBearerToken();
return this.handleJobRequest(this.client.get(`/jobs/${jobId}`, {
params: { exclude_params: excludeParams },
}));
}
// 8. DELETE /jobs/:job_id - delete a specific job from IBM
async deleteJob(jobId) {
await this.refreshBearerToken();
return this.handleJobRequest(this.client.delete(`/jobs/${jobId}`));
}
// 9. POST /jobs/:job_id/cancel - cancel a specific job from IBM
async cancelJob(jobId, parentJobId) {
await this.refreshBearerToken();
const customHeader = parentJobId ? { 'parent-job-id': parentJobId } : {};
return this.handleJobRequest(this.client.post(`/jobs/${jobId}/cancel`, null, {
headers: {
...this.client.defaults.headers.common,
...customHeader,
},
}));
}
// 10. GET /jobs/:job_id/logs - get logs of a specific job from IBM
async getJobLogs(jobId) {
await this.refreshBearerToken();
return this.handleJobRequest(this.client.get(`/jobs/${jobId}/logs`));
}
// 11. GET /jobs/:job_id/transpiled_circuits - get transpiled circuits of a specific job from IBM
async getJobTranspiledCircuits(jobId) {
await this.refreshBearerToken();
return this.handleJobRequest(this.client.get(`/jobs/${jobId}/transpiled_circuits`));
}
// 12. GET /jobs/:job_id/metrics - get metrics of a specific job from IBM
async getJobMetrics(jobId) {
await this.refreshBearerToken();
return this.handleJobRequest(this.client.get(`/jobs/${jobId}/metrics`));
}
}
exports.IBMCloudClient = IBMCloudClient;
//# sourceMappingURL=client.js.map