ChatGPT API Entegrasyonu: Laravel ve Node.js Örnekleri

z

zafer ak

Yazar

30 October 2025 13 dakika okuma 706 görüntülenme
ChatGPT API Entegrasyonu: Laravel ve Node.js Örnekleri
OpenAI API ile akıllı uygulamalar geliştirin. Chat completions, embeddings ve function calling.

OpenAI API'ye Giriş

ChatGPT API, uygulamalarınıza yapay zeka yetenekleri eklemenizi sağlar. GPT-4 Turbo ve GPT-4o modelleri ile text generation, chat ve function calling yapabilirsiniz.

API Anahtarı Alma

  1. platform.openai.com adresine gidin
  2. API Keys bölümünden yeni key oluşturun
  3. Key'i güvenli şekilde saklayın

Laravel Entegrasyonu

// composer require openai-php/laravel

// config/openai.php
return [
    "api_key" => env("OPENAI_API_KEY"),
    "organization" => env("OPENAI_ORGANIZATION"),
];

// app/Services/AIService.php
namespace App\Services;

use OpenAI\Laravel\Facades\OpenAI;

class AIService
{
    public function chat(string $message, array $context = []): string
    {
        $messages = [
            ["role" => "system", "content" => "Sen yardımcı bir asistansın."],
            ...$context,
            ["role" => "user", "content" => $message],
        ];

        $response = OpenAI::chat()->create([
            "model" => "gpt-4o",
            "messages" => $messages,
            "max_tokens" => 1000,
            "temperature" => 0.7,
        ]);

        return $response->choices[0]->message->content;
    }

    public function streamChat(string $message): \Generator
    {
        $stream = OpenAI::chat()->createStreamed([
            "model" => "gpt-4o",
            "messages" => [
                ["role" => "user", "content" => $message],
            ],
        ]);

        foreach ($stream as $response) {
            yield $response->choices[0]->delta->content ?? "";
        }
    }
}

Function Calling

$response = OpenAI::chat()->create([
    "model" => "gpt-4o",
    "messages" => [
        ["role" => "user", "content" => "İstanbul hava durumu nasıl?"],
    ],
    "tools" => [
        [
            "type" => "function",
            "function" => [
                "name" => "get_weather",
                "description" => "Belirtilen şehrin hava durumunu getirir",
                "parameters" => [
                    "type" => "object",
                    "properties" => [
                        "city" => [
                            "type" => "string",
                            "description" => "Şehir adı",
                        ],
                    ],
                    "required" => ["city"],
                ],
            ],
        ],
    ],
    "tool_choice" => "auto",
]);

// Tool call'u işle
if ($response->choices[0]->message->toolCalls) {
    $toolCall = $response->choices[0]->message->toolCalls[0];
    $args = json_decode($toolCall->function->arguments, true);

    $weatherData = $this->getWeather($args["city"]);
    // Sonucu AI'a geri gönder
}

Node.js Örneği

import OpenAI from "openai";

const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
});

async function chat(message) {
  const completion = await openai.chat.completions.create({
    model: "gpt-4o",
    messages: [
      { role: "system", content: "Sen yardımcı bir asistansın." },
      { role: "user", content: message },
    ],
  });

  return completion.choices[0].message.content;
}

// Streaming
async function* streamChat(message) {
  const stream = await openai.chat.completions.create({
    model: "gpt-4o",
    messages: [{ role: "user", content: message }],
    stream: true,
  });

  for await (const chunk of stream) {
    yield chunk.choices[0]?.delta?.content || "";
  }
}

Embeddings

$response = OpenAI::embeddings()->create([
    "model" => "text-embedding-3-small",
    "input" => "Laravel ile web geliştirme",
]);

$embedding = $response->embeddings[0]->embedding;
// Vector database'e kaydet (Pinecone, Weaviate, etc.)

Maliyet Optimizasyonu

  • GPT-4o-mini kullanın (ucuz ama yetenekli)
  • max_tokens sınırı koyun
  • Caching uygulayın
  • Batch API kullanın

Sonuç

ChatGPT API, uygulamalarınıza AI süper güçleri ekler. Doğru prompt engineering ile harika sonuçlar alabilirsiniz.

İlgili Yazılar