در این بخش، نمونه کدهایی برای فراخوانی API در زبانهای برنامهنویسی مختلف ارائه شده است.
<?php
function callHooshService($token, $query, $action = "text")
{
$url = 'https://HOOSHSERVICE-API-URL/' . $action;
$postData = ['prompt' => $query];
$jsonData = json_encode($postData);
$headers = [
'Authorization: Bearer ' . $token,
'Content-Type: application/json',
'Content-Length: ' . strlen($jsonData),
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 300);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
// --- Example Usage ---
$api_token = "YOUR_API_TOKEN";
$user_query = "Tell me five interesting facts about the Milky Way galaxy.";
$result_json = callHooshService($api_token, $user_query, "text");
$result_data = json_decode($result_json, true);
if (isset($result_data['status']) && $result_data['status'] === 'success') {
echo "AI Response: " . $result_data['result'];
} else {
echo "API Error: " . ($result_data['message'] ?? 'Unknown error');
}
?>
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
public class HooshServiceClient
{
private readonly HttpClient _httpClient;
private const string ApiBaseUrl = "https://HOOSHSERVICE-API-URL/";
public HooshServiceClient(string apiToken)
{
_httpClient = new HttpClient();
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiToken);
}
public async Task<string> GetTextResponseAsync(string prompt)
{
var requestData = new { prompt };
var jsonContent = new StringContent(JsonSerializer.Serialize(requestData), Encoding.UTF8, "application/json");
HttpResponseMessage response = await _httpClient.PostAsync(ApiBaseUrl + "text", jsonContent);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsStringAsync();
}
}
// --- Example Usage ---
public class Program
{
public static async Task Main(string[] args)
{
var apiToken = "YOUR_API_TOKEN";
var client = new HooshServiceClient(apiToken);
string prompt = "Name three European capitals.";
string jsonResponse = await client.GetTextResponseAsync(prompt);
Console.WriteLine(jsonResponse);
}
}
import requests
import json
def call_hoosh_service(token, query, action="text"):
api_url = f"https://HOOSHSERVICE-API-URL/{action}"
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json"
}
payload = {"prompt": query}
try:
response = requests.post(api_url, headers=headers, json=payload, timeout=300)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
return {"status": "error", "message": str(e)}
# --- Example Usage ---
api_token = "YOUR_API_TOKEN"
user_query = "How can I become a better programmer?"
result = call_hoosh_service(api_token, user_query, "text")
if result.get("status") == "success":
print(f"AI Response: {result.get('result')}")
else:
print(f"API Error: {result.get('message', 'Unknown error')}")
async function callHooshService(token, query, action = 'text') {
const apiUrl = `https://HOOSHSERVICE-API-URL/${action}`;
const headers = {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
};
const payload = {prompt: query};
try {
const response = await fetch(apiUrl, {
method: 'POST',
headers: headers,
body: JSON.stringify(payload)
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({ message: response.statusText }));
throw new Error(`API Error: ${response.status} - ${errorData.message}`);
}
return await response.json();
} catch (error) {
console.error('Request Failed:', error);
return { status: 'error', message: error.message };
}
}
// --- Example Usage ---
const apiToken = 'YOUR_API_TOKEN';
const userQuery = 'What is the difference between UI and UX?';
(async () => {
const result = await callHooshService(apiToken, userQuery, 'text');
if (result && result.status === 'success') {
console.log('AI Response:', result.result);
} else {
console.error('Failed to get response:', result.message);
}
})();