Backend.AI Client Library for Python

Overview

Backend.AI Client

PyPI version Python Versions SDK Documentation Build Status (Linux) Build Status (Windows) Code Coverage

The official API client library for Backend.AI

Usage (KeyPair mode)

You should set the access key and secret key as environment variables to use the API. Grab your keypair from cloud.backend.ai or your cluster admin.

On Linux/macOS, create a shell script as my-backend-ai.sh and run it before using the backend.ai command:

export BACKEND_ACCESS_KEY=...
export BACKEND_SECRET_KEY=...
export BACKEND_ENDPOINT=https://my-precious-cluster
export BACKEND_ENDPOINT_TYPE=api

On Windows, create a batch file as my-backend-ai.bat and run it before using the backend.ai command:

chcp 65001
set PYTHONIOENCODING=UTF-8
set BACKEND_ACCESS_KEY=...
set BACKEND_SECRET_KEY=...
set BACKEND_ENDPOINT=https://my-precious-cluster
set BACKEND_ENDPOINT_TYPE=api

Note that you need to switch to the UTF-8 codepage for correct display of special characters used in the console logs.

Usage (Session mode)

Change BACKEND_ENDPOINT_TYPE to "session" and set the endpoint to the URL of your console server.

export BACKEND_ENDPOINT=https://my-precious-cluster
export BACKEND_ENDPOINT_TYPE=session
$ backend.ai login
User ID: [email protected]
Password:
✔ Login succeeded!

$ backend.ai ...  # run any command

$ backend.ai logout
✔ Logout done.

The session expiration timeout is set by the console server.

Command-line Interface

backend.ai command is the entry point of all sub commands. (Alternatively you can use a verbosely long version: python -m ai.backend.client.cli)

Highlight: run command

The run command execute a code snippet or code source files on a Backend.AI compute session created on-the-fly.

To run the code specified in the command line directly, use -c option to pass the code string (like a shell).

$ backend.ai run python:3.6-ubuntu18.04 -c "print('hello world')"
∙ Client session token: d3694dda6e5a9f1e5c718e07bba291a9
✔ Kernel (ID: zuF1OzMIhFknyjUl7Apbvg) is ready.
hello world

By default, you need to specify language with full version tag like python:3.6-ubuntu18.04. Depending on the Backend.AI admin's language alias settings, this can be shortened just as python. If you want to know defined language aliases, contact the admin of Backend.AI server.

You can even run a C code on-the-fly. (Note that we put a dollar sign before the single-quoted code argument so that the shell to interpret '\n' as actual newlines.)

$ backend.ai run gcc:gcc6.4-alpine3.8 -c $'#include <stdio.h>\nint main() {printf("hello world\\n");}'
∙ Client session token: abc06ee5e03fce60c51148c6d2dd6126
✔ Kernel (ID: d1YXvee-uAJTx4AKYyeksA) is ready.
hello world

For larger programs, you may upload multiple files and then build & execute them. The below is a simple example to run a sample C program.

$ git clone https://gist.github.com/achimnol/df464c6a3fe05b21e9b06d5b80e986c5 c-example
Cloning into 'c-example'...
Unpacking objects: 100% (5/5), done.
$ cd c-example
$ backend.ai run gcc:gcc6.4-alpine3.8 main.c mylib.c mylib.h
∙ Client session token: 1c352a572bc751a81d1f812186093c47
✔ Kernel (ID: kJ6CgWR7Tz3_v2WsDHOwLQ) is ready.
✔ Uploading done.
✔ Build finished.
myvalue is 42
your name? LABLUP
hello, LABLUP!

Please refer the --help manual provided by the run command.

Highlight: start and app command

backend.ai start is simliar to the run command in that it creates a new compute session, but it does not execute anything there. You can subsequently call backend.ai run -t <sessionId> ... to execute codes snippets or use backend.ai app command to start a local proxy to a container service such as Jupyter which runs inside the compute session.

$ backend.ai start -t mysess -r cpu=1 -r mem=2g lablup/python:3.6-ubuntu18.04
∙ Session ID mysess is created and ready.
∙ This session provides the following app services: ipython, jupyter, jupyterlab
$ backend.ai app mysess jupyter
∙ A local proxy to the application "jupyter" provided by the session "mysess" is available at: http://127.0.0.1:8080

Highlight: ps and rm command

You can see the list of currently running sessions using your API keypair.

$ backend.ai ps
Session ID    Lang/runtime              Tag    Created At                        Terminated At    Status      CPU Cores    CPU Used (ms)    Total Memory (MiB)    Used Memory (MiB)    GPU Cores
------------  ------------------------  -----  --------------------------------  ---------------  --------  -----------  ---------------  --------------------  -------------------  -----------
88ee10a027    lablup/python:3.6-ubuntu         2018-12-11T03:53:14.802206+00:00                   RUNNING             1            16314                  1024                 39.2            0
fce7830826    lablup/python:3.6-ubuntu         2018-12-11T03:50:10.150740+00:00                   RUNNING             1            15391                  1024                 39.2            0

If you set -t option in the run command, it will be used as the session ID—you may use it to assign a human-readable, easy-to-type alias for your sessions. These session IDs can be reused after the current session using the same ID terminates.

To terminate a session, you can use terminate or rm command.

$ backend.ai rm 5baafb2136029228ca9d873e1f2b4f6a
✔ Done.

Highlight: proxy command

To use API development tools such as GraphiQL for the admin API, run an insecure local API proxy. This will attach all the necessary authorization headers to your vanilla HTTP API requests.

$ backend.ai proxy
∙ Starting an insecure API proxy at http://localhost:8084

More commands?

Please run backend.ai --help to see more commands.

Troubleshooting (FAQ)

  • There are error reports related to simplejson with Anaconda on Windows. This package no longer depends on simplejson since v1.0.5, so you may uninstall it safely since Python 3.5+ offers almost identical json module in the standard library.

    If you really need to keep the simplejson package, uninstall the existing simplejson package manually and try reinstallation of it by downloading a pre-built binary wheel from here.

Comments
  • Argument parsing error when specifying

    Argument parsing error when specifying "--exec" option to "run" command

    argparse module is not working as expected.

    $ backend.ai run python --exec "python hello.py" hello.py
    usage: backend.ai [-h] {help,config,run,proxy,admin,ps} ...
    backend.ai: error: unrecognized arguments: hello.py
    
    bug 
    opened by achimnol 5
  • Client py tus-draft

    Client py tus-draft

    This is draft version.

    • The client implemented at func/vfolder.py under @api_function async def upload_tus

    • To test client capabilities the file func/mytus.py is used.

    • The package client-tus is located under func/tusclient. It is based on tus-py-client. It was refactored by adding backend.ai session creation and making request to generate a new id for a file.

    • It has the following issues such that aiohttp server on received request produces uncaught exception 400.

    • The server function create_tus_session cannot be executed after the exception occurred. So, fully functionality of tus client is not tested

    feature 
    opened by leksikov 4
  • 버츄얼 폴더에 get 메소드 버그

    버츄얼 폴더에 get 메소드 버그

    session = Session()
    vf = session.VFolder
    name = "first_vf"
    vf.create(name)
    vf.get(name)
    

    을 할경우 아래와 같이 에러가 발생합니다.

    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    <ipython-input-24-586f79b79e3d> in <module>
    ----> 1 vf.get('first_vf')
    
    ~/code/brgg/CodeLion/.venv/lib/python3.6/site-packages/ai/backend/client/base.py in _caller(cls, *args, **kwargs)
         63                    'You must use API wrapper functions via a Session object.'
         64             gen = meth(*args, **kwargs)
    ---> 65             resp = cls._make_request(gen)
         66             return cls._handle_response(resp, gen)
         67 
    
    ~/code/brgg/CodeLion/.venv/lib/python3.6/site-packages/ai/backend/client/base.py in _make_request(gen)
         49     @staticmethod
         50     def _make_request(gen):
    ---> 51         rqst = next(gen)
         52         resp = rqst.fetch()
         53         return resp
    
    TypeError: 'VFolder' object is not an iterator
    

    get메소드는 다른 메소드와 달리 별도의 처리가 되지 않아 발생한 상황인듯 하여 확인 부탁드립니다.

    opened by like-sinsky 4
  • Tunneling proxy to access service ports (e.g., TensorBoard)

    Tunneling proxy to access service ports (e.g., TensorBoard)

    Configuring a network is often painful for end-users. Let's provide a better way in the CLI of sorna client, and let the users just open "localhost:8081" to magically connect to a web page served by the kernel session. We could use the SSH socks proxy or just some custom-built ones via WebSockets.

    feature 
    opened by achimnol 4
  • Feature/audit_logs

    Feature/audit_logs

    This pull request refers to: https://github.com/lablup/backend.ai-internal/issues/17

    This is the implementation of the audit log feature in client side, which includes admin cli commands

    List

    This command list audit logs of a user by user_id

    Screenshot 2022-05-04 at 18 30 52 Screenshot 2022-05-09 at 21 09 03
    opened by hydroxyde 3
  • Feature/filebrowser in storage proxy

    Feature/filebrowser in storage proxy

    A CLI implementation for starting File Browser in storage proxy. After File Browser starts the CLI opens the web browser tab with url of FileBrowser UI interface.

    feature cli client 
    opened by leksikov 3
  • refactor: Make CLI commands consistent

    refactor: Make CLI commands consistent

    Let's make command arguments and options to be consistent and update to Click 8.0.x.

    • refs https://github.com/lablup/backend.ai-test
    • refs lablup/backend.ai#240

    The client SDK consists of: low-level API (auth, request) + functional API (wrappers around REST and GraphQL) + CLI commands. This PR will rewrite the CLI commands, and this will not be backward compatible due to ambiguity of command parsing. (Just imagine that etcdctl requires ETCDCTL_API environment variable to switch between v2 and v3 command sets.)

    What's included in this PR:

    • API v4 or older support is removed with an explicit warning during version negotiation.
    • Python 3.7 support is removed and now it requires 3.8 or later.
    • New consistent CLI command hierarchy with backend.ai admin? <entity> {info,list,...}. e.g.,
      • Before
        • backend.ai admin agents
        • backend.ai admin agent i-dgx001 (😞 mix of plural and singular "agent" and "agents")
        • backend.ai admin scaling-group -n default (😞 some individual item query commands just accept an argument but some accept an arbitrarily named option -- inconsistent!!)
      • After
        • backend.ai admin agent list
        • backend.ai admin agent info i-dgx001 (💯 now consistent singular name followed by list, info)
        • backend.ai admin scaling-group info default (💯 now consistently accept the key as a sole argument)
      • Still it preserves many frequently-used shortcuts such as run, ps, rm, etc., but they are now the pure duplicate, by generating the command handler function twice for different command groups and thus removing potential of missing new options/arguments due to manual copy-and-paste of codes.
    • Global --output=console (the default) or --output=json option to control the output format of CLI list and info commands. e.g.,
      • backend.ai --output=json ps --dead
      • backend.ai --output=json admin agent list
      • This introduces a new "output" framework as ai.backend.client.output subpackage.
        • Now all functional list/detail APIs must be called with a list of FieldSpec as fields arguments, instead of a list of str.
        • You may refer the predefined FieldSpec instances from ai.backend.client.output.fields and each functional API module's _default_list_fields and _default_detail_fields variables.
        • It standardizes the error output and exit code so that users may write more sophisticated automation scripts using the CLI with jq command and shell scripts.
    • --limit and --offset to control pagination of paginated list commands (NOTE: Not all list commands support this...)
      • e.g., backend.ai ps --dead --offset=30 --limit=20
      • All JSON output of list commands now include count (the number of items in the current page result), total_count (the number of all items in the server), items (the list of item objects) fields so that client may perform its own pagination as needed, in a consistent way.

    Left as future work:

    • This PR does not implement the --output=json support for mutation and session execution commands. They currently work like before, just printing out console messages regardless of the output option.
    feature refactor cli client 
    opened by achimnol 3
  • backend.ai ssh/scp commands

    backend.ai ssh/scp commands

    Completed Backend.AI SSH client which can connect to the existing backend.ai session SSH server for the Issue #228

    After session is started. It is possible to directly initialize ssh connection. backend.ai ssh mysess

    Or with port specification for that session: backend.ai ssh mysess -p 9922

    File upload and download. Scp client was implemented to upload and download files. (session name, local file, host file/dir, flag to reverse) backend.ai scp mysess vfolder.py [email protected]:tmp/

    To download file from localhost reverse the src and dest: backend.ai scp mysess [email protected]:tmp/ vfolder.py

    Directories upload and download support. Add -r option. upload: backend.ai scp mysess -r tmp/ [email protected]:tmp/ download: backend.ai scp mysess -r [email protected]:tmp/ tmp/

    cli usability client 
    opened by leksikov 3
  • Added --format and --plain options to the 'backend.ai ps' command

    Added --format and --plain options to the 'backend.ai ps' command

    lablup/backend.ai#87 @achimnol

    • Added --format/-f options for "backend.ai ps"/"backend.ai admin session" commands

    • Added --plain option to see process status info in plain tabular format

    • [x] I will update the documentation file as soon as possible

    feature 
    opened by miraliahmadli 3
  • 쿼리 요청이 불가능합니다.

    쿼리 요청이 불가능합니다.

    from ai.backend.client import Kernel로 되있으나 실제로는 from ai.backend.client.kernel import Kernel해야 작동이 됩니다. 또한 위와 같이 변경하여 아래와 같이 요청을 시도하여도

    from ai.backend.client.kernel import Kernel
    
    kern = Kernel.get_or_create('python', client_token='abcdef')
    result = kern.execute('print("hello world")', mode='query')
    print(result['console'])
    kern.destroy()
    

    AssertionError: You must use API wrapper functions via a Session object. 에러가 발생합니다. get_or_create가 클래스 메소드이다보니 세션을 어느시점에 어떻게 넣어줘야 하는지 궁금합니다.

    마지막으로 사소한 부분이긴 하나 실세 샘플 코드에서는 클라이언트 토큰이 'abc'로 적혀있는데 실제로 그대로 돌려볼경우 assert 4 <= len(client_token) <= 64, 'Client session token should be 4 to 64 characters long.' 에러가 막히지 않을까 싶습니다. 그래서 4자 이상으로 변경하시면 처음 시도하시는 분이 에러없이 테스트 해보실수 있지 않을까 싶습니다.

    help wanted 
    opened by like-sinsky 3
  • Cannot download file(s) from compute session

    Cannot download file(s) from compute session

    backend.ai download <sess-id> <filepath> command is broken with following traceback:

    Traceback (most recent call last):c51362187f653ee5745d6906b...
      File "/Users/adrysn/.pyenv/versions/playground/bin/backend.ai", line 11, in <module>
        sys.exit(main())
      File "/Users/adrysn/.pyenv/versions/3.7.0/envs/playground/lib/python3.7/site-packages/ai/backend/client/cli/__init__.py", line 104, in main
        args.function(args)
      File "/Users/adrysn/.pyenv/versions/3.7.0/envs/playground/lib/python3.7/site-packages/ai/backend/client/cli/__init__.py", line 40, in wrapped
        handler(args)
      File "/Users/adrysn/.pyenv/versions/3.7.0/envs/playground/lib/python3.7/site-packages/ai/backend/client/cli/files.py", line 44, in download
        kernel.download(args.files, show_progress=True)
      File "/Users/adrysn/.pyenv/versions/3.7.0/envs/playground/lib/python3.7/site-packages/ai/backend/client/base.py", line 79, in _caller
        return self._handle_response(resp, gen)
      File "/Users/adrysn/.pyenv/versions/3.7.0/envs/playground/lib/python3.7/site-packages/ai/backend/client/base.py", line 37, in _handle_response
        meth_gen.send(resp)
      File "/Users/adrysn/.pyenv/versions/3.7.0/envs/playground/lib/python3.7/site-packages/ai/backend/client/kernel.py", line 191, in _download
        total=resp.stream_reader.total_bytes,
    AttributeError: 'Response' object has no attribute 'stream_reader'
    

    Meanwhile, downloading from vfolders is working.

    bug 
    opened by adrysn 3
  • refactor: remove dependency of tqdm in vfolder function progress

    refactor: remove dependency of tqdm in vfolder function progress

    resolves https://github.com/lablup/backend.ai/issues/344

    add abstraction in vfolder function and remove tqdm dependency

    upload function still uses tqdm because aiotusclient uses tqdm directly.

    refactor cli client 
    opened by fregataa 0
  • feat: Display kernel-pull-progress

    feat: Display kernel-pull-progress

    backend.ai-issue#227

    Client (Python & Javascript) Task

    • [x] Check the existence of the task ID in the create-kernel API response.

    • [x] If it exists, show a progress bar reflecting its progress stream.

    Using response from manager, client obtains background-task pulling kernel and displays progress bar reflecting kernel-pulling. But, I do request twice.

    • From first request, client obtains kernel_id and background task.

    • From second request, client gets all the information from existed session.

    But, I think we need another way to get all the information(contains background-task id) from manager with a single request.

    feature cli client 
    opened by youngjun0627 4
  • Docs/cli 2009

    Docs/cli 2009

    Configuration

    • API Mode

    • Session Mode

    • Checking out current configuration

    • Command reference 
 Code Execution
    • ComputeSessions

    • Container Apps

    • Adv. Code Execution

    • Session Templates

    • Command reference


    Storage Management

    • VFolder Basics -> 생성·삭제·업로드·다운로드·파일조회 관련 설명

    • VFolder Sharing -> invitation 관련 기능 설명(새로운 내용 추가)

    • Command reference


    의 구조로 docs를 정리했습니다. review 부탁드립니다!

    docs cli 
    opened by kmkwon94 3
Releases(20.03.0a1)
  • 20.03.0a1(Apr 6, 2020)

    Breaking Changes

    • Breaking Changes without explicit PR/issue numbers
      • Now the client SDK runs on Python 3.6, 3.7, and 3.8 and dropped support for Python 3.5.
    • All functional API classes are moved into the ai.backend.client.func sub-package. (#82)
      • Kernel is changed to Session.
      • The session ID field name in the response of Session objects is now session_id instead of kernel_id.
      • Except above, this would not introduce big changes in the SDK user codes since they use AsyncSession and Session in the ai.backend.client.session module.

    Features

    • Features without explicit PR/issue numbers
      • Add SDK API (SessionTemplate) and CLI command set (backend.ai sesstpl)
    • Support for unmanaged vfolders and token-based download API (#77)
    • backend.ai config command now displays the server/client component and API versions with negotiated API version if available. (#79)
    • Add --format and --plain options to backend.ai ps command to customize the output table format (#80)
    • Perform automatic API version negotiation when entering session contexts while keeping the functional API same (#82)
    • Support dotfiles management API and CLI (#85)

    Fixes

    • Refine details of the app command such as error handling (#90)
    • Improve exception handling in backend.ai app command and update backend.ai-cli package (#94)

    Miscellaneous

    Source code(tar.gz)
    Source code(zip)
Owner
Lablup
lab | up: Make AI Accessible - A start-up to innovate research / education processes.
Lablup
A Discord webhook spammer made in Python

A Python made Discord webhook spammer usually used for token loggers to spam them/delete them original by cattyn changes listed below.

2 Jan 12, 2022
Facebook fishing on telegram bot

Facebook-fishing Facebook fishing on telegram bot تثبيت الاداة pkg update -y pkg upgrade -y pkg install git -y pkg install python -y git clone https:/

sadamalsharabi 7 Oct 18, 2022
An open-source, multipurpose, configurable discord bot that does it all

Spacebot is an open source discord bot that is designed to be fun, easy to use, and replace every other discord bot out there!! Feel free to add a star ⭐ to the repository to promote the project!

Dhravya Shah 41 Dec 10, 2022
Official Python wrapper for the Quantel Finance API

Quantel is a powerful financial data and insights API. It provides easy access to world-class financial information. Quantel goes beyond just financial statements, giving users valuable information l

Guy 47 Oct 16, 2022
Bitcoin tracker hecho con python.

Bitcoin Tracker Precio del Bitcoin en tiempo real. Script simple hecho con python. Rollercoin RollerCoin es un juego en el que puedes ganar bitcoin (y

biyivi 3 Jan 04, 2022
Lumi-Bot - Discord bot that fetches cryptocurrency prices utilizing CoinGeko API

Lumi-Bot Discord bot that fetches and monitors cryptocurrency prices utilizing C

Diego Castro 2 Oct 08, 2022
🤖 Telegram UserBot Untuk Memutar Lagu Dan Video Di Obrolan Suara Telegram.

🤖 Telegram UserBot Untuk Memutar Lagu Dan Video Di Obrolan Suara Telegram.

Fariz 2 Nov 13, 2021
A simple Python library to integrate with the Heron Data API

Heron Python This library provides easy access to the Heron Data API from applications written in Python. Documentation No language-specific docs are

Heron Data 11 Nov 11, 2022
CyberTKR - CyberTK-API

CyberTKR - CyberTK-API

TKR 2 Apr 08, 2022
Bot Auto Chess.com

Bot Auto Chess.com Is a suggestion for chess moves on the chess.com platform. The available features are: chess suggestions and moves automatically. i

Tn. Ninja 34 Jan 01, 2023
Step by Step Guide To Install Discord Py Master Branch on Replit

Guide to Install Discord Py Master Branch on Replit Step 1 Create an empty repl on replit Step 2 Add this Basic Code to the file main.py so as to chec

Pranav Saxena 7 Nov 18, 2022
API which returns cusswords , can be used to check cusswords in bots etc.

Anti-abuse-api-flask API which returns cusswords , can be used to check cusswords in bots etc. Run pip install -r requirements.txt py app.py API Endpo

8 Jan 03, 2023
A Advanced Powerful, Smart And Intelligent Group Management Bot With New And Powerful Features

Vegeta Robot A Advanced Powerful, Smart And Intelligent Group Management Bot With New And Powerful Features ... Written with Pyrogram and Telethon...

⚡ CT_PRO ⚡ 9 Nov 16, 2022
DIAL(Did I Alert Lambda?) is a centralised security misconfiguration detection framework which completely runs on AWS Managed services like AWS API Gateway, AWS Event Bridge & AWS Lambda

DIAL(Did I Alert Lambda?) is a centralised security misconfiguration detection framework which completely runs on AWS Managed services like AWS API Gateway, AWS Event Bridge & AWS Lambda

CRED 71 Dec 29, 2022
Repository for the Nexus Client software.

LinkScope Client Description This is the repository for the LinkScope Client Online Investigation software. LinkScope allows you to perform online inv

107 Dec 30, 2022
You cant check for conflicts until course enrolment actually opens. I wanted to do it earlier.

AcornICS I noticed that Acorn it does not let you check if a timetable is valid based on the enrollment cart, it also does not let you visualize it ea

Isidor Kaplan 2 Sep 16, 2021
McTrade is a bot exploiting Binance API, open source! built in python !

Open Source Crypto Trading Bot using Binance API Report Bug · Request Feature Table of Contents About The Project Built With Getting Started Prerequis

Raphael Cohen 5 Jul 17, 2022
Cookiecutter templates for Serverless applications using AWS SAM and the Rust programming language.

Cookiecutter SAM template for Lambda functions in Rust This is a Cookiecutter template to create a serverless application based on the Serverless Appl

AWS Samples 24 Nov 11, 2022
A python package to easy the integration with Direct Online Pay (Mpesa, TigoPesa, AirtelMoney, Card Payments)

A python package to easy the integration with Direct Online Pay (DPO) which easily allow you easily integrate with payment options once without having to deal with each of them individually;

Jordan Kalebu 2 Nov 25, 2021
Library to manage your own custom RPC on your desktop

Info I don't recommend novices setting this up yourself. It requires Redis, a server to host the API on, and a bit of understanding of Windows & Pytho

Isaac K 1 Apr 16, 2022