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
Aws-lambda-requests-wrapper - Request/Response wrapper for AWS Lambda with API Gateway

AWS Lambda Requests Wrapper Request/Response wrapper for AWS Lambda with API Gat

1 May 20, 2022
A Telegram Bot written in Python for mirroring files on the Internet to Google Drive

No support is going to be provided of any kind, only maintaining this for vps user on request. This is a Telegram Bot written in Python for mirroring

0 Dec 26, 2021
Discord Rich Presence for Team Fortress 2

TF2 Rich Presence Discord Rich Presence for Team Fortress 2 Detects current game state, queue info, playtime, and more Configurable, reliable, and per

Kataiser 33 Dec 31, 2022
Reverse engineering multi-device WhatsApp Web.

whatsapp-web-multi-device-reveng In this repository, the research for reverse engineering multi-device WhatsApp Web takes place, see here for a descri

84 Jan 01, 2023
Um simples bot público para todos usarem no discord!

Discord Bot - Código Público Características: Linguagem de Programação: Python Quantidade de comandos: 17 Comandos: Prefixo do bot: O prefixo desse bo

Kevin 3 Dec 31, 2021
A Telegram Bot to Extract Various Types Of Archives

IDN Unzip Bot A Telegram Bot to Extract Various Types Of Archives Features Extract various types of archives like rar, zip, tar, 7z, tar.xz etc. Passw

IDNCoderX 8 Jul 25, 2022
A bot for Large Fry Larrys

GroupMe Bot Driver This driver is written entirely in Python, and with easy configuration in mind. Using this driver, you'll be able to monitor multip

1 Oct 25, 2021
Automation application was made by me using Google, Sheet and Slack APIs with Python.

README This application is used to transfer the data in the xlsx document we have to the Google Drive environment and calculate the "total budget" wit

3 Apr 12, 2022
A client that allows a user, specifiy their discord token, to send images remotely to discord

ImageBot_for_Discord A client that allows a user, specifiy their discord token, to send images remotely to discord. Can select images using a file dia

0 Aug 24, 2022
A discord token creator that uses the service capmonster for captcha solving!

Discord Token Creator A discord token creator that uses the service capmonster for captcha solving! Report Bug · Request Feature Features Autojoin dis

dropout 41 Oct 25, 2021
An Open Source ALL-In-One Telegram RoBot, that can do lot of things.

URL Uploader Bot An Open Source ALL-In-One Telegram RoBot, that can do lot of things. My Features Installation The Easy Way You can also tap the Deplo

NT BOTS 1 Oct 23, 2021
⚡ Simple mass dm selfbot for Discord written in python3.

Zapp Simple mass dm selfbot for Discord written in python3. Warning. This project was made for educational purposes only! I take no responsibility for

Ѵιcнч 34 Nov 01, 2022
Unofficial python api for MicroBT Whatsminer ASICs

whatsminer-api Unofficial python api for MicroBT Whatsminer ASICs Code adapted from a python file found in the Whatsminer Telegram group that is credi

Satoshi Anonymoto 16 Dec 23, 2022
Rapid Sms Bomber For Indian Number.

Bombzilla Rapid Sms Bomber For Indian Number. Installation git clone https://github.com/sarv99/Bombzilla cd Bombzilla chmod +x setup.sh ./setup.sh Af

Saurav Jangid 1 Jan 12, 2022
Disqus API bindings for Python

disqus-python Let's start with installing the API: pip install disqus-python Use the API by instantiating it, and then calling the method through dott

DISQUS 163 Oct 14, 2022
A Telegram Bot with(Forwarder Bot + User Bot + More Features )

A Telegram Bot with(Forwarder Bot + User Bot + More Features )

Kaif 3 Feb 16, 2022
Python API Client for Close

Close API A convenient Python wrapper for the Close API. API docs: http://developer.close.com Support: Close 56 Nov 30, 2022

Biblioteca Python que extrai dados de mercado do Bacen (Séries Temporais)

Pybacen This library was developed for economic analysis in the Brazilian scenario (Investments, micro and macroeconomic indicators) Installation Inst

42 Jan 05, 2023
Telegram bot to host python bots

Host-Bot Setup the api Upload the flask api on your host #its not important to do #i used it just for simple captcha system + save ids on your host!

Plugin 15 Feb 11, 2022
Telegram bot to stream videos in telegram voicechat for both groups and channels

Telegram bot to stream videos in telegram voicechat for both groups and channels. Supports live streams, YouTube videos and telegram media. With record stream support, Schedule streams, and many more

ALBY 9 Feb 20, 2022