Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions .github/workflows/run-javascript-midjourney.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
name: Run JavaScript Midjourney Example

on:
workflow_dispatch:
inputs:
prompt:
description: 'Midjourney prompt for image generation'
required: false
default: 'A beautiful sunset over the snow mountains --v 7'
type: string

jobs:
run-example:
runs-on: ubuntu-latest

steps:
- name: Checkout repository
uses: actions/checkout@v4

- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'
cache-dependency-path: examples/javascript/package-lock.json

- name: Install dependencies
working-directory: examples/javascript
run: npm ci

- name: Create .env file
working-directory: examples/javascript
run: |
echo "LEGNEXT_API_KEY=${{ secrets.LEGNEXT_API_KEY }}" >> .env
echo "LEGNEXT_API_BASE=https://api.legnext.ai/api" >> .env

- name: Run Midjourney example
working-directory: examples/javascript
run: node midjourney-example.js
env:
PROMPT: ${{ inputs.prompt }}

- name: Upload execution logs
if: always()
uses: actions/upload-artifact@v4
with:
name: execution-logs-${{ github.run_number }}
path: examples/javascript/*.log
if-no-files-found: ignore
49 changes: 49 additions & 0 deletions .github/workflows/run-python-midjourney.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
name: Run Python Midjourney Example

on:
workflow_dispatch:
inputs:
prompt:
description: 'Midjourney prompt for image generation'
required: false
default: 'A beautiful sunset over the snow mountains --v 7'
type: string

jobs:
run-example:
runs-on: ubuntu-latest

steps:
- name: Checkout repository
uses: actions/checkout@v4

- name: Setup Python
uses: actions/setup-python@v5
with:
python-version: '3.11'
cache: 'pip'
cache-dependency-path: examples/python/requirements.txt

- name: Install dependencies
working-directory: examples/python
run: pip install -r requirements.txt

- name: Create .env file
working-directory: examples/python
run: |
echo "LEGNEXT_API_KEY=${{ secrets.LEGNEXT_API_KEY }}" >> .env
echo "LEGNEXT_API_BASE=https://api.legnext.ai/api" >> .env

- name: Run Midjourney example
working-directory: examples/python
run: python midjourney_example.py
env:
PROMPT: ${{ inputs.prompt }}

- name: Upload execution logs
if: always()
uses: actions/upload-artifact@v4
with:
name: execution-logs-${{ github.run_number }}
path: examples/python/*.log
if-no-files-found: ignore
6 changes: 5 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,6 @@
.env
node_modules/
node_modules/
__pycache__/
*.pyc
*.pyo
*.pyd
7 changes: 6 additions & 1 deletion examples/javascript/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,9 @@

# OpenAI API key for authenticating requests
OPENAI_API_KEY=YOUR_TOKEN_HERE
OPENAI_API_BASE=https://api.deep.assistant.run.place/v1
OPENAI_API_BASE=https://api.deep.assistant.run.place/v1

# Legnext API key for Midjourney image generation
# Get your API key from https://legnext.ai/app/api-keys
LEGNEXT_API_KEY=YOUR_LEGNEXT_API_KEY
LEGNEXT_API_BASE=https://api.legnext.ai/api
46 changes: 37 additions & 9 deletions examples/javascript/README.md
Original file line number Diff line number Diff line change
@@ -1,41 +1,69 @@
# JavaScript Example

This example demonstrates how to use the Deep.Assistant API with JavaScript/Node.js and the OpenAI SDK.
This directory contains examples for using different APIs with JavaScript/Node.js.

## Examples

1. **Deep.Assistant API** (`example.js`) - OpenAI-compatible API gateway
2. **Midjourney API via Legnext** (`midjourney-example.js`) - Generate images using Midjourney

## Setup

1. Copy the example environment file and configure your API credentials:
```bash
cp .env.example .env
```

Then edit `.env` with your API credentials:
```env
# For Deep.Assistant API
OPENAI_API_KEY=YOUR_TOKEN_HERE
OPENAI_API_BASE=https://api.deep.assistant.run.place/v1

# For Legnext Midjourney API
LEGNEXT_API_KEY=YOUR_LEGNEXT_API_KEY
LEGNEXT_API_BASE=https://api.legnext.ai/api
```

2. Install dependencies:
```bash
npm install
```

## Running the Example
## Running the Examples

### Deep.Assistant API Example

```bash
npm start
# or
node example.js
```

## Code Overview

The example uses:
This example uses:
- `openai` - OpenAI JavaScript SDK
- `dotenv` - Environment variable loading from .env file
- Standard OpenAI environment variables (`OPENAI_API_KEY`, `OPENAI_BASE_URL`, `OPENAI_API_BASE`)

## API Key
### Midjourney API Example

```bash
npm run midjourney
# or
node midjourney-example.js
```

This example demonstrates:
- Creating an image generation job with a text prompt
- Polling for job completion
- Retrieving the generated image URL

The example uses:
- `node-fetch` - HTTP client for API requests
- `dotenv` - Environment variable loading from .env file
- Legnext API for unofficial Midjourney access

## API Keys

Get your API key from the Telegram bot: https://t.me/DeepGPTBot
Use the `/api` command to obtain your key.
- **Deep.Assistant API Key**: Get from the Telegram bot at https://t.me/DeepGPTBot (use `/api` command)
- **Legnext API Key**: Get from https://legnext.ai/app/api-keys
130 changes: 130 additions & 0 deletions examples/javascript/midjourney-example.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
import dotenv from 'dotenv';
import fetch from 'node-fetch';

// Load environment variables from .env file
dotenv.config();

const LEGNEXT_API_KEY = process.env.LEGNEXT_API_KEY || "YOUR_LEGNEXT_API_KEY";
const LEGNEXT_API_BASE = process.env.LEGNEXT_API_BASE || "https://api.legnext.ai/api";

/**
* Generate an image using Midjourney via Legnext API
* @param {string} prompt - Text prompt for image generation
* @returns {Promise<object>} - Job creation response
*/
async function generateImage(prompt) {
const response = await fetch(`${LEGNEXT_API_BASE}/v1/diffusion`, {
method: 'POST',
headers: {
'x-api-key': LEGNEXT_API_KEY,
'Content-Type': 'application/json'
},
body: JSON.stringify({
text: prompt
})
});

if (!response.ok) {
const error = await response.text();
throw new Error(`Failed to generate image: ${response.status} - ${error}`);
}

return await response.json();
}

/**
* Check the status of a job
* @param {string} jobId - Job ID to check
* @returns {Promise<object>} - Job status response
*/
async function getJobStatus(jobId) {
const response = await fetch(`${LEGNEXT_API_BASE}/v1/job/${jobId}`, {
method: 'GET',
headers: {
'x-api-key': LEGNEXT_API_KEY
}
});

if (!response.ok) {
const error = await response.text();
throw new Error(`Failed to get job status: ${response.status} - ${error}`);
}

return await response.json();
}

/**
* Wait for job completion by polling
* @param {string} jobId - Job ID to wait for
* @param {number} maxAttempts - Maximum number of polling attempts (default: 60)
* @param {number} intervalMs - Interval between polls in milliseconds (default: 5000)
* @returns {Promise<object>} - Completed job details
*/
async function waitForCompletion(jobId, maxAttempts = 60, intervalMs = 5000) {
for (let i = 0; i < maxAttempts; i++) {
const job = await getJobStatus(jobId);

console.log(`[${i + 1}/${maxAttempts}] Job status: ${job.status}`);

if (job.status === 'completed') {
return job;
} else if (job.status === 'failed') {
throw new Error(`Job failed: ${job.error || 'Unknown error'}`);
}

// Wait before next poll
await new Promise(resolve => setTimeout(resolve, intervalMs));
}

throw new Error('Job did not complete within the maximum wait time');
}

async function main() {
try {
console.log('Starting Midjourney image generation via Legnext API...\n');

const prompt = "A beautiful sunset over the snow mountains --v 7";
console.log(`Prompt: ${prompt}\n`);

// Step 1: Generate image
console.log('Step 1: Submitting image generation request...');
const createResponse = await generateImage(prompt);
const jobId = createResponse.job_id;
console.log(`✓ Job created with ID: ${jobId}\n`);

// Step 2: Wait for completion
console.log('Step 2: Waiting for image generation to complete...');
const completedJob = await waitForCompletion(jobId);

// Step 3: Display results
console.log('\n✓ Image generation completed!\n');
console.log('Results:');
console.log(`- Job ID: ${completedJob.job_id}`);
console.log(`- Status: ${completedJob.status}`);
console.log(`- Model: ${completedJob.model}`);

if (completedJob.output && completedJob.output.image_url) {
console.log(`\nGenerated Image URL:`);
console.log(completedJob.output.image_url);
}

if (completedJob.output && completedJob.output.actions) {
console.log(`\nAvailable Actions:`);
completedJob.output.actions.forEach(action => {
console.log(`- ${action}`);
});
}

if (completedJob.meta) {
console.log(`\nMetadata:`);
console.log(`- Created: ${completedJob.meta.created_at}`);
console.log(`- Completed: ${completedJob.meta.completed_at}`);
}

} catch (error) {
console.error('Error:', error.message);
process.exit(1);
}
}

main();
6 changes: 4 additions & 2 deletions examples/javascript/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,13 @@
"main": "example.js",
"scripts": {
"test": "node example.js",
"start": "node example.js"
"start": "node example.js",
"midjourney": "node midjourney-example.js"
},
"dependencies": {
"openai": "^4.0.0",
"dotenv": "^16.0.0"
"dotenv": "^16.0.0",
"node-fetch": "^3.3.0"
},
"keywords": ["openai", "api", "testing"],
"author": "Deep.Assistant",
Expand Down
7 changes: 6 additions & 1 deletion examples/python/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,9 @@

# OpenAI API key for authenticating requests
OPENAI_API_KEY=YOUR_TOKEN_HERE
OPENAI_API_BASE=https://api.deep.assistant.run.place/v1
OPENAI_API_BASE=https://api.deep.assistant.run.place/v1

# Legnext API key for Midjourney image generation
# Get your API key from https://legnext.ai/app/api-keys
LEGNEXT_API_KEY=YOUR_LEGNEXT_API_KEY
LEGNEXT_API_BASE=https://api.legnext.ai/api
Loading