# SDK design

## 🧩 AI1NET SDK

Supports:

* Multi-model access
* Smart routing
* Streaming
* Token usage tracking

***

## 🟨 JavaScript SDK

### &#x20;Install

```bash
npm install ai1net
```

***

### Basic Usage

```ts
import AI1NET from "ai1net"

const client = new AI1NET({
  apiKey: "your-api-key"
})

const res = await client.generate({
  input: "Explain AI in simple terms"
})

console.log(res.output)
```

***

### Specify Model (Optional)

```ts
await client.generate({
  model: "gpt-like",
  input: "Write a tweet about AI"
})
```

***

Smart Routing (Default)

```ts
await client.generate({
  route: "auto", // default
  input: "Best AI for coding?"
})
```

***

### Advanced Parameters

```ts
await client.generate({
  input: "Write a story",
  parameters: {
    max_tokens: 200,
    temperature: 0.8
  }
})
```

***

### Streaming Response

```ts
const stream = await client.stream({
  input: "Tell me a long story"
})

for await (const chunk of stream) {
  process.stdout.write(chunk.delta)
}
```

***

### Image Generation

```ts
const res = await client.image.generate({
  input: "Cyberpunk city at night",
  size: "1024x1024"
})

console.log(res.image_url)
```

***

### Response Format

```ts
{
  output: "AI response...",
  model: "provider/model-name",
  usage: {
    input_tokens: 10,
    output_tokens: 120
  },
  latency_ms: 210
}
```

***

### Full SDK Implementation (Simplified)

```ts
class AI1NET {
  constructor({ apiKey, baseURL = "https://api.ai1net.io" }) {
    this.apiKey = apiKey
    this.baseURL = baseURL
  }

  async generate({ input, model, route = "auto", parameters = {} }) {
    const res = await fetch(`${this.baseURL}/v1/generate`, {
      method: "POST",
      headers: {
        "Authorization": `Bearer ${this.apiKey}`,
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        input,
        model,
        route,
        parameters
      })
    })

    return res.json()
  }

  async stream({ input }) {
    const res = await fetch(`${this.baseURL}/v1/stream`, {
      method: "POST",
      headers: {
        "Authorization": `Bearer ${this.apiKey}`,
        "Content-Type": "application/json"
      },
      body: JSON.stringify({ input })
    })

    const reader = res.body.getReader()
    const decoder = new TextDecoder()

    return {
      async *[Symbol.asyncIterator]() {
        while (true) {
          const { done, value } = await reader.read()
          if (done) break
          yield JSON.parse(decoder.decode(value))
        }
      }
    }
  }

  image = {
    generate: async ({ input, size = "1024x1024" }) => {
      const res = await fetch(`${this.baseURL}/v1/image`, {
        method: "POST",
        headers: {
          "Authorization": `Bearer ${this.apiKey}`,
          "Content-Type": "application/json"
        },
        body: JSON.stringify({ input, size })
      })

      return res.json()
    }
  }
}

export default AI1NET
```

***

## 🐍 Python SDK

### Install

```bash
pip install ai1net
```

***

### Basic Usage

```python
from ai1net import AI1NET

client = AI1NET(api_key="your-api-key")

res = client.generate(
    input="Explain AI simply"
)

print(res["output"])
```

***

### Model Selection

```python
client.generate(
    model="gpt-like",
    input="Write a blog intro"
)
```

***

### Advanced Parameters

```python
client.generate(
    input="Write a story",
    parameters={
        "max_tokens": 200,
        "temperature": 0.7
    }
)
```

***

### Streaming

```python
for chunk in client.stream(input="Tell me a story"):
    print(chunk["delta"], end="")
```

***

### Image Generation

```python
res = client.image.generate(
    input="Futuristic AI robot",
    size="1024x1024"
)

print(res["image_url"])
```

***

### Full SDK Implementation (Simplified)

```python
import requests

class AI1NET:
    def __init__(self, api_key, base_url="https://api.ai1net.io"):
        self.api_key = api_key
        self.base_url = base_url

    def _headers(self):
        return {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json"
        }

    def generate(self, input, model=None, route="auto", parameters=None):
        res = requests.post(
            f"{self.base_url}/v1/generate",
            headers=self._headers(),
            json={
                "input": input,
                "model": model,
                "route": route,
                "parameters": parameters or {}
            }
        )
        return res.json()

    def stream(self, input):
        res = requests.post(
            f"{self.base_url}/v1/stream",
            headers=self._headers(),
            json={"input": input},
            stream=True
        )

        for line in res.iter_lines():
            if line:
                yield eval(line.decode())

    class Image:
        def __init__(self, parent):
            self.parent = parent

        def generate(self, input, size="1024x1024"):
            res = requests.post(
                f"{self.parent.base_url}/v1/image",
                headers=self.parent._headers(),
                json={"input": input, "size": size}
            )
            return res.json()

    @property
    def image(self):
        return self.Image(self)
```

***

## SDK Design Philosophy

AI1NET SDK is built to be:

* **Simple** → 1 function to start (`generate`)
* **Flexible** → optional model selection
* **Smart** → routing by default
* **Extensible** → supports all AI types
* **Unified** → same interface for all models

***

## What This Unlocks

With this SDK:

* Devs can integrate AI in **minutes**
* Providers get **more usage automatically**
* AI1NET becomes **the default AI layer**

***


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.ai1net.xyz/for-ai-providers/sdk-design.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
