magics-python


Namemagics-python JSON
Version 0.0.2 PyPI version JSON
download
home_pageNone
SummaryPython client for Magics's Cloud Platform!
upload_time2024-10-13 04:21:09
maintainerNone
docs_urlNone
authorMagics AI
requires_python>=3.8
licenseApache-2.0
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            
# Magics Python API library

The [Magics Python API Library](https://pypi.org/project/magics/) is the official Python client for Magics's API platform, providing a convenient way for interacting with the REST APIs and enables easy integrations with Python 3.8+ applications with easy to use synchronous and asynchronous clients.



## Installation

To install Magics Python Library from PyPI, simply run:

```shell Shell
 pip install -e . 
```

### Setting up API Key

#### Setting environment variable

```shell
export MAGICS_API_KEY=xxxxx
```

#### Using the client

```python
from magics import Magics

client = Magics(api_key="xxxxx")
```

This repo contains both a Python Library and a CLI. We'll demonstrate how to use both below.

## Usage – Python Client

### Chat Completions

```python
import os
from magics import Magics

client = Magics(api_key=os.environ.get("MAGICS_API_KEY"))

response = client.chat.completions.create(
    model="mistralai/Mixtral-8x7B-Instruct-v0.1",
    messages=[{"role": "user", "content": "tell me about new york"}],
)
print(response.choices[0].message.content)
```

#### Streaming

```python
import os
from magics import Magics

client = Magics(api_key=os.environ.get("MAGICS_API_KEY"))
stream = client.chat.completions.create(
    model="mistralai/Mixtral-8x7B-Instruct-v0.1",
    messages=[{"role": "user", "content": "tell me about new york"}],
    stream=True,
)

for chunk in stream:
    print(chunk.choices[0].delta.content or "", end="", flush=True)
```

#### Async usage

```python
import os, asyncio
from magics import AsyncMagics

async_client = AsyncMagics(api_key=os.environ.get("MAGICS_API_KEY"))
messages = [
    "What are the top things to do in San Francisco?",
    "What country is Paris in?",
]

async def async_chat_completion(messages):
    async_client = AsyncMagics(api_key=os.environ.get("MAGICS_API_KEY"))
    tasks = [
        async_client.chat.completions.create(
            model="mistralai/Mixtral-8x7B-Instruct-v0.1",
            messages=[{"role": "user", "content": message}],
        )
        for message in messages
    ]
    responses = await asyncio.gather(*tasks)

    for response in responses:
        print(response.choices[0].message.content)

asyncio.run(async_chat_completion(messages))
```

### Completions

Completions are for code and language models shown [here](https://docs.magics.ai/docs/inference-models). Below, a code model example is shown.

```python
import os
from magics import Magics

client = Magics(api_key=os.environ.get("MAGICS_API_KEY"))

response = client.completions.create(
    model="codellama/CodeLlama-34b-Python-hf",
    prompt="Write a Next.js component with TailwindCSS for a header component.",
    max_tokens=200,
)
print(response.choices[0].text)
```

#### Streaming

```python
import os
from magics import Magics

client = Magics(api_key=os.environ.get("MAGICS_API_KEY"))
stream = client.completions.create(
    model="codellama/CodeLlama-34b-Python-hf",
    prompt="Write a Next.js component with TailwindCSS for a header component.",
    stream=True,
)

for chunk in stream:
    print(chunk.choices[0].delta.content or "", end="", flush=True)
```

#### Async usage

```python
import os, asyncio
from magics import AsyncMagics

async_client = AsyncMagics(api_key=os.environ.get("MAGICS_API_KEY"))
prompts = [
    "Write a Next.js component with TailwindCSS for a header component.",
    "Write a python function for the fibonacci sequence",
]

async def async_chat_completion(prompts):
    async_client = AsyncMagics(api_key=os.environ.get("MAGICS_API_KEY"))
    tasks = [
        async_client.completions.create(
            model="codellama/CodeLlama-34b-Python-hf",
            prompt=prompt,
        )
        for prompt in prompts
    ]
    responses = await asyncio.gather(*tasks)

    for response in responses:
        print(response.choices[0].text)

asyncio.run(async_chat_completion(prompts))
```

### Image generation

```python
import os
from magics import Magics

client = Magics(api_key=os.environ.get("MAGICS_API_KEY"))

response = client.images.generate(
    prompt="space robots",
    model="stabilityai/stable-diffusion-xl-base-1.0",
    steps=10,
    n=4,
)
print(response.data[0].b64_json)
```

### Embeddings

```python
from typing import List
from magics import Magics

client = Magics(api_key=os.environ.get("MAGICS_API_KEY"))

def get_embeddings(texts: List[str], model: str) -> List[List[float]]:
    texts = [text.replace("\n", " ") for text in texts]
    outputs = client.embeddings.create(model=model, input = texts)
    return [outputs.data[i].embedding for i in range(len(texts))]

input_texts = ['Our solar system orbits the Milky Way galaxy at about 515,000 mph']
embeddings = get_embeddings(input_texts, model='magicscomputer/m2-bert-80M-8k-retrieval')

print(embeddings)
```

### Files

The files API is used for fine-tuning and allows developers to upload data to fine-tune on. It also has several methods to list all files, retrive files, and delete files. Please refer to our fine-tuning docs [here](https://docs.magics.ai/docs/fine-tuning-python).

```python
import os
from magics import Magics

client = Magics(api_key=os.environ.get("MAGICS_API_KEY"))

client.files.upload(file="somedata.jsonl") # uploads a file
client.files.list() # lists all uploaded files
client.files.retrieve(id="file-d0d318cb-b7d9-493a-bd70-1cfe089d3815") # retrieves a specific file
client.files.retrieve_content(id="file-d0d318cb-b7d9-493a-bd70-1cfe089d3815") # retrieves content of a specific file
client.files.delete(id="file-d0d318cb-b7d9-493a-bd70-1cfe089d3815") # deletes a file
```

### Fine-tunes

The finetune API is used for fine-tuning and allows developers to create finetuning jobs. It also has several methods to list all jobs, retrive statuses and get checkpoints. Please refer to our fine-tuning docs [here](https://docs.magics.ai/docs/fine-tuning-python).

```python
import os
from magics import Magics

client = Magics(api_key=os.environ.get("MAGICS_API_KEY"))

client.fine_tuning.create(
  training_file = 'file-d0d318cb-b7d9-493a-bd70-1cfe089d3815',
  model = 'mistralai/Mixtral-8x7B-Instruct-v0.1',
  n_epochs = 3,
  n_checkpoints = 1,
  batch_size = "max",
  learning_rate = 1e-5,
  suffix = 'my-demo-finetune',
  wandb_api_key = '1a2b3c4d5e.......',
)
client.fine_tuning.list() # lists all fine-tuned jobs
client.fine_tuning.retrieve(id="ft-c66a5c18-1d6d-43c9-94bd-32d756425b4b") # retrieves information on finetune event
client.fine_tuning.cancel(id="ft-c66a5c18-1d6d-43c9-94bd-32d756425b4b") # Cancels a fine-tuning job
client.fine_tuning.list_events(id="ft-c66a5c18-1d6d-43c9-94bd-32d756425b4b") #  Lists events of a fine-tune job
client.fine_tuning.download(id="ft-c66a5c18-1d6d-43c9-94bd-32d756425b4b") # downloads compressed fine-tuned model or checkpoint to local disk
```

### Models

This lists all the models that Magics supports.

```python
import os
from magics import Magics

client = Magics(api_key=os.environ.get("MAGICS_API_KEY"))

models = client.models.list()

for model in models:
    print(model)
```

## Usage – CLI

### Chat Completions

```bash
magics chat.completions \
  --message "system" "You are a helpful assistant named Magics" \
  --message "user" "What is your name?" \
  --model mistralai/Mixtral-8x7B-Instruct-v0.1
```

The Chat Completions CLI enables streaming tokens to stdout by default. To disable streaming, use `--no-stream`.

### Completions

```bash
magics completions \
  "Large language models are " \
  --model mistralai/Mixtral-8x7B-v0.1 \
  --max-tokens 512 \
  --stop "."
```

The Completions CLI enables streaming tokens to stdout by default. To disable streaming, use `--no-stream`.

### Image Generations

```bash
magics images generate \
  "space robots" \
  --model stabilityai/stable-diffusion-xl-base-1.0 \
  --n 4
```

The image is opened in the default image viewer by default. To disable this, use `--no-show`.

### Files

```bash
# Help
magics files --help

# Check file
magics files check example.jsonl

# Upload file
magics files upload example.jsonl

# List files
magics files list

# Retrieve file metadata
magics files retrieve file-6f50f9d1-5b95-416c-9040-0799b2b4b894

# Retrieve file content
magics files retrieve-content file-6f50f9d1-5b95-416c-9040-0799b2b4b894

# Delete remote file
magics files delete file-6f50f9d1-5b95-416c-9040-0799b2b4b894
```

### Fine-tuning

```bash
# Help
magics fine-tuning --help

# Create fine-tune job
magics fine-tuning create \
  --model magicscomputer/llama-2-7b-chat \
  --training-file file-711d8724-b3e3-4ae2-b516-94841958117d

# List fine-tune jobs
magics fine-tuning list

# Retrieve fine-tune job details
magics fine-tuning retrieve ft-c66a5c18-1d6d-43c9-94bd-32d756425b4b

# List fine-tune job events
magics fine-tuning list-events ft-c66a5c18-1d6d-43c9-94bd-32d756425b4b

# Cancel running job
magics fine-tuning cancel ft-c66a5c18-1d6d-43c9-94bd-32d756425b4b

# Download fine-tuned model weights
magics fine-tuning download ft-c66a5c18-1d6d-43c9-94bd-32d756425b4b
```

### Models

```bash
# Help
magics models --help

# List models
magics models list
```



            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "magics-python",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": null,
    "keywords": null,
    "author": "Magics AI",
    "author_email": "support@magics.ai",
    "download_url": "https://files.pythonhosted.org/packages/70/bb/356e804b292d63d86265f39222f4c91abdcdd2ba8c4e8e9313bd2da1e935/magics-python-0.0.2.tar.gz",
    "platform": null,
    "description": "\n# Magics Python API library\n\nThe [Magics Python API Library](https://pypi.org/project/magics/) is the official Python client for Magics's API platform, providing a convenient way for interacting with the REST APIs and enables easy integrations with Python 3.8+ applications with easy to use synchronous and asynchronous clients.\n\n\n\n## Installation\n\nTo install Magics Python Library from PyPI, simply run:\n\n```shell Shell\n pip install -e . \n```\n\n### Setting up API Key\n\n#### Setting environment variable\n\n```shell\nexport MAGICS_API_KEY=xxxxx\n```\n\n#### Using the client\n\n```python\nfrom magics import Magics\n\nclient = Magics(api_key=\"xxxxx\")\n```\n\nThis repo contains both a Python Library and a CLI. We'll demonstrate how to use both below.\n\n## Usage \u2013 Python Client\n\n### Chat Completions\n\n```python\nimport os\nfrom magics import Magics\n\nclient = Magics(api_key=os.environ.get(\"MAGICS_API_KEY\"))\n\nresponse = client.chat.completions.create(\n    model=\"mistralai/Mixtral-8x7B-Instruct-v0.1\",\n    messages=[{\"role\": \"user\", \"content\": \"tell me about new york\"}],\n)\nprint(response.choices[0].message.content)\n```\n\n#### Streaming\n\n```python\nimport os\nfrom magics import Magics\n\nclient = Magics(api_key=os.environ.get(\"MAGICS_API_KEY\"))\nstream = client.chat.completions.create(\n    model=\"mistralai/Mixtral-8x7B-Instruct-v0.1\",\n    messages=[{\"role\": \"user\", \"content\": \"tell me about new york\"}],\n    stream=True,\n)\n\nfor chunk in stream:\n    print(chunk.choices[0].delta.content or \"\", end=\"\", flush=True)\n```\n\n#### Async usage\n\n```python\nimport os, asyncio\nfrom magics import AsyncMagics\n\nasync_client = AsyncMagics(api_key=os.environ.get(\"MAGICS_API_KEY\"))\nmessages = [\n    \"What are the top things to do in San Francisco?\",\n    \"What country is Paris in?\",\n]\n\nasync def async_chat_completion(messages):\n    async_client = AsyncMagics(api_key=os.environ.get(\"MAGICS_API_KEY\"))\n    tasks = [\n        async_client.chat.completions.create(\n            model=\"mistralai/Mixtral-8x7B-Instruct-v0.1\",\n            messages=[{\"role\": \"user\", \"content\": message}],\n        )\n        for message in messages\n    ]\n    responses = await asyncio.gather(*tasks)\n\n    for response in responses:\n        print(response.choices[0].message.content)\n\nasyncio.run(async_chat_completion(messages))\n```\n\n### Completions\n\nCompletions are for code and language models shown [here](https://docs.magics.ai/docs/inference-models). Below, a code model example is shown.\n\n```python\nimport os\nfrom magics import Magics\n\nclient = Magics(api_key=os.environ.get(\"MAGICS_API_KEY\"))\n\nresponse = client.completions.create(\n    model=\"codellama/CodeLlama-34b-Python-hf\",\n    prompt=\"Write a Next.js component with TailwindCSS for a header component.\",\n    max_tokens=200,\n)\nprint(response.choices[0].text)\n```\n\n#### Streaming\n\n```python\nimport os\nfrom magics import Magics\n\nclient = Magics(api_key=os.environ.get(\"MAGICS_API_KEY\"))\nstream = client.completions.create(\n    model=\"codellama/CodeLlama-34b-Python-hf\",\n    prompt=\"Write a Next.js component with TailwindCSS for a header component.\",\n    stream=True,\n)\n\nfor chunk in stream:\n    print(chunk.choices[0].delta.content or \"\", end=\"\", flush=True)\n```\n\n#### Async usage\n\n```python\nimport os, asyncio\nfrom magics import AsyncMagics\n\nasync_client = AsyncMagics(api_key=os.environ.get(\"MAGICS_API_KEY\"))\nprompts = [\n    \"Write a Next.js component with TailwindCSS for a header component.\",\n    \"Write a python function for the fibonacci sequence\",\n]\n\nasync def async_chat_completion(prompts):\n    async_client = AsyncMagics(api_key=os.environ.get(\"MAGICS_API_KEY\"))\n    tasks = [\n        async_client.completions.create(\n            model=\"codellama/CodeLlama-34b-Python-hf\",\n            prompt=prompt,\n        )\n        for prompt in prompts\n    ]\n    responses = await asyncio.gather(*tasks)\n\n    for response in responses:\n        print(response.choices[0].text)\n\nasyncio.run(async_chat_completion(prompts))\n```\n\n### Image generation\n\n```python\nimport os\nfrom magics import Magics\n\nclient = Magics(api_key=os.environ.get(\"MAGICS_API_KEY\"))\n\nresponse = client.images.generate(\n    prompt=\"space robots\",\n    model=\"stabilityai/stable-diffusion-xl-base-1.0\",\n    steps=10,\n    n=4,\n)\nprint(response.data[0].b64_json)\n```\n\n### Embeddings\n\n```python\nfrom typing import List\nfrom magics import Magics\n\nclient = Magics(api_key=os.environ.get(\"MAGICS_API_KEY\"))\n\ndef get_embeddings(texts: List[str], model: str) -> List[List[float]]:\n    texts = [text.replace(\"\\n\", \" \") for text in texts]\n    outputs = client.embeddings.create(model=model, input = texts)\n    return [outputs.data[i].embedding for i in range(len(texts))]\n\ninput_texts = ['Our solar system orbits the Milky Way galaxy at about 515,000 mph']\nembeddings = get_embeddings(input_texts, model='magicscomputer/m2-bert-80M-8k-retrieval')\n\nprint(embeddings)\n```\n\n### Files\n\nThe files API is used for fine-tuning and allows developers to upload data to fine-tune on. It also has several methods to list all files, retrive files, and delete files. Please refer to our fine-tuning docs [here](https://docs.magics.ai/docs/fine-tuning-python).\n\n```python\nimport os\nfrom magics import Magics\n\nclient = Magics(api_key=os.environ.get(\"MAGICS_API_KEY\"))\n\nclient.files.upload(file=\"somedata.jsonl\") # uploads a file\nclient.files.list() # lists all uploaded files\nclient.files.retrieve(id=\"file-d0d318cb-b7d9-493a-bd70-1cfe089d3815\") # retrieves a specific file\nclient.files.retrieve_content(id=\"file-d0d318cb-b7d9-493a-bd70-1cfe089d3815\") # retrieves content of a specific file\nclient.files.delete(id=\"file-d0d318cb-b7d9-493a-bd70-1cfe089d3815\") # deletes a file\n```\n\n### Fine-tunes\n\nThe finetune API is used for fine-tuning and allows developers to create finetuning jobs. It also has several methods to list all jobs, retrive statuses and get checkpoints. Please refer to our fine-tuning docs [here](https://docs.magics.ai/docs/fine-tuning-python).\n\n```python\nimport os\nfrom magics import Magics\n\nclient = Magics(api_key=os.environ.get(\"MAGICS_API_KEY\"))\n\nclient.fine_tuning.create(\n  training_file = 'file-d0d318cb-b7d9-493a-bd70-1cfe089d3815',\n  model = 'mistralai/Mixtral-8x7B-Instruct-v0.1',\n  n_epochs = 3,\n  n_checkpoints = 1,\n  batch_size = \"max\",\n  learning_rate = 1e-5,\n  suffix = 'my-demo-finetune',\n  wandb_api_key = '1a2b3c4d5e.......',\n)\nclient.fine_tuning.list() # lists all fine-tuned jobs\nclient.fine_tuning.retrieve(id=\"ft-c66a5c18-1d6d-43c9-94bd-32d756425b4b\") # retrieves information on finetune event\nclient.fine_tuning.cancel(id=\"ft-c66a5c18-1d6d-43c9-94bd-32d756425b4b\") # Cancels a fine-tuning job\nclient.fine_tuning.list_events(id=\"ft-c66a5c18-1d6d-43c9-94bd-32d756425b4b\") #  Lists events of a fine-tune job\nclient.fine_tuning.download(id=\"ft-c66a5c18-1d6d-43c9-94bd-32d756425b4b\") # downloads compressed fine-tuned model or checkpoint to local disk\n```\n\n### Models\n\nThis lists all the models that Magics supports.\n\n```python\nimport os\nfrom magics import Magics\n\nclient = Magics(api_key=os.environ.get(\"MAGICS_API_KEY\"))\n\nmodels = client.models.list()\n\nfor model in models:\n    print(model)\n```\n\n## Usage \u2013 CLI\n\n### Chat Completions\n\n```bash\nmagics chat.completions \\\n  --message \"system\" \"You are a helpful assistant named Magics\" \\\n  --message \"user\" \"What is your name?\" \\\n  --model mistralai/Mixtral-8x7B-Instruct-v0.1\n```\n\nThe Chat Completions CLI enables streaming tokens to stdout by default. To disable streaming, use `--no-stream`.\n\n### Completions\n\n```bash\nmagics completions \\\n  \"Large language models are \" \\\n  --model mistralai/Mixtral-8x7B-v0.1 \\\n  --max-tokens 512 \\\n  --stop \".\"\n```\n\nThe Completions CLI enables streaming tokens to stdout by default. To disable streaming, use `--no-stream`.\n\n### Image Generations\n\n```bash\nmagics images generate \\\n  \"space robots\" \\\n  --model stabilityai/stable-diffusion-xl-base-1.0 \\\n  --n 4\n```\n\nThe image is opened in the default image viewer by default. To disable this, use `--no-show`.\n\n### Files\n\n```bash\n# Help\nmagics files --help\n\n# Check file\nmagics files check example.jsonl\n\n# Upload file\nmagics files upload example.jsonl\n\n# List files\nmagics files list\n\n# Retrieve file metadata\nmagics files retrieve file-6f50f9d1-5b95-416c-9040-0799b2b4b894\n\n# Retrieve file content\nmagics files retrieve-content file-6f50f9d1-5b95-416c-9040-0799b2b4b894\n\n# Delete remote file\nmagics files delete file-6f50f9d1-5b95-416c-9040-0799b2b4b894\n```\n\n### Fine-tuning\n\n```bash\n# Help\nmagics fine-tuning --help\n\n# Create fine-tune job\nmagics fine-tuning create \\\n  --model magicscomputer/llama-2-7b-chat \\\n  --training-file file-711d8724-b3e3-4ae2-b516-94841958117d\n\n# List fine-tune jobs\nmagics fine-tuning list\n\n# Retrieve fine-tune job details\nmagics fine-tuning retrieve ft-c66a5c18-1d6d-43c9-94bd-32d756425b4b\n\n# List fine-tune job events\nmagics fine-tuning list-events ft-c66a5c18-1d6d-43c9-94bd-32d756425b4b\n\n# Cancel running job\nmagics fine-tuning cancel ft-c66a5c18-1d6d-43c9-94bd-32d756425b4b\n\n# Download fine-tuned model weights\nmagics fine-tuning download ft-c66a5c18-1d6d-43c9-94bd-32d756425b4b\n```\n\n### Models\n\n```bash\n# Help\nmagics models --help\n\n# List models\nmagics models list\n```\n\n\n",
    "bugtrack_url": null,
    "license": "Apache-2.0",
    "summary": "Python client for Magics's Cloud Platform!",
    "version": "0.0.2",
    "project_urls": null,
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "1ec4ab1fd48789cb685b15b1ea0906113f2638aebbd3bd8a7a88738f6d254b23",
                "md5": "2ea72ead25d29cbb98be343d5195387d",
                "sha256": "a25893fd0ad59c87992a6bb48f27ca0af3df8d9d3bb6dfee0bfcabdf5e5ac77b"
            },
            "downloads": -1,
            "filename": "magics_python-0.0.2-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "2ea72ead25d29cbb98be343d5195387d",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 69312,
            "upload_time": "2024-10-13T04:21:08",
            "upload_time_iso_8601": "2024-10-13T04:21:08.058759Z",
            "url": "https://files.pythonhosted.org/packages/1e/c4/ab1fd48789cb685b15b1ea0906113f2638aebbd3bd8a7a88738f6d254b23/magics_python-0.0.2-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "70bb356e804b292d63d86265f39222f4c91abdcdd2ba8c4e8e9313bd2da1e935",
                "md5": "c414efbc70e783123b1ad176c0dac183",
                "sha256": "40a916244ca7c206c3bbe8620f21635b4759c4edbd4a4ad513f6e35e08d48a70"
            },
            "downloads": -1,
            "filename": "magics-python-0.0.2.tar.gz",
            "has_sig": false,
            "md5_digest": "c414efbc70e783123b1ad176c0dac183",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 50212,
            "upload_time": "2024-10-13T04:21:09",
            "upload_time_iso_8601": "2024-10-13T04:21:09.550339Z",
            "url": "https://files.pythonhosted.org/packages/70/bb/356e804b292d63d86265f39222f4c91abdcdd2ba8c4e8e9313bd2da1e935/magics-python-0.0.2.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-10-13 04:21:09",
    "github": false,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "lcname": "magics-python"
}
        
Elapsed time: 0.38213s