├── .gitignore
├── config.json
├── Audio
├── Nova.mp3
└── Onyx.mp3
├── Images
└── OlurumTurkiyem.png
├── Configurations
└── ConfigReader.cs
├── MyOpenAIProject.csproj
├── README.md
├── MyOpenAIProject.sln
├── Program.cs
└── Examples
├── 10
└── O3MathSolver.cs
├── 09
└── GPT4VisionExample.cs
├── 01
└── SimpleChatExample.cs
├── 07
└── AudioExample.cs
├── 02
└── StreamingChatExample.cs
├── 06
└── ImageGenerateExample.cs
├── 04
└── StructuredOutputs.cs
├── 08
└── RAGExample.cs
├── 05
└── EmbeddingsExample.cs
└── 03
└── ToolsAndFunctionsExample.cs
/.gitignore:
--------------------------------------------------------------------------------
1 | # .NET
2 | bin/
3 | obj/
4 | .vs/
5 |
--------------------------------------------------------------------------------
/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "OpenAI": {
3 | "ApiKey": "your_openai_key"
4 | }
5 | }
6 |
--------------------------------------------------------------------------------
/Audio/Nova.mp3:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/KardelRuveyda/openai-dotnet-exercises/HEAD/Audio/Nova.mp3
--------------------------------------------------------------------------------
/Audio/Onyx.mp3:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/KardelRuveyda/openai-dotnet-exercises/HEAD/Audio/Onyx.mp3
--------------------------------------------------------------------------------
/Images/OlurumTurkiyem.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/KardelRuveyda/openai-dotnet-exercises/HEAD/Images/OlurumTurkiyem.png
--------------------------------------------------------------------------------
/Configurations/ConfigReader.cs:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/KardelRuveyda/openai-dotnet-exercises/HEAD/Configurations/ConfigReader.cs
--------------------------------------------------------------------------------
/MyOpenAIProject.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Exe
5 | net9.0
6 | enable
7 | enable
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # OPEN AI DOTNET EXERCISES
2 |
3 | Bu proje, OpenAI API'sini kullanarak yapay zeka özelliklerini uygulamalarınıza entegre etmek için bir örnek .NET konsol uygulamasını içerir.
4 |
5 | ## Dosya Yapısı
6 |
7 | - **Audio:** Bu klasör, metin okuma (text-to-speech) ile üretilen ses dosyalarını içerir.
8 | - **Configurations:** Bu klasör, OpenAI API konfigürasyon dosyalarını içerir.
9 | - **Examples:** Bu klasör, OpenAI ile ilgili çalışmalarınızın örneklerini içerir.
10 | - **Images:** Bu klasör, DALL-E ile üretilen fotoğrafları içerir.
11 |
12 |
13 |
14 | ## Makale
15 |
16 | Konu hakkında daha fazla bilgi edinmek ve detaylı bir inceleme okumak için aşağıdaki makaleyi ziyaret edebilirsiniz:
17 |
18 | https://medium.com/@ruveydakardelcetin/openai-net-api-kullanımı-yapay-zeka-gücünü-net-projelerinize-taşıyın-32b9f973d97f
19 |
20 | 
21 |
22 |
23 |
--------------------------------------------------------------------------------
/MyOpenAIProject.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 17
4 | VisualStudioVersion = 17.11.35312.102
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MyOpenAIProject", "MyOpenAIProject.csproj", "{92526B05-E040-473B-A66F-ABB6C756EA89}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|Any CPU = Debug|Any CPU
11 | Release|Any CPU = Release|Any CPU
12 | EndGlobalSection
13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 | {92526B05-E040-473B-A66F-ABB6C756EA89}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15 | {92526B05-E040-473B-A66F-ABB6C756EA89}.Debug|Any CPU.Build.0 = Debug|Any CPU
16 | {92526B05-E040-473B-A66F-ABB6C756EA89}.Release|Any CPU.ActiveCfg = Release|Any CPU
17 | {92526B05-E040-473B-A66F-ABB6C756EA89}.Release|Any CPU.Build.0 = Release|Any CPU
18 | EndGlobalSection
19 | GlobalSection(SolutionProperties) = preSolution
20 | HideSolutionNode = FALSE
21 | EndGlobalSection
22 | GlobalSection(ExtensibilityGlobals) = postSolution
23 | SolutionGuid = {60CB543B-6C05-4137-B140-43D2381C48D3}
24 | EndGlobalSection
25 | EndGlobal
26 |
--------------------------------------------------------------------------------
/Program.cs:
--------------------------------------------------------------------------------
1 | #region SimpleChatExample
2 | //SimpleChatExample.Run();
3 | //await SimpleChatExample.RunAsync();
4 | #endregion
5 |
6 | #region StreamingChatExample
7 |
8 | //StreamingChatExample.Run();
9 | //await StreamingChatExample.RunAsync();
10 | #endregion
11 |
12 |
13 | #region ToolsAndFunctionsExample
14 | //ToolsAndFunctionsExample.Run();
15 | #endregion
16 |
17 | #region StructuredOutputs
18 | //await StructuredOutputs.RunAsync();
19 | #endregion
20 |
21 | #region EmbeddingsExample
22 | //EmbeddingsExample.SimpleEmbedding();
23 | //await EmbeddingsExample.SimpleEmbeddingAsync();
24 | //EmbeddingsExample.MultipleEmbeddings();
25 | //await EmbeddingsExample.MultipleEmbeddingsAsync();
26 | //await EmbeddingsExample.MultipleEmbeddingsAsync();
27 | #endregion
28 |
29 | #region ImageGenerateExample
30 | //ImageGenerateExample.Run();
31 | #endregion
32 |
33 | #region AudioExample
34 | //AudioExample.SimpleTextToSpeech();
35 | //AudioExample.SimpleSpeechToText();
36 | //AudioExample.Example02_SimpleTextToSpeech();
37 | #endregion
38 |
39 |
40 | #region RAGExample
41 | //RAGExample.CreateAndRunGenerativeAIAssistant();
42 | #endregion
43 |
44 |
45 | #region GPT4VisionExample
46 | //GPT4VisionExample.RunAssistantWithVision();
47 | #endregion
48 |
49 |
50 | #region
51 | using OpenAI.Examples;
52 |
53 | O3MathSolver.Example_O1_MathProblemSolver();
54 | #endregion
55 |
--------------------------------------------------------------------------------
/Examples/09/GPT4VisionExample.cs:
--------------------------------------------------------------------------------
1 | using OpenAI.Chat;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.IO;
5 |
6 |
7 | public class GPT4VisionExample
8 | {
9 | public static void RunAssistantWithVision()
10 | {
11 | // 1. API anahtarını config.json dosyasından oku
12 | string apiKey = ConfigReader.ReadApiKeyFromConfig();
13 |
14 | // 2. API anahtarı alınamazsa işlemi sonlandır
15 | if (string.IsNullOrEmpty(apiKey))
16 | {
17 | Console.WriteLine("config.json dosyasında API anahtarı bulunamadı.");
18 | return;
19 | }
20 |
21 | // 3. GPT-4o modelini kullanacak bir ChatClient nesnesi oluştur
22 | ChatClient client = new("gpt-4o", apiKey);
23 |
24 | // 4. Görüntü dosyasının yolunu belirt
25 | string imageFilePath = Path.Combine("Assets", "images_dog_and_cat.png");
26 |
27 | // 5. Görüntü dosyasını okuyarak bir stream aç ve byte verisi olarak al
28 | using Stream imageStream = File.OpenRead(imageFilePath);
29 | BinaryData imageBytes = BinaryData.FromStream(imageStream);
30 |
31 | // 6. Kullanıcıdan gelen bir mesaj listesi oluştur ve resim verisini ekle
32 | List messages = new List
33 | {
34 | new UserChatMessage(
35 | ChatMessageContentPart.CreateTextPart("Lütfen aşağıdaki görüntüyü tanımlar mısın?"),
36 | ChatMessageContentPart.CreateImagePart(imageBytes, "image/png")
37 | ),
38 | };
39 |
40 | // 7. OpenAI'ye görüntü ve mesajı gönderip tamamlanmış bir yanıt al
41 | ChatCompletion completion = client.CompleteChat(messages);
42 |
43 | // 8. Asistanın yanıtını ekrana yazdır
44 | Console.WriteLine($"[ASİSTAN]: {completion.Content[0].Text}");
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/Examples/01/SimpleChatExample.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Threading.Tasks;
3 | using OpenAI.Chat;
4 |
5 | namespace MyOpenAIProject.Examples
6 | {
7 | public class SimpleChatExample
8 | {
9 | public static void Run()
10 | {
11 | // API anahtarını ConfigReader sınıfından alma işlemi
12 | string apiKey = ConfigReader.ReadApiKeyFromConfig();
13 |
14 | Console.WriteLine("-----API KEY OKUNDU-----");
15 | // API anahtarı alınamazsa işlemi sonlandır
16 | if (string.IsNullOrEmpty(apiKey))
17 | {
18 | Console.WriteLine("API key not found in config.json");
19 | return;
20 | }
21 |
22 | // OpenAI ChatClient oluşturun
23 | ChatClient client = new(model: "gpt-4o", apiKey);
24 |
25 | // Sohbet tamamlama işlemini gerçekleştirin
26 | ChatCompletion completion = client.CompleteChat("“Bu bir test” deyin.'");
27 |
28 | // Sonucu ekrana yazdırın
29 | Console.WriteLine($"[ASSISTANT]: {completion.Content[0].Text}");
30 | Console.ReadLine();
31 | }
32 |
33 | public static async Task RunAsync()
34 | {
35 | // API anahtarını ConfigReader sınıfından alma işlemi
36 | string apiKey = ConfigReader.ReadApiKeyFromConfig();
37 |
38 | Console.WriteLine("-----API KEY OKUNDU-----");
39 |
40 | // API anahtarı alınamazsa işlemi sonlandır
41 | if (string.IsNullOrEmpty(apiKey))
42 | {
43 | Console.WriteLine("API key not found in config.json");
44 | return;
45 | }
46 |
47 | ChatClient client = new(model: "gpt-4o", apiKey);
48 |
49 | ChatCompletion completion = await client.CompleteChatAsync("“Bu bir test” deyin.'");
50 |
51 | Console.WriteLine($"[ASSISTANT]: {completion.Content[0].Text}");
52 | }
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/Examples/07/AudioExample.cs:
--------------------------------------------------------------------------------
1 | using OpenAI.Audio;
2 | namespace OpenAI.Examples
3 | {
4 | public class AudioExample
5 | {
6 | public static void SimpleSpeechToText()
7 | {
8 | string apiKey = ConfigReader.ReadApiKeyFromConfig();
9 |
10 | AudioClient client = new(model: "whisper-1", apiKey);
11 |
12 | string audioFilePath = Path.Combine("Audio", "Nova.mp3");
13 |
14 | AudioTranscriptionOptions options = new()
15 | {
16 | ResponseFormat = AudioTranscriptionFormat.Verbose,
17 | };
18 |
19 | AudioTranscription transcription = client.TranscribeAudio(audioFilePath, options);
20 |
21 | Console.WriteLine("Transcription:");
22 | Console.WriteLine($"{transcription.Text}");
23 |
24 | Console.WriteLine();
25 | Console.WriteLine($"Words:");
26 | foreach (TranscribedWord word in transcription.Words)
27 | {
28 | Console.WriteLine($" {word.Word,15} : {word.StartTime.TotalMilliseconds,5:0} - {word.EndTime.TotalMilliseconds,5:0}");
29 | }
30 |
31 | Console.WriteLine();
32 | Console.WriteLine($"Segments:");
33 | foreach (TranscribedSegment segment in transcription.Segments)
34 | {
35 | Console.WriteLine($" {segment.Text,90} : {segment.StartTime.TotalMilliseconds,5:0} - {segment.EndTime.TotalMilliseconds,5:0}");
36 | }
37 | }
38 |
39 |
40 |
41 | public static void SimpleTextToSpeech()
42 | {
43 | string apiKey = ConfigReader.ReadApiKeyFromConfig();
44 |
45 | AudioClient client = new("tts-1", apiKey);
46 |
47 | string input = "Bu örnekleri nereden bulacağız diye düşünmeyin hepsi kitapta var biraz sonra paylaşacağım.";
48 |
49 | BinaryData speech = client.GenerateSpeech(input, GeneratedSpeechVoice.Onyx);
50 |
51 | using FileStream stream = File.OpenWrite($"{Guid.NewGuid()}.mp3");
52 | speech.ToStream().CopyTo(stream);
53 | }
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/Examples/02/StreamingChatExample.cs:
--------------------------------------------------------------------------------
1 | using OpenAI.Chat;
2 | using System.ClientModel;
3 |
4 | namespace MyOpenAIProject.Examples
5 | {
6 | public class StreamingChatExample
7 | {
8 | public static void Run()
9 | {
10 | // API anahtarını ConfigReader sınıfından alma işlemi
11 | string apiKey = ConfigReader.ReadApiKeyFromConfig();
12 |
13 | // API anahtarı alınamazsa işlemi sonlandır
14 | if (string.IsNullOrEmpty(apiKey))
15 | {
16 | Console.WriteLine("API key not found in config.json");
17 | return;
18 | }
19 |
20 | ChatClient client = new(model: "gpt-4o", apiKey);
21 |
22 | CollectionResult completionUpdates =
23 | client.CompleteChatStreaming("'Bu bir testtir.' demeni istiyorum.");
24 |
25 | Console.Write($"[ASSISTANT]: ");
26 | foreach (StreamingChatCompletionUpdate completionUpdate in completionUpdates)
27 | {
28 | if (completionUpdate.ContentUpdate.Count > 0)
29 | {
30 | Console.Write(completionUpdate.ContentUpdate[0].Text);
31 | }
32 | }
33 | Console.ReadLine();
34 | }
35 |
36 | public static async Task RunAsync()
37 | {
38 | // API anahtarını ConfigReader sınıfından alma işlemi
39 | string apiKey = ConfigReader.ReadApiKeyFromConfig();
40 |
41 | // API anahtarı alınamazsa işlemi sonlandır
42 | if (string.IsNullOrEmpty(apiKey))
43 | {
44 | Console.WriteLine("API key not found in config.json");
45 | return;
46 | }
47 |
48 | // OpenAI ChatClient oluşturun
49 | ChatClient client = new(model: "gpt-4o", apiKey);
50 |
51 | AsyncCollectionResult completionUpdates =
52 | client.CompleteChatStreamingAsync("'Bu bir testtir.' demeni istiyorum.");
53 |
54 | Console.Write($"[ASSISTANT]: ");
55 |
56 | await foreach (StreamingChatCompletionUpdate completionUpdate in completionUpdates)
57 | {
58 | if (completionUpdate.ContentUpdate.Count > 0)
59 | {
60 | Console.Write(completionUpdate.ContentUpdate[0].Text);
61 | }
62 | }
63 | Console.ReadLine();
64 | }
65 |
66 |
67 | }
68 | }
69 |
--------------------------------------------------------------------------------
/Examples/06/ImageGenerateExample.cs:
--------------------------------------------------------------------------------
1 | using OpenAI.Images;
2 |
3 | public class ImageGenerateExample
4 | {
5 | public static void Run()
6 | {
7 | // API anahtarını ConfigReader sınıfından alma işlemi
8 | string apiKey = ConfigReader.ReadApiKeyFromConfig();
9 |
10 | // API anahtarı alınamazsa işlemi sonlandır
11 | if (string.IsNullOrEmpty(apiKey))
12 | {
13 | Console.WriteLine("API key not found in config.json");
14 | return;
15 | }
16 |
17 | ImageClient client = new(model: "dall-e-3", apiKey);
18 |
19 | string prompt = @"
20 | Rozet Tasarımı
21 |
22 | Kurallar:
23 | 🔹 Boyut: 512x512
24 | 🔹 Stil: Realistik — bu stilin tüm karakteristik özellikleri (renk geçişleri, ışık-gölge oyunları, detay seviyesi) korunmalıdır.
25 | 🔹 Tema: Oyunlaştırılmış — ikonun ifadesine, duygusuna ve sembollerine doğrudan yansıtılmalıdır.
26 | 🔹 Arka Plan: Saydam. Arka plan saydam olmalıdır ve tasarımı destekleyecek herhangi bir doku içermemelidir.
27 | 🔹 Genel Renk Paleti:
28 | - Birincil: #0062FF
29 | - İkincil: #CDE9FF
30 | - Üçüncül: #FFA933
31 | 🔹 Çerçeve: Arma / Kalkan. Tasarım sabit bir arma / kalkan içerisinde konumlandırılmalı ve bunun dışına taşmamalıdır.
32 |
33 | 🎯 Önemli Kurallar:
34 | - Rozet adı, görsel tasarımda açıkça görünmelidir: Technical PO.
35 | - Ad okunabilir, net ve dengeli bir biçimde tasarımın içinde yer almalıdır.
36 | - Rozet ikonları aynı görsel çizgide ve bütünlükte olmalıdır.
37 | - Tasarımlar sade, modern ve görsel olarak dengeli olmalıdır.
38 | - Yüksek çözünürlükte ve hızlı üretime uygun yapıda olmalıdır.
39 | - Gölgelendirme, yumuşak kenarlar ve minimal detaylar kullanılabilir ancak sadelik korunmalıdır.
40 | - Renk dışına çıkılmamalı, görsel karmaşadan kaçınılmalıdır.
41 | - İkon, kendi başına da bir mesaj iletebilmeli ve anlamlı bir bütünlük taşımalıdır.
42 |
43 | Rozet Adı: Technical PO
44 | Gereksinimler: Minimum 2 yıl boyunca en az bir uygulama veya modülde PO olarak görev almış / alıyor olmak.
45 | ";
46 |
47 |
48 | ImageGenerationOptions options = new()
49 | {
50 | Quality = GeneratedImageQuality.High,
51 | Size = GeneratedImageSize.W1024xH1024, // Dall-E için geçerli boyutlardan biri
52 | Style = GeneratedImageStyle.Vivid,
53 | ResponseFormat = GeneratedImageFormat.Bytes
54 | };
55 |
56 | Console.WriteLine("Rozet oluşturuluyor...");
57 | GeneratedImage image = client.GenerateImage(prompt, options);
58 | BinaryData bytes = image.ImageBytes;
59 |
60 | string fileName = $"badge_{Guid.NewGuid()}.png";
61 | using FileStream stream = File.OpenWrite(fileName);
62 | bytes.ToStream().CopyTo(stream);
63 |
64 | Console.WriteLine($"Rozet oluşturuldu: {fileName}");
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/Examples/10/O3MathSolver.cs:
--------------------------------------------------------------------------------
1 | using OpenAI.Chat;
2 |
3 | namespace OpenAI.Examples
4 | {
5 | public class O3MathSolver
6 | {
7 | public static void Example_O1_MathProblemSolver()
8 | {
9 | // API anahtarını config'den oku
10 | string apiKey = ConfigReader.ReadApiKeyFromConfig();
11 |
12 | if (string.IsNullOrEmpty(apiKey))
13 | {
14 | Console.WriteLine("API anahtarı bulunamadı.");
15 | return;
16 | }
17 |
18 | // O1-preview modeli ile ChatClient oluştur
19 | ChatClient client = new("o3-mini", apiKey);
20 |
21 | // Sistem talimatları için SystemChatMessage kullan
22 | List messages = new()
23 | {
24 | ChatMessage.CreateSystemMessage(@"
25 | Sen bir matematik uzmanısın. Problemleri şu şekilde çöz:
26 | 1. Problemi analiz et
27 | 2. Hangi yöntemi kullanacağını belirle
28 | 3. Adım adım çözüm yap
29 | 4. Sonucu doğrula
30 | 5. Alternatif çözüm yolları varsa belirt
31 | "),
32 | ChatMessage.CreateUserMessage(@"
33 | Aşağıdaki matematik problemini çöz:
34 |
35 | Bir şirket, aylık satışlarının %15'ini reklam harcamalarına ayırıyor.
36 | Bu ay toplam 120.000 TL satış yaptılar ve reklam harcamaları
37 | geçen aya göre %20 arttı. Geçen ay reklam harcamaları
38 | ne kadardı?
39 | ")
40 | };
41 |
42 | // O1 modeli için özel seçenekler
43 | ChatCompletionOptions options = new()
44 | {
45 | MaxOutputTokenCount = 2000
46 | };
47 |
48 | try
49 | {
50 | Console.WriteLine("Problem çözülüyor... (O1 modeli düşünüyor)");
51 |
52 | ChatCompletion completion = client.CompleteChat(messages, options);
53 |
54 | // Reasoning token kullanımını göster
55 | if (completion.Usage?.OutputTokenDetails != null)
56 | {
57 | Console.WriteLine("\n=== TOKEN KULLANIMI ===");
58 | Console.WriteLine($"🧠 Reasoning Tokens: {completion.Usage.OutputTokenDetails.ReasoningTokenCount}");
59 | Console.WriteLine($"💬 Display Tokens: {completion.Usage.OutputTokenCount - completion.Usage.OutputTokenDetails.ReasoningTokenCount}");
60 | Console.WriteLine($"📊 Total Output Tokens: {completion.Usage.OutputTokenCount}");
61 | Console.WriteLine($"📥 Input Tokens: {completion.Usage.InputTokenCount}");
62 | }
63 |
64 | Console.WriteLine("\n=== ÇÖZÜM ===");
65 | Console.WriteLine(completion.Content[0].Text);
66 |
67 | }
68 | catch (Exception ex)
69 | {
70 | Console.WriteLine($"Hata oluştu: {ex.Message}");
71 | }
72 | }
73 | }
74 | }
--------------------------------------------------------------------------------
/Examples/04/StructuredOutputs.cs:
--------------------------------------------------------------------------------
1 |
2 | using OpenAI.Chat;
3 | using System.Text.Json;
4 |
5 | public class StructuredOutputs
6 | {
7 | // Run metodu, OpenAI API'sini kullanarak yapılandırılmış bir çıktı elde eder ve sonuçları ekrana yazar
8 | public static async Task RunAsync()
9 | {
10 | // API anahtarını config dosyasından okuma işlemi
11 | Console.WriteLine("API anahtarı okunuyor...");
12 | string apiKey = ConfigReader.ReadApiKeyFromConfig();
13 |
14 | if (string.IsNullOrEmpty(apiKey))
15 | {
16 | Console.WriteLine("Hata: API anahtarı bulunamadı.");
17 | return;
18 | }
19 |
20 | // OpenAI ChatClient oluşturuluyor
21 | Console.WriteLine("ChatClient oluşturuluyor...");
22 |
23 | ChatClient client = new(model: "gpt-4o-mini", apiKey);
24 |
25 | // Kullanıcı mesajını oluşturuyoruz
26 | List messages = new()
27 | {
28 | new UserChatMessage("How can I solve 8x - 7 = 17?")
29 | };
30 |
31 | // Yapılandırılmış yanıt formatı oluşturuyoruz (JSON şeması)
32 | ChatCompletionOptions options = new()
33 | {
34 | ResponseFormat = ChatResponseFormat.CreateJsonSchemaFormat(
35 | jsonSchemaFormatName: "math_reasoning",
36 | jsonSchema: BinaryData.FromBytes("""
37 | {
38 | "type": "object",
39 | "properties": {
40 | "steps": {
41 | "type": "array",
42 | "items": {
43 | "type": "object",
44 | "properties": {
45 | "explanation": { "type": "string" },
46 | "output": { "type": "string" }
47 | },
48 | "required": ["explanation", "output"],
49 | "additionalProperties": false
50 | }
51 | },
52 | "final_answer": { "type": "string" }
53 | },
54 | "required": ["steps", "final_answer"],
55 | "additionalProperties": false
56 | }
57 | """u8.ToArray()),
58 | jsonSchemaIsStrict: true),
59 |
60 | };
61 |
62 | // OpenAI API'den tamamlama isteğini yapıyoruz
63 | ChatCompletion completion = await client.CompleteChatAsync(messages, options);
64 |
65 | // Yapılandırılmış JSON'u ayrıştırıyoruz
66 | using JsonDocument structuredJson = JsonDocument.Parse(completion.Content[0].Text);
67 |
68 | // Nihai cevabı ve adımları konsola yazdırıyoruz
69 | Console.WriteLine($"Final answer: {structuredJson.RootElement.GetProperty("final_answer").GetString()}");
70 | Console.WriteLine("Reasoning steps:");
71 |
72 | foreach (JsonElement stepElement in structuredJson.RootElement.GetProperty("steps").EnumerateArray())
73 | {
74 | Console.WriteLine($" - Explanation: {stepElement.GetProperty("explanation").GetString()}");
75 | Console.WriteLine($" Output: {stepElement.GetProperty("output").GetString()}");
76 | }
77 | }
78 | }
79 |
--------------------------------------------------------------------------------
/Examples/08/RAGExample.cs:
--------------------------------------------------------------------------------
1 | using OpenAI;
2 | using OpenAI.Assistants;
3 | using OpenAI.Files;
4 | using System.ClientModel;
5 |
6 | #pragma warning disable OPENAI001
7 |
8 | public class RAGExample
9 | {
10 | public static void CreateAndRunGenerativeAIAssistant()
11 | {
12 | // API key oku
13 | string apiKey = ConfigReader.ReadApiKeyFromConfig();
14 |
15 | if (string.IsNullOrEmpty(apiKey))
16 | {
17 | Console.WriteLine("API key not found in config.json");
18 | return;
19 | }
20 |
21 | // OpenAI client'ları başlat
22 | OpenAIClient openAIClient = new(apiKey);
23 | OpenAIFileClient fileClient = openAIClient.GetOpenAIFileClient();
24 | AssistantClient assistantClient = openAIClient.GetAssistantClient();
25 |
26 | // Belgeyi hazırla ve yükle
27 | using Stream document = BinaryData.FromString("""
28 | {
29 | "title": "Generative AI for .NET Developers",
30 | "sections": [
31 | {
32 | "topic": "RAG (Retrieval-Augmented Generation)",
33 | "content": "RAG yaklaşımı, LLM modellerine ek bağlam sağlayarak daha doğru ve güncel yanıtlar üretmesini sağlar. .NET geliştiricileri, belgeleri chunk'lara ayırıp embedding'lerini çıkararak vektör veritabanına yükler. Daha sonra kullanıcı sorgusu embed edilir ve en yakın parçalar modele verilir."
34 | },
35 | {
36 | "topic": "Prompt Engineering",
37 | "content": "İyi bir prompt, sistem mesajı + kullanıcı mesajı + bağlam parçalarını içerir. Net talimatlar ve format beklentileriyle modelden daha kontrollü sonuçlar alınır."
38 | },
39 | {
40 | "topic": "Kod Örneği",
41 | "content": "OpenAI .NET SDK veya HttpClient kullanarak Chat API çağrısı yapılabilir. Örneğin gpt-4o-mini modelinden RAG senaryoları için hızlı ve ekonomik sonuçlar alınabilir."
42 | }
43 | ]
44 | }
45 | """).ToStream();
46 |
47 | OpenAIFile guideFile = fileClient.UploadFile(
48 | document,
49 | "generative_ai_dotnet.json",
50 | FileUploadPurpose.Assistants);
51 |
52 | // Asistan oluşturma seçenekleri
53 | AssistantCreationOptions assistantOptions = new()
54 | {
55 | Name = "Generative AI .NET Eğitim Asistanı",
56 | Instructions = "Sen, 'Generative AI for .NET Developers' eğitim belgesiyle ilgili sorulara cevap veren bir yardımcısın. " +
57 | "Belge dışındaki sorulara cevap verme!",
58 | Tools =
59 | {
60 | new FileSearchToolDefinition(),
61 | },
62 | ToolResources = new()
63 | {
64 | FileSearch = new()
65 | {
66 | NewVectorStores =
67 | {
68 | new VectorStoreCreationHelper([guideFile.Id]),
69 | }
70 | }
71 | },
72 | };
73 |
74 | Assistant assistant = assistantClient.CreateAssistant("gpt-4o-mini", assistantOptions);
75 |
76 | // Kullanıcıdan soru al - cevap döngüsü
77 | while (true)
78 | {
79 | Console.WriteLine("\nSoru girin (çıkış için 'exit'): ");
80 | string userQuestion = Console.ReadLine();
81 |
82 | if (userQuestion?.ToLower() == "exit")
83 | break;
84 |
85 | ThreadCreationOptions threadOptions = new()
86 | {
87 | InitialMessages = { userQuestion }
88 | };
89 |
90 | ThreadRun threadRun = assistantClient.CreateThreadAndRun(assistant.Id, threadOptions);
91 |
92 | // Yanıt tamamlanana kadar bekle
93 | Console.Write("Asistan yanıt üretiyor");
94 | do
95 | {
96 | Console.Write("."); // her saniye bir nokta ekle
97 | Thread.Sleep(TimeSpan.FromSeconds(1));
98 | threadRun = assistantClient.GetRun(threadRun.ThreadId, threadRun.Id);
99 | } while (!threadRun.Status.IsTerminal);
100 | Console.WriteLine();
101 |
102 | // Yanıtı yazdır
103 | CollectionResult messages =
104 | assistantClient.GetMessages(threadRun.ThreadId, new MessageCollectionOptions() { Order = MessageCollectionOrder.Ascending });
105 |
106 | foreach (ThreadMessage message in messages)
107 | {
108 | Console.Write($"[{message.Role.ToString().ToUpper()}]: ");
109 | foreach (MessageContent contentItem in message.Content)
110 | {
111 | if (!string.IsNullOrEmpty(contentItem.Text))
112 | {
113 | Console.WriteLine(contentItem.Text);
114 | }
115 | }
116 | }
117 | }
118 |
119 | // Kaynak temizleme (isteğe bağlı)
120 | //_ = assistantClient.DeleteAssistant(assistant.Id);
121 | //_ = fileClient.DeleteFile(guideFile.Id);
122 | }
123 | }
124 |
125 | #pragma warning restore OPENAI001
126 |
--------------------------------------------------------------------------------
/Examples/05/EmbeddingsExample.cs:
--------------------------------------------------------------------------------
1 | using OpenAI.Embeddings;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Threading.Tasks;
5 |
6 | namespace MyOpenAIProject.Examples._05
7 | {
8 | public class EmbeddingsExample
9 | {
10 | private static readonly string apiKey = ConfigReader.ReadApiKeyFromConfig();
11 |
12 | private static readonly string description = "Bu otobüs firmasıyla yaptığım yolculuk oldukça keyifliydi. Koltuklar rahat ve genişti, ayrıca"
13 | + " personel çok nazikti. İkramlar yeterliydi ve zamanında varış sağlandı. Güvenli bir yolculuk için kesinlikle"
14 | + " tavsiye ederim.";
15 |
16 | private static readonly string category = "Lüks";
17 |
18 | public static void SimpleEmbedding()
19 | {
20 | EmbeddingClient client = new("text-embedding-3-small", apiKey);
21 | OpenAIEmbedding embedding = client.GenerateEmbedding(description);
22 | ReadOnlyMemory vector = embedding.ToFloats();
23 |
24 | Console.WriteLine($"Boyut(Dimension): {vector.Length}");
25 | Console.WriteLine($"Kayan Noktalı Sayılar(Float): ");
26 | for (int i = 0; i < vector.Length; i++)
27 | {
28 | Console.WriteLine($" [{i,4}] = {vector.Span[i]}");
29 | }
30 | }
31 |
32 | public static async Task SimpleEmbeddingAsync()
33 | {
34 | EmbeddingClient client = new("text-embedding-3-small", apiKey);
35 |
36 | OpenAIEmbedding embedding = await client.GenerateEmbeddingAsync(description);
37 | ReadOnlyMemory vector = embedding.ToFloats();
38 |
39 | Console.WriteLine($"Boyut(Dimension): {vector.Length}");
40 | Console.WriteLine($"Kayan Noktalı Sayılar(Float): ");
41 | for (int i = 0; i < vector.Length; i++)
42 | {
43 | Console.WriteLine($" [{i,4}] = {vector.Span[i]}");
44 | }
45 | }
46 |
47 | public static void EmbeddingWithOptions()
48 | {
49 | EmbeddingClient client = new("text-embedding-3-small", apiKey);
50 |
51 | EmbeddingGenerationOptions options = new() { Dimensions = 512 };
52 |
53 | OpenAIEmbedding embedding = client.GenerateEmbedding(description, options);
54 | ReadOnlyMemory vector = embedding.ToFloats();
55 |
56 | Console.WriteLine($"Boyut: {vector.Length}");
57 | Console.WriteLine($"Kayan Noktalı Sayılar: ");
58 | for (int i = 0; i < vector.Length; i++)
59 | {
60 | Console.WriteLine($" [{i,3}] = {vector.Span[i]}");
61 | }
62 | }
63 |
64 | public static async Task EmbeddingWithOptionsAsync()
65 | {
66 | EmbeddingClient client = new("text-embedding-3-small", apiKey);
67 | EmbeddingGenerationOptions options = new() { Dimensions = 512 };
68 |
69 | OpenAIEmbedding embedding = await client.GenerateEmbeddingAsync(description, options);
70 | ReadOnlyMemory vector = embedding.ToFloats();
71 |
72 | Console.WriteLine($"Boyut: {vector.Length}");
73 | Console.WriteLine($"Kayan Noktalı Sayılar: ");
74 | for (int i = 0; i < vector.Length; i++)
75 | {
76 | Console.WriteLine($" [{i,3}] = {vector.Span[i]}");
77 | }
78 | }
79 |
80 | public static void MultipleEmbeddings()
81 | {
82 | EmbeddingClient client = new("text-embedding-3-small", apiKey);
83 |
84 | List girdiler = new() { category, description }; // Birden fazla girdi ile liste oluşturma
85 |
86 | // Her iki metin için embedding oluşturur
87 | OpenAIEmbeddingCollection collection = client.GenerateEmbeddings(girdiler);
88 |
89 | // Her embedding'i ayrı ayrı işler ve sonuçları konsola yazdırır
90 | foreach (OpenAIEmbedding embedding in collection)
91 | {
92 | ReadOnlyMemory vector = embedding.ToFloats();
93 |
94 | Console.WriteLine($"Boyut: {vector.Length}");
95 | Console.WriteLine("Kayan Noktalı Sayılar: ");
96 | for (int i = 0; i < vector.Length; i++)
97 | {
98 | Console.WriteLine($" [{i,4}] = {vector.Span[i]}");
99 | }
100 |
101 | Console.WriteLine(); // Her embedding'in sonucunu ayırmak için boş satır ekleniyor
102 | }
103 | }
104 |
105 | public static async Task MultipleEmbeddingsAsync()
106 | {
107 | EmbeddingClient client = new("text-embedding-3-small", apiKey);
108 |
109 | List inputs = new() { category, description }; // Girdi listesini oluşturuyoruz
110 |
111 | // Asenkron olarak embedding'leri topluca oluşturur
112 | OpenAIEmbeddingCollection collection = await client.GenerateEmbeddingsAsync(inputs);
113 |
114 | // Her embedding'i ayrı ayrı işler ve sonuçları konsola yazdırır
115 | foreach (OpenAIEmbedding embedding in collection)
116 | {
117 | ReadOnlyMemory vector = embedding.ToFloats();
118 |
119 | Console.WriteLine($"Boyut: {vector.Length}");
120 | Console.WriteLine("Kayan Noktalı Sayılar: ");
121 | for (int i = 0; i < vector.Length; i++)
122 | {
123 | Console.WriteLine($" [{i,4}] = {vector.Span[i]}");
124 | }
125 |
126 | Console.WriteLine(); // Her embedding'in sonucunu ayırmak için boş bir satır
127 | }
128 | }
129 | }
130 | }
131 |
--------------------------------------------------------------------------------
/Examples/03/ToolsAndFunctionsExample.cs:
--------------------------------------------------------------------------------
1 | using OpenAI.Chat;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Linq;
5 | using System.Text;
6 | using System.Text.Json;
7 | using System.Threading.Tasks;
8 |
9 | namespace MyOpenAIProject.Examples
10 | {
11 | public class ToolsAndFunctionsExample
12 | {
13 | private static string GetCurrentLocation()
14 | {
15 | Console.WriteLine("---- Anlık lokasyon çağırıldı.----");
16 | // Normalde burada konum API'si çağrılır, biz İstanbul'u sabit olarak döndüreceğiz.
17 | return "İstanbul";
18 | }
19 |
20 | private static string GetCurrentWeather(string location, string unit = "celsius")
21 | {
22 | Console.WriteLine("---- Hava durumu çağırıldı.----");
23 | // Hava durumu API'si çağrısı yapılır. Örneğin, "Bugün İstanbul'da hava 25 derece."
24 | return $"25 {unit} ve İstanbul'da açık bir hava var.";
25 | }
26 |
27 | private static readonly ChatTool getCurrentLocationTool = ChatTool.CreateFunctionTool(
28 | functionName: nameof(GetCurrentLocation),
29 | functionDescription: "Kullanıcının mevcut konumunu alır ve bu örnekte İstanbul olarak sabitler."
30 | );
31 |
32 | private static readonly ChatTool getCurrentWeatherTool = ChatTool.CreateFunctionTool(
33 | functionName: nameof(GetCurrentWeather),
34 | functionDescription: "Belirli bir konum için hava durumu bilgisini alır. İstanbul varsayılan konumdur.",
35 | functionParameters: BinaryData.FromString("""
36 | {
37 | "type": "object",
38 | "properties": {
39 | "location": {
40 | "type": "string",
41 | "description": "Konum bilgisi, örn. İstanbul"
42 | },
43 | "unit": {
44 | "type": "string",
45 | "enum": [ "celsius", "fahrenheit" ],
46 | "description": "Kullanılacak sıcaklık birimi, varsayılan 'celsius'."
47 | }
48 | },
49 | "required": [ "location" ]
50 | }
51 | """)
52 | );
53 |
54 | public static void Run()
55 | {
56 | Console.WriteLine("Sohbet başlatılıyor...");
57 |
58 | // Kullanıcıdan girdi alınması
59 | Console.WriteLine("Kullanıcı: İstanbul'da hava nasıl diye sorabilir.");
60 | string userInput = Console.ReadLine();
61 |
62 | // Kullanıcı mesajını ekliyoruz
63 | List messages = new()
64 | {
65 | new UserChatMessage(userInput) // Kullanıcıdan gelen mesaj
66 | };
67 |
68 | // Hangi araçların kullanılacağını belirleyen seçenekler
69 | ChatCompletionOptions options = new()
70 | {
71 | Tools = { getCurrentLocationTool, getCurrentWeatherTool } // Araçları tanımlıyoruz
72 | };
73 |
74 | // API anahtarını config dosyasından okuma işlemi
75 | Console.WriteLine("API anahtarı okunuyor...");
76 | string apiKey = ConfigReader.ReadApiKeyFromConfig();
77 |
78 | if (string.IsNullOrEmpty(apiKey))
79 | {
80 | Console.WriteLine("Hata: API anahtarı bulunamadı.");
81 | return;
82 | }
83 |
84 | // OpenAI ChatClient oluşturuluyor
85 | Console.WriteLine("ChatClient oluşturuluyor...");
86 | ChatClient client = new(model: "gpt-4o", apiKey);
87 |
88 |
89 | bool requiresAction;
90 |
91 | do
92 | {
93 | requiresAction = false;
94 | ChatCompletion chatCompletion = client.CompleteChat(messages, options);
95 |
96 | switch (chatCompletion.FinishReason)
97 | {
98 | case ChatFinishReason.Stop:
99 | {
100 | // Add the assistant message to the conversation history.
101 | // Asistan cevabını ekle
102 | messages.Add(new AssistantChatMessage(chatCompletion));
103 |
104 | // chatCompletion nesnesini kontrol etme
105 | string jsonResponse = JsonSerializer.Serialize(chatCompletion);
106 | break;
107 | }
108 |
109 | case ChatFinishReason.ToolCalls:
110 | {
111 | messages.Add(new AssistantChatMessage(chatCompletion));
112 |
113 | foreach (ChatToolCall toolCall in chatCompletion.ToolCalls)
114 | {
115 | switch (toolCall.FunctionName)
116 | {
117 | case nameof(GetCurrentLocation):
118 | {
119 | string toolResult = GetCurrentLocation();
120 | messages.Add(new ToolChatMessage(toolCall.Id, toolResult));
121 | break;
122 | }
123 |
124 | case nameof(GetCurrentWeather):
125 | {
126 |
127 | using JsonDocument argumentsJson = JsonDocument.Parse(toolCall.FunctionArguments);
128 | bool hasLocation = argumentsJson.RootElement.TryGetProperty("location", out JsonElement location);
129 | bool hasUnit = argumentsJson.RootElement.TryGetProperty("unit", out JsonElement unit);
130 |
131 | if (!hasLocation)
132 | {
133 | throw new ArgumentNullException(nameof(location), "The location argument is required.");
134 | }
135 |
136 | string toolResult = hasUnit
137 | ? GetCurrentWeather(location.GetString(), unit.GetString())
138 | : GetCurrentWeather(location.GetString());
139 | messages.Add(new ToolChatMessage(toolCall.Id, toolResult));
140 | break;
141 | }
142 |
143 | default:
144 | {
145 | // Handle other unexpected calls.
146 | throw new NotImplementedException();
147 | }
148 | }
149 | }
150 |
151 | requiresAction = true;
152 | break;
153 | }
154 |
155 | case ChatFinishReason.Length:
156 | throw new NotImplementedException("MaxTokens parametresi veya token limitinin aşılması nedeniyle tamamlanmamış model çıktısı.");
157 |
158 | case ChatFinishReason.ContentFilter:
159 | throw new NotImplementedException("İçerik filtresi bayrağı nedeniyle atlanan içerik.");
160 |
161 | case ChatFinishReason.FunctionCall:
162 | throw new NotImplementedException("Araç çağrıları lehine kullanım dışı bırakıld.");
163 |
164 | default:
165 | throw new NotImplementedException(chatCompletion.FinishReason.ToString());
166 | }
167 | } while (requiresAction);
168 |
169 | // Mesajları konsola yazdırıyoruz
170 | Console.WriteLine("Sohbet tamamlandı. Sonuçlar konsola yazdırılıyor...");
171 | foreach (ChatMessage message in messages)
172 | {
173 | if (message is UserChatMessage userMessage)
174 | {
175 | Console.WriteLine($"[KULLANICI]: {userMessage.Content[0].Text}");
176 | }
177 | else if (message is AssistantChatMessage assistantMessage)
178 | {
179 | // Asistan yanıtı Content[0].Text alanında yer alıyor, bu nedenle doğru şekilde yazdırıyoruz
180 | if (assistantMessage.Content != null && assistantMessage.Content.Count > 0)
181 | {
182 | Console.WriteLine($"[ASİSTAN]: {assistantMessage.Content[0].Text}");
183 | }
184 | }
185 | else if (message is ToolChatMessage toolMessage)
186 | {
187 | Console.WriteLine($"[ARAÇ]: {toolMessage.Content[0].Text}");
188 | }
189 | }
190 |
191 | }
192 |
193 | }
194 | }
195 |
--------------------------------------------------------------------------------