→ חזרה לעמוד הקודם
// סיכום וחומר לימוד

דוגמת קוד עבור יצירת קונטרולר לצ'אט עם סגנון שיחה

פרויקט הנדסת תוכנהיצירת צ'אט עם סגנון שיחה

להדרכה ליצירת צ׳אט עם סגנון שיחה

קוד הקונטרולר

using System.Text.Json;
using Microsoft.AspNetCore.Mvc;
using System.Net.Http;
using System.Net.Http.Json;
using System.Text.Json.Nodes;

namespace שםהפרויקט.Controllers
{
    [ApiController]
    [Route("api/chat")]
    public class ChatController : ControllerBase
    {
        private const string ApiKey = "YOUR_GEMINI_API_KEY";
        private const string ApiUrl =
            "https://generativelanguage.googleapis.com/v1beta/models/"
            + "gemini-3.5-flash-lite:generateContent";
        private static readonly HttpClient Client = new HttpClient();

        public record ChatRequest(string Message);

        [HttpPost]
        public async Task<IActionResult> Send(ChatRequest input)
        {
            if (string.IsNullOrWhiteSpace(input.Message))
                return BadRequest(new { error = "יש להזין הודעה." });

            var body = new
            {
                system_instruction = new
                {
                    parts = new[] { new { text = "Reply in Hebrew, as if to a 5-year-old child." } }
                },
                contents = new[]
                {
                    new { role = "user", parts = new[] { new { text = input.Message } } }
                }
            };

            using var request = new HttpRequestMessage(HttpMethod.Post, ApiUrl);
            request.Headers.Add("x-goog-api-key", ApiKey);
            request.Content = JsonContent.Create(body);

            try
            {
                using var response = await Client.SendAsync(request);
                string responseText = await response.Content.ReadAsStringAsync();

                if (!response.IsSuccessStatusCode)
                    return StatusCode(502, new { geminiStatus = (int)response.StatusCode, details = responseText });

                var json = JsonNode.Parse(responseText);
                var parts = json?["candidates"]?[0]?["content"]?["parts"]?.AsArray();

                var reply = parts?
                    .FirstOrDefault(p => p?["thought"]?.GetValue<bool>() != true)?["text"]?
                    .GetValue<string>();

                if (string.IsNullOrWhiteSpace(reply))
                    return StatusCode(502, new { error = "לא התקבלה תשובה טקסטואלית." });

                return Ok(new { reply });
            }
            catch (HttpRequestException ex)
            {
                return StatusCode(502, new { error = "התקשורת עם השרת נכשלה.", details = ex.Message });
            }
        }
    }
}
הורדת הקובץ המקוריPDF · דוגמת קוד עבור יצירת קונטרולר לצ'אט עם סגנון שיחה