Today
-
Yesterday
-
Total
-

ABOUT ME

-

방문자

  • [C#] Ollama를 이용한 로컬 LLM 연동, API 호출
    카테고리 없음 2026. 11. 9. 23:13

    [C#] Ollama를 이용한 로컬 LLM 연동, API 호출

    Ollama로 로컬에 구동 중인 LLM 모델을 C#(.NET) 환경에서 HttpClient를 통해 호출하는 방법입니다.

    절차

    1. Ollama 설치 및 모델 실행
    2. 요청/응답 모델(Class) 정의
    3. API 호출 코드 작성
    4. (선택) 스트리밍 출력 처리

     

    1. Ollama 설치 및 모델 실행
    터미널(CMD)에서 사용할 모델을 다운로드 및 실행합니다.

    ollama run llama3

    기본적으로 http://localhost:11434 포트로 API 서버가 활성화됩니다.
    (백그라운드 실행 확인: ollama list)

     

    2. 요청 및 응답 데이터 모델 정의
    Ollama /api/generate 규격에 맞는 데이터 클래스를 생성합니다.

    public class OllamaRequest
    {
        public string model { get; set; }
        public string prompt { get; set; }
        public bool stream { get; set; } = false;
    }
    
    public class OllamaResponse
    {
        public string model { get; set; }
        public string response { get; set; }
        public bool done { get; set; }
    }

     

    3. API 호출 코드 작성
    외부 라이브러리 없이 .NET 기본 HttpClient와 System.Text.Json을 사용합니다.

    using System;
    using System.Net.Http;
    using System.Text;
    using System.Text.Json;
    using System.Threading.Tasks;
    
    class Program
    {
        private static readonly HttpClient client = new HttpClient();
    
        static async Task Main(string[] args)
        {
            string apiUrl = "http://localhost:11434/api/generate";
    
            var requestData = new OllamaRequest
            {
                model = "llama3",
                prompt = "C#의 장점 3가지를 요약해줘.",
                stream = false
            };
    
            string json = JsonSerializer.Serialize(requestData);
            var content = new StringContent(json, Encoding.UTF8, "application/json");
    
            try
            {
                HttpResponseMessage response = await client.PostAsync(apiUrl, content);
                response.EnsureSuccessStatusCode();
    
                string responseBody = await response.Content.ReadAsStringAsync();
                var result = JsonSerializer.Deserialize<OllamaResponse>(responseBody);
    
                Console.WriteLine("=== 응답 결과 ===");
                Console.WriteLine(result.response);
            }
            catch (HttpRequestException ex)
            {
                Console.WriteLine($"호출 실패: {ex.Message}");
            }
        }
    }

    3-1. 호출 실패(Connection refused / 10061) 에러 발생 시
    Ollama 백그라운드 서비스가 꺼져 있는 경우 발생합니다.
    작업 관리자에서 Ollama 프로세스를 확인하거나, 터미널에서 ollama serve를 실행하여 서비스 데몬을 구동합니다.

     

    4. 실시간 한 글자씩 스트리밍(Streaming) 출력
    응답 대기 시간 없이 실시간 토큰 출력이 필요한 경우 stream: true로 설정하고 라인 단위로 수신합니다.

    var requestData = new OllamaRequest { model = "llama3", prompt = "테스트", stream = true };
    var response = await client.PostAsync(apiUrl, new StringContent(JsonSerializer.Serialize(requestData), Encoding.UTF8, "application/json"));
    
    using var stream = await response.Content.ReadAsStreamAsync();
    using var reader = new System.IO.StreamReader(stream);
    
    while (!reader.EndOfStream)
    {
        var line = await reader.ReadLineAsync();
        if (!string.IsNullOrWhiteSpace(line))
        {
            var chunk = JsonSerializer.Deserialize<OllamaResponse>(line);
            Console.Write(chunk.response);
        }
    }
Posted by virtualgiraffe.