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 client interface for Scrapinghub's API

Client interface for Scrapinghub API The scrapinghub is a Python library for communicating with the Scrapinghub API. Requirements Python 2.7 or above

Scrapinghub 184 Sep 28, 2022
Bot that embeds a random hysterical meme from Reddit into your text channel as an embedded message, using an API call.

Discord_Meme_Bot 🤣 Bot that embeds a random hysterical meme from Reddit into your text channel as an embedded message, using an API call. Add the bot

2 Jan 16, 2022
Flaga ze Szturmu na AWS.

Witaj Jesteś na GitHub'ie i czytasz właśnie plik README.md który znajduje się wewnątrz repozytorium Flaga z 7 i 8 etapu Szturmu na AWS. W tym etapie w

9 May 16, 2022
Neofetch/pfetch, but for weather

Wfetch Neofetch/pfetch, but for weather Features Information about the weather outside: Weather condition Temperature Humidity Pressure Wind Sunrise-s

G_cat 72 Nov 18, 2022
Powerful Ethereum Smart-Contract Toolkit

Heimdall Heimdall is an advanced and modular smart-contract toolkit which aims to make dealing with smart contracts on EVM based chains easier. Instal

Jonathan Becker 69 Dec 26, 2022
Editing a Tinder bot created by @frederikme

tinder_bot_edit Editing a Tinder bot created by @frederikme Table of Contents Basic Swipe Bot Basic Swipe Bot Download the code as a zip or clone the

Alex Carter 1 Nov 23, 2021
An inline Telegram bot to keep your private messages hidden from prying eyes.

Hide This Bot Hide This Bot is an inline Telegram bot to keep your private messages hidden from prying eyes.     How do I host it? Here is a brief gui

41 Dec 02, 2022
A simple Discord Bot created for basic functionality and fun chat commands for use in a private server.

LoveAndChaos-Bot v0.1.0 LoveAndChaos-Bot is a Discord Bot specifically designed for a private server; this bot is merely a test and a method to expose

Morgan Rose 1 Dec 12, 2021
NFT Generator: A modular NFT generator application

NFT Generator A simple passion project done with the role to learn a bit about h

2 Aug 30, 2022
A simple use library for bot discord.py developers

Discord Bot Template It's a simple use library for bot discord.py developers. Ob

Tir Omar 0 Oct 16, 2022
A discord bot written in discord.py to manage custom roles assigned to boosters of your server.

BBotty A discord bot written in discord.py to manage custom roles assigned to boosters of your server. v0.0.1-alpha released! This version is incomple

Oui002 1 Nov 27, 2021
UniHub API is my solution to bringing students and their universities closer

🎓 UniHub API UniHub API is my solution to bringing students and their universities closer... By joining UniHub, students will be able to join their r

Abdelbaki Boukerche 5 Nov 21, 2021
Python wrapper library for World Weather Online API

pywwo Python wrapper library for World Weather Online API using lxml.objectify How to use from pywwo import * setKey('your_key', 'free') w=LocalWeat

World Weather Online 20 Dec 19, 2022
This very basic script can be used to automate COVID-19 vaccination slot booking on India's Co-WIN Platform.

COVID-19 Vaccination Slot Booking Script This very basic CLI based script can be used to automate covid vaccination slot booking on Co-WIN Platform. I

605 Dec 14, 2022
An anime themed telegram group management bot based on sqlalchemy database running on python3.

Kazuko Robot A Telegram Python bot running on python3 forked with saitama and DiasyX with a sqlalchemy database and an entirely themed persona to make

heyaaman 22 Dec 07, 2022
Python + AWS Lambda Hands OnPython + AWS Lambda Hands On

Python + AWS Lambda Hands On Python Criada em 1990, por Guido Van Rossum. "Bala de prata" (quase). Muito utilizado em: Automatizações - Selenium, Beau

Marcelo Ortiz de Santana 8 Sep 09, 2022
Security Monkey monitors AWS, GCP, OpenStack, and GitHub orgs for assets and their changes over time.

NOTE: Security Monkey is in maintenance mode and will be end-of-life in 2020. For AWS users, please make use of AWS Config. For GCP users, please make

Netflix, Inc. 4.3k Jan 09, 2023
Simple integrate of API udemy.com with python

Pyudemy Simple integrate of API udemy.com with python Quick start $ pip install pyudemy or $ python setup.py install Authentication To make any calls

Hudson Brendon 30 Jan 02, 2023
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