API, OpenAI, Anthropic, Google·

چطور از API های هوش مصنوعی استفاده کنیم

آموزشی تکمیلی جهتف استفاده از API های هوش مصنوعی توسط روز دنیا

مقدمه

رابط‌های برنامه‌نویسی کاربردی (API) سازگار با OpenAI به شما امکان می‌دهند تا از مدل‌های زبانی قدرتمند مشابه ChatGPT در سرورهای خود استفاده کنید. این راهنما نحوه استفاده از این API‌ها را با زبان‌های برنامه‌نویسی مختلف و سرور شخصی شما در https://api.ahur.ir/v1 نشان می‌دهد.

api

code

server

معرفی OpenAI Compatible APIs

رابط‌های API سازگار با OpenAI به شما اجازه می‌دهند تا از مدل‌های زبانی پیشرفته در سرور خود استفاده کنید. این API‌ها با نسخه اصلی OpenAI سازگار هستند و می‌توانید به راحتی کدهای موجود خود را با تغییر URL به سرور شخصی خود منتقل کنید.

python

javascript

curl

go

rust

java

راهنمای استفاده

استفاده با Python

python

برای استفاده از Python، کتابخانه رسمی OpenAI را نصب کنید ```bash pip install openai


سپس کد زیر را:
استفاده کنید:
```python
from openai import OpenAI

client = OpenAI(
    base_url="https://api.ahur.ir/v1",
    api_key="your-api-key"  # کلید API خود را وارد کنید
)

response = client.chat.completions.create(
    model="gpt-3.5-turbo",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "Hello! How are you?"}
    ]
)

print(response.choices[0].message.content)

::

همچنین می‌توانید از کتابخانه requests استفاده کنید:

import requests

url = "https://api.ahur.ir/v1/chat/completions"
headers = {
  "Content-Type": "application/json",
  "Authorization": "Bearer your-api-key"
}
data = {
  "model": "gpt-3.5-turbo",
  "messages": [
      {"role": "system", "content": "You are a helpful assistant."},
      {"role": "user", "content": "Hello! How are you?"}
  ]
}

response = requests.post(url, headers=headers, json=data)
print(response.json()["choices"][0]["message"]["content"])

استفاده با JavaScript/Node.js

javascript

ابتدا کتابخانه openai را نصب کنید:

npm install openai

سپس کد زیر را استفاده کنید:

import OpenAI from 'openai';

const openai = new OpenAI({
    baseURL: 'https://api.ahur.ir/v1',
    apiKey: 'your-api-key' // کلید API خود را وارد کنید
});

async function main() {
    const chatCompletion = await openai.chat.completions.create({
        model: 'gpt-3.5-turbo',
        messages: [
            {role: 'system', content: 'You are a helpful assistant.'},
            {role: 'user', content: 'Hello! How are you?'}
        ],
    });

    console.log(chatCompletion.choices[0].message.content);
}

main();

می‌توانید از Axios نیز استفاده کنید:

import axios from 'axios';

const url = 'https://api.ahur.ir/v1/chat/completions';
const headers = {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer your-api-key'
};
const data = {
    model: 'gpt-3.5-turbo',
    messages: [
        {role: 'system', content: 'You are a helpful assistant.'},
        {role: 'user', content: 'Hello! How are you?'}
    ]
};

axios.post(url, data, {headers})
    .then(response => {
        console.log(response.data.choices[0].message.content);
    })
    .catch(error => console.error(error));

استفاده با cURL

curl

در ترمینال خود از دستور زیر استفاده کنید:

curl https://api.ahur.ir/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer your-api-key" \
  -d '{
    "model": "gpt-3.5-turbo",
    "messages": [
      {"role": "system", "content": "You are a helpful assistant."},
      {"role": "user", "content": "Hello! How are you?"}
    ]
  }'

برای دریافت پاسخ به صورت استریم:

curl https://api.ahur.ir/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer your-api-key" \
  -d '{
    "model": "gpt-3.5-turbo",
    "messages": [
      {"role": "user", "content": "Count to 5"}
    ],
    "stream": true
  }'

استفاده با Go

go

بسته‌های لازم را نصب کنید:

go get github.com/sashabaranov/go-openai

کد Go:

package main

import (
    "context"
    "fmt"
    openai "github.com/sashabaranov/go-openai"
)

func main() {
    client := openai.NewClientWithOpts(
        openai.WithBaseURL("https://api.ahur.ir/v1"),
        openai.WithAPIKey("your-api-key"),
    )

    resp, err := client.CreateChatCompletion(
        context.Background(),
        openai.ChatCompletionRequest{
            Model: openai.GPT3Dot5Turbo,
            Messages: []openai.ChatCompletionMessage{
                {Role: openai.ChatMessageRoleSystem, Content: "You are a helpful assistant."},
                {Role: openai.ChatMessageRoleUser, Content: "Hello! How are you?"},
            },
        },
    )

    if err != nil {
        fmt.Printf("ChatCompletion error: %v\n", err)
        return
    }

    fmt.Println(resp.Choices[0].Message.Content)
}

بدون کتابخانه خارجی:

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "net/http"
)

type Request struct {
    Model    string        `json:"model"`
    Messages []Message     `json:"messages"`
}

type Message struct {
    Role    string `json:"role"`
    Content string `json:"content"`
}

func main() {
    url := "https://api.ahur.ir/v1/chat/completions"
    
    reqBody := Request{
        Model: "gpt-3.5-turbo",
        Messages: []Message{
            {Role: "system", Content: "You are a helpful assistant."},
            {Role: "user", Content: "Hello! How are you?"},
        },
    }

    body, _ := json.Marshal(reqBody)
    
    req, _ := http.NewRequest("POST", url, bytes.NewBuffer(body))
    req.Header.Set("Content-Type", "application/json")
    req.Header.Set("Authorization", "Bearer your-api-key")

    client := &http.Client{}
    resp, _ := client.Do(req)
    defer resp.Body.Close()

    var result map[string]interface{}
    json.NewDecoder(resp.Body).Decode(&result)
    
    choices := result["choices"].([]interface{})
    message := choices[0].(map[string]interface{})["message"].(map[string]interface{})
    fmt.Println(message["content"])
}

استفاده با Rust

rust

وابستگی را به Cargo.toml اضافه کنید:

[dependencies]
reqwest = { version = "0.11", features = ["json"] }
tokio = { version = "1", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"

کد Rust:

use reqwest::Client;
use serde::{Deserialize, Serialize};

#[derive(Serialize)]
struct ChatRequest {
    model: String,
    messages: Vec<Message>,
}

#[derive(Serialize)]
struct Message {
    role: String,
    content: String,
}

#[derive(Deserialize)]
struct ChatResponse {
    choices: Vec<Choice>,
}

#[derive(Deserialize)]
struct Choice {
    message: ResponseMessage,
}

#[derive(Deserialize)]
struct ResponseMessage {
    content: String,
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = Client::new();

    let request = ChatRequest {
        model: "gpt-3.5-turbo".to_string(),
        messages: vec![
            Message { role: "system".to_string(), content: "You are a helpful assistant.".to_string() },
            Message { role: "user".to_string(), content: "Hello! How are you?".to_string() },
        ],
    };

    let response = client
        .post("https://api.ahur.ir/v1/chat/completions")
        .header("Content-Type", "application/json")
        .header("Authorization", "Bearer your-api-key")
        .json(&request)
        .send()
        .await?;

    let result: ChatResponse = response.json().await?;
    println!("{}", result.choices[0].message.content);

    Ok(())
}

نسخه با async/await بیشتر:

use reqwest::Client;
use serde::{Deserialize, Serialize};

#[derive(Serialize, Debug)]
struct Message {
    role: String,
    content: String,
}

#[derive(Serialize, Debug)]
struct ChatRequest {
    model: String,
    messages: Vec<Message>,
    stream: Option<bool>,
}

#[derive(Deserialize, Debug)]
struct Choice {
    message: Message,
}

#[derive(Deserialize, Debug)]
struct Response {
    choices: Vec<Choice>,
}

async fn call_api(api_key: &str, content: &str) -> Result<String, Box<dyn std::error::Error>> {
    let client = Client::new();

    let request = ChatRequest {
        model: "gpt-3.5-turbo".to_string(),
        messages: vec![
            Message { role: "system".to_string(), content: "You are a helpful assistant.".to_string() },
            Message { role: "user".to_string(), content: content.to_string() },
        ],
        stream: Some(false),
    };

    let response = client
        .post("https://api.ahur.ir/v1/chat/completions")
        .header("Content-Type", "application/json")
        .header("Authorization", format!("Bearer {}", api_key))
        .json(&request)
        .send()
        .await?;

    let result: Response = response.json().await?;
    Ok(result.choices[0].message.content)
}

استفاده با PHP

php

با استفاده از cURL در PHP:

<?php

$url = "https://api.ahur.ir/v1/chat/completions";
$apiKey = "your-api-key";

$data = [
    "model" => "gpt-3.5-turbo",
    "messages" => [
        ["role" => "system", "content" => "You are a helpful assistant."],
        ["role" => "user", "content" => "Hello! How are you?"]
    ]
];

$ch = curl_init($url);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Content-Type: application/json",
    "Authorization: Bearer " . $apiKey
]);

$response = curl_exec($ch);
curl_close($ch);

$result = json_decode($response, true);
echo $result['choices'][0]['message']['content'];
?>

با استفاده از کتابخانه Guzzle:

<?php

require 'vendor/autoload.php';

$client = new \GuzzleHttp\Client([
    'base_uri' => 'https://api.ahur.ir/v1',
]);

$response = $client->post('chat/completions', [
    'headers' => [
        'Authorization' => 'Bearer your-api-key',
        'Content-Type' => 'application/json',
    ],
    'json' => [
        'model' => 'gpt-3.5-turbo',
        'messages' => [
            ['role' => 'system', 'content' => 'You are a helpful assistant.'],
            ['role' => 'user', 'content' => 'Hello! How are you?']
        ],
    ],
]);

$result = json_decode($response->getBody(), true);
echo $result['choices'][0]['message']['content'];
?>

کاربردهای عملی

چت بات

یکی از محبوب‌ترین کاربردها، ساخت چت بات است:

from openai import OpenAI

client = OpenAI(
    base_url="https://api.ahur.ir/v1",
    api_key="your-api-key"
)

def chat_with_ai(prompt):
    response = client.chat.completions.create(
        model="gpt-3.5-turbo",
        messages=[
            {"role": "system", "content": "You are a helpful AI assistant."},
            {"role": "user", "content": prompt}
        ]
    )
    return response.choices[0].message.content

while True:
    user_input = input("You: ")
    if user_input.lower() in ["exit", "quit"]:
        break
    response = chat_with_ai(user_input)
    print(f"AI: {response}")
import OpenAI from 'openai';

const openai = new OpenAI({
    baseURL: 'https://api.ahur.ir/v1',
    apiKey: 'your-api-key'
});

async function chat(prompt) {
    const response = await openai.chat.completions.create({
        model: 'gpt-3.5-turbo',
        messages: [
            {role: 'system', content: 'You are a helpful AI assistant.'},
            {role: 'user', content: prompt}
        ],
    });
    return response.choices[0].message.content;
}

// استفاده در یک برنامه وب
document.getElementById('sendBtn').addEventListener('click', async () => {
    const input = document.getElementById('userInput').value;
    const response = await chat(input);
    document.getElementById('output').innerText = response;
});

تولید متن

تولید متن با مدل‌های مختلف:

from openai import OpenAI

client = OpenAI(
    base_url="https://api.ahur.ir/v1",
    api_key="your-api-key"
)

# مقاله
article = client.chat.completions.create(
    model="gpt-3.5-turbo",
    messages=[
        {"role": "user", "content": "Write an article about AI"}
    ]
)

# کد نویسی
code = client.chat.completions.create(
    model="gpt-3.5-turbo",
    messages=[
        {"role": "user", "content": "Write a Python function to sort an array"}
    ]
)

# ترجمه
translate = client.chat.completions.create(
    model="gpt-3.5-turbo",
    messages=[
        {"role": "user", "content": "Translate 'Hello' to Persian"}
    ]
)

استفاده از Embedding برای جستجوی معنایی:

from openai import OpenAI

client = OpenAI(
    base_url="https://api.ahur.ir/v1",
    api_key="your-api-key"
)

response = client.embeddings.create(
    model="text-embedding-ada-002",
    input="The quick brown fox jumps over the lazy dog"
)

embedding = response.data[0].embedding
print(f"Embedding dimension: {len(embedding)}")

استریم پاسخ

دریافت پاسخ به صورت استریم:

from openai import OpenAI

client = OpenAI(
    base_url="https://api.ahur.ir/v1",
    api_key="your-api-key"
)

stream = client.chat.completions.create(
    model="gpt-3.5-turbo",
    messages=[{"role": "user", "content": "Write a story about a cat"}],
    stream=True
)

for chunk in stream:
    if chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="")

در JavaScript:

import OpenAI from 'openai';

const openai = new OpenAI({
    baseURL: 'https://api.ahur.ir/v1',
    apiKey: 'your-api-key'
});

const stream = await openai.chat.completions.create({
    model: 'gpt-3.5-turbo',
    messages: [{role: 'user', content: 'Write a story about a cat'}],
    stream: true,
});

for await (const chunk of stream) {
    process.stdout.write(chunk.choices[0]?.delta?.content || '');
}

نتیجه‌گیری

رابط‌های API سازگار با OpenAI ابزار قدرتمندی هستند که به شما امکان می‌دهند از قابلیت‌های هوش مصنوعی در برنامه‌های خود استفاده کنید. با استفاده از سرور شخصی در https://api.ahur.ir/v1 می‌توانید از این امکانات با کنترل بیشتر و حریم خصوصی بهتر بهره‌مند شوید.


منابع

ویژگی‌ها

شرکت

© 2026 پلتفرم هوش مصنوعی اهور. تمام حقوق محفوظ است.