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 work@localhost:tmp/

    To download file from localhost reverse the src and dest: backend.ai scp mysess work@localhost:tmp/ vfolder.py

    Directories upload and download support. Add -r option. upload: backend.ai scp mysess -r tmp/ work@localhost:tmp/ download: backend.ai scp mysess -r work@localhost: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
Drcom-pt-client - Drcom Pt version client with refresh timer

drcom-pt-client Drcom Pt version client with refresh timer Dr.com Pt版本客户端 可用于网页认

null 4 Nov 16, 2022
Clippin n grafting Backend

Clipping' n Grafting Presenting you, ?? Clippin' n Grafting ?? , your very own ecommerce website displaying all your artsy-craftsy stuff. Not only the

Google-Developer-Student-Club-ISquareIT (GDSC I²IT) 2 Oct 22, 2021
Troposphere and shellscript based AWS infrastructure automation creates an awsapigateway lambda with a go backend

Automated-cloudformation-infra Troposphere and shellscript based AWS infrastructure automation. Feel free to clone and edit for personal usage. The en

null 1 Jan 3, 2022
Portal Backend for Yuta management

Portal Backend for Yuta management Prerequisites Python 3.10 or above. pip, pdm installed. Quickstart Install the required packages: pdm install Runn

Loc Mai 1 Dec 20, 2021
🐍 The official Python client library for Google's discovery based APIs.

Google API Client This is the Python client library for Google's discovery based APIs. To get started, please see the docs folder. These client librar

Google APIs 6.2k Jan 8, 2023
The official Python client library for the Kite Connect trading APIs

The Kite Connect API Python client - v3 The official Python client for communicating with the Kite Connect API. Kite Connect is a set of REST-like API

Zerodha Technology 756 Jan 6, 2023
Unirest in Python: Simplified, lightweight HTTP client library.

Unirest for Python Unirest is a set of lightweight HTTP libraries available in multiple languages, built and maintained by Mashape, who also maintain

Kong 432 Dec 21, 2022
🐍 The official Python client library for Google's discovery based APIs.

Google API Client This is the Python client library for Google's discovery based APIs. To get started, please see the docs folder. These client librar

Google APIs 6.2k Dec 31, 2022
Pure Python 3 MTProto API Telegram client library, for bots too!

Telethon ⭐️ Thanks everyone who has starred the project, it means a lot! Telethon is an asyncio Python 3 MTProto library to interact with Telegram's A

LonamiWebs 7.3k Jan 1, 2023
Python client library for Google Maps API Web Services

Python Client for Google Maps Services Description Use Python? Want to geocode something? Looking for directions? Maybe matrices of directions? This l

Google Maps 3.8k Jan 1, 2023
Beyonic API Python official client library simplified examples using Flask, Django and Fast API.

Beyonic API Python official client library simplified examples using Flask, Django and Fast API.

Harun Mbaabu Mwenda 46 Sep 1, 2022
Python Client Library to interface with the Phoenix Realtime Server

supabase-realtime-client Python Client Library to interface with the Phoenix Realtime Server This is a fork of the supabase community realtime client

Anand 2 May 24, 2022
The Python client library for the Tuneup Technology App.

Tuneup Technology App Python Client Library The Python client library for the Tuneup Technology App. This library allows you to interact with the cust

Tuneup Technology 0 Jun 29, 2022
Python client library for Bigcommerce API

Bigcommerce API Python Client Wrapper over the requests library for communicating with the Bigcommerce v2 API. Install with pip install bigcommerce or

BigCommerce 81 Dec 26, 2022
Backlog API v2 Client Library for Python

BacklogPy - Backlog API v2 Client Library for Python BacklogPy is Backlog API v2 Client Library for Python 2/3 Install You can install the client libr

Koudai Aono 7 Dec 16, 2022
Thread-safe Python RabbitMQ Client & Management library

AMQPStorm Thread-safe Python RabbitMQ Client & Management library. Introduction AMQPStorm is a library designed to be consistent, stable and thread-sa

Erik Olof Gunnar Andersson 167 Nov 20, 2022
Python API client library for phpIPAM installations

phpypam: Python API client library for phpIPAM installation As we started to develop phpipam-ansible-modules we used an existing python library for ph

codeaffen 3 Aug 3, 2022
Osmopy - osmo python client library

osmopy Version 0.0.2 Tools for Osmosis wallet management and offline transaction

null 5 May 22, 2022
PHION's client-side core python library

PHION-core PHION's client-side core python library. This library is not meant to be used directly by users. If you want to install phion please use th

PHION 2 Feb 7, 2022