1. Go to this page and download the library: Download sanjarani/openai-laravel library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
sanjarani / openai-laravel example snippets
use Sanjarani\OpenAI\Facades\OpenAI;
// مثال برای Chat API
$messages = [
["role" => "system", "content" => "You are a helpful assistant."],
["role" => "user", "content" => "Hello! Who are you?"],
];
$response = OpenAI::chat()->create($messages);
echo $response["choices"][0]["message"]["content"];
use Sanjarani\OpenAI\Facades\OpenAI;
use Sanjarani\OpenAI\Exceptions\OpenAIException;
try {
$response = OpenAI::chat()->create([["role" => "user", "content" => "Hello"]]);
} catch (OpenAIException $e) {
// $e->getMessage() پیام اصلی خطا
// $e->getCode() کد وضعیت HTTP یا کد خطای داخلی
// $e->getErrorDetails() آرایهای از جزئیات خطا از API (در صورت وجود)
logger()->error("OpenAI API Error: " . $e->getMessage(), ["details" => $e->getErrorDetails()]);
}
$response = OpenAI::chat()->create($messages);
if (isset($response["_from_cache"]) && $response["_from_cache"] === true) {
echo "Response was retrieved from cache!";
}
$messages = [
["role" => "user", "content" => "Translate 'Hello, world!' to French."],
];
$options = [
"model" => "gpt-4o", // اختیاری، از مقدار پیشفرض در کانفیگ استفاده میکند
"temperature" => 0.7,
"max_tokens" => 50,
];
$response = OpenAI::chat()->create($messages, $options);
// $response["choices"][0]["message"]["content"]
$messages = [
["role" => "user", "content" => "Tell me a short story."],
];
$stream = OpenAI::chat()->createStream($messages);
foreach ($stream as $responseChunk) {
// پردازش هر قطعه از پاسخ
// $responseChunk["choices"][0]["delta"]["content"]
if (isset($responseChunk["choices"][0]["delta"]["content"])) {
echo $responseChunk["choices"][0]["delta"]["content"];
}
if (($responseChunk["choices"][0]["finish_reason"] ?? null) === "stop") {
// پایان جریان
break;
}
}
$prompt = "Write a tagline for an ice cream shop.";
$options = [
"model" => "gpt-3.5-turbo-instruct",
"max_tokens" => 30,
];
$response = OpenAI::completions()->create($prompt, $options);
// $response["choices"][0]["text"]
$prompt = "Once upon a time...";
$stream = OpenAI::completions()->createStream($prompt);
foreach ($stream as $responseChunk) {
// $responseChunk["choices"][0]["text"]
if (isset($responseChunk["choices"][0]["text"])) {
echo $responseChunk["choices"][0]["text"];
}
if (($responseChunk["choices"][0]["finish_reason"] ?? null) === "stop") {
break;
}
}
$input = "The quick brown fox jumps over the lazy dog";
$options = [
"model" => "text-embedding-3-small", // یا text-embedding-3-large
];
$response = OpenAI::embeddings()->create($input, $options);
// $response["data"][0]["embedding"] (آرایهای از اعداد float)
$prompt = "A futuristic cityscape with flying cars, digital art";
$options = [
"model" => "dall-e-3", // یا dall-e-2
"n" => 1,
"size" => "1024x1024", // برای dall-e-3: 1024x1024, 1792x1024, 1024x1792
"response_format" => "url", // یا b64_json
"quality" => "standard", // برای dall-e-3: standard, hd
"style" => "vivid" // برای dall-e-3: vivid, natural
];
$response = OpenAI::images()->create($prompt, $options);
// $response["data"][0]["url"] یا $response["data"][0]["b64_json"]
$imagePath = "/path/to/your/image.png"; // تصویر مربعی PNG کمتر از ۴ مگابایت
$prompt = "Add a sun wearing sunglasses to the sky";
$options = [
"mask" => "/path/to/your/mask.png", // اختیاری، تصویر PNG با همان ابعاد تصویر اصلی
"n" => 1,
"size" => "1024x1024",
];
$response = OpenAI::images()->edit($imagePath, $prompt, $options);
// $response["data"][0]["url"]
$imagePath = "/path/to/your/image.png"; // تصویر مربعی PNG کمتر از ۴ مگابایت
$options = [
"n" => 1,
"size" => "1024x1024",
];
$response = OpenAI::images()->createVariation($imagePath, $options);
// $response["data"][0]["url"]
$input = "Some potentially problematic text.";
$options = [
"model" => "text-moderation-latest", // یا text-moderation-stable
];
$response = OpenAI::moderations()->create($input, $options);
// $response["results"][0]["flagged"]
// $response["results"][0]["categories"] (آرایهای از دستهبندیهای نقض شده)
// $response["results"][0]["category_scores"] (امتیازات برای هر دستهبندی)
use Sanjarani\OpenAI\Support\Tool;
$codeInterpreterTool = Tool::codeInterpreter();
$fileSearchTool = Tool::fileSearch();
$functionTool = Tool::function(
"getCurrentWeather",
"Get the current weather in a given location",
[
"type" => "object",
"properties" => [
"location" => ["type" => "string", "description" => "The city and state, e.g. San Francisco, CA"],
"unit" => ["type" => "string", "enum" => ["celsius", "fahrenheit"]]
],
"
$assistant = OpenAI::assistants()->create(
"gpt-4o",
[
"name" => "Personal Math Tutor",
"instructions" => "You are a personal math tutor. Write and run code to answer math questions.",
"tools" => [$codeInterpreterTool, $fileSearchTool] // یا آرایهای از تعریف ابزارها
// "tool_resources" => [ "file_search" => [ "vector_store_ids" => ["vs_xxxx"] ] ] // در صورت نیاز
]
);
$assistantId = $assistant["id"];
// آپلود یک فایل برای استفاده با Assistant (ابتدا از Files API استفاده کنید)
$fileUploadResponse = OpenAI::files()->upload("/path/to/document.pdf", "assistants");
$fileIdForAssistant = $fileUploadResponse["id"];
// پیوست کردن فایل به Assistant (v1 روش قدیمیتر، v2 از tool_resources استفاده میکند)
// برای v2، فایلها معمولاً به Vector Stores اضافه میشوند و سپس Vector Store به Assistant متصل میشود.
// یا فایلها هنگام ایجاد Message یا Run به Thread اضافه میشوند.
// مثال برای v1 (اگر API هنوز پشتیبانی کند):
// $assistantFile = OpenAI::assistants()->createFile($assistantId, $fileIdForAssistant);
// $retrievedAssistantFile = OpenAI::assistants()->retrieveFile($assistantId, $fileIdForAssistant);
// $assistantFilesList = OpenAI::assistants()->listFiles($assistantId);
// $deletedAssistantFile = OpenAI::assistants()->deleteFile($assistantId, $fileIdForAssistant);
// // ایجاد یک Thread (مثال مفهومی، نیاز به پیادهسازی دارد)
// $thread = OpenAI::threads()->create();
// $threadId = $thread["id"];
// // افزودن پیام به Thread (مثال مفهومی)
// $message = OpenAI::threads()->messages($threadId)->create([
// "role" => "user",
// "content" => "I need to solve the equation 3x + 11 = 14. Can you help me?"
// ]);
// // اجرای Assistant روی Thread (مثال مفهومی)
// $run = OpenAI::threads()->runs($threadId)->create([
// "assistant_id" => $assistantId,
// "instructions" => "Please address the user as Jane Doe. The user has a premium account."
// ]);
// $runId = $run["id"];
// // بررسی وضعیت Run و دریافت پاسخها (مثال مفهومی، نیاز به polling و مدیریت status دارد)
// do {
// sleep(1);
// $runStatus = OpenAI::threads()->runs($threadId)->retrieve($runId);
// } while (in_array($runStatus["status"], ["queued", "in_progress", "