# AI SDK CPP: ClickHouse가 공개한, Modern C++로 AI 서비스의 API에 연동하기 위한 SDK

**URL:** <https://discuss.pytorch.kr/t/ai-sdk-cpp-clickhouse-modern-c-ai-api-sdk/7216>\
**Category:** 읽을거리&정보공유\
**Tags:** sdk, cpp, clickhouse, ai-sdk-cpp\
**Created:** [7월 2, 2025, 9:30오후 UTC](https://discuss.pytorch.kr/t/ai-sdk-cpp-clickhouse-modern-c-ai-api-sdk/7216 "2025-07-02T21:30:05Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![9bow](https://discuss.pytorch.kr/user_avatar/discuss.pytorch.kr/9bow/32/16301_2.png) [@9bow](https://discuss.pytorch.kr/u/9bow)\
**Post date:** [7월 2, 2025, 9:30오후 UTC](https://discuss.pytorch.kr/t/ai-sdk-cpp-clickhouse-modern-c-ai-api-sdk/7216/1 "2025-07-02T21:30:05Z")

</div>

![AI SDK CPP: ClickHouse가 공개한, Modern C++로 AI 서비스에 연동하기 위한 SDK](https://discuss.pytorch.kr/uploads/default/original/2X/6/6bd5bc0d93912795e3033a9e8ab2844bfeb817ff.png)

## AI SDK CPP 프로젝트 소개

오늘은 ClickHouse에서 공개한 ai-sdk-cpp 프로젝트를 소개합니다. 최근 AI 모델의 발전과 함께 다양한 서비스에서 AI 기능을 손쉽게 연동하는 것이 매우 중요해졌습니다. 하지만 C++ 개발자들에게는 Python이나 TypeScript에 비해 AI 서비스 연동이 여전히 불편하거나, 직접 REST API를 핸들링해야 하는 번거로움이 있었습니다. 이런 불편함을 해소하기 위해 등장한 것이 바로 ai-sdk-cpp입니다.

`ai-sdk-cpp`는 OpenAI, Anthropic 등 주요 AI 모델 프로바이더와 쉽게 통합할 수 있는 현대적 C++ 라이브러리입니다. C++20 이상의 문법을 적극적으로 활용하여 클린하고 표현력 있는 코드를 작성할 수 있도록 설계되었으며, 외부 의존성을 최소화하여 다양한 프로젝트에 쉽게 통합할 수 있습니다. 이 라이브러리는 다양한 AI 서비스의 복잡한 구현 세부사항을 추상화하여, 일관된 인터페이스를 통해 다양한 AI 모델을 활용할 수 있도록 지원합니다.

AI 모델 활용이 점점 더 많은 영역에서 요구되고 있는 지금, C++로 서비스나 시스템을 개발하는 엔지니어에게도 손쉽고 안정적인 AI 연동 솔루션이 필요합니다. 기존에 Python 기반 라이브러리만 제공되어 불편을 겪었던 분들, 또는 멀티스레드 환경이나 고성능 처리가 중요한 시스템을 만드는 분들에게 ai-sdk-cpp는 매우 매력적인 선택지가 될 수 있습니다.

또한, ClickHouse는 대용량 데이터베이스 및 분산 시스템 분야에서 널리 알려진 오픈소스 기업으로, 이 프로젝트 역시 그들의 높은 품질 기준에 맞게 개발되었습니다. 해당 라이브러리는 오픈소스로 공개되어 있어 누구나 자유롭게 사용할 수 있고, 커뮤니티 기반의 개선도 활발하게 이루어지고 있습니다.

## AI SDK CPP 프로젝트와 기존의 유사 라이브러리 비교

AI API 연동을 위한 라이브러리는 Python(TensorFlow, Huggingface Transformers)이나 TypeScript(Vercel AI SDK) 기반으로는 이미 많이 존재합니다. 특히 Vercel의 AI SDK는 TypeScript/JavaScript 생태계에서 매우 인기 있는 도구로, 다양한 AI 프로바이더와의 연동을 통합 인터페이스로 지원하는 점이 특징입니다.

하지만 C++에서는 AI 서비스 연동을 위해 별도의 라이브러리 없이 직접 HTTP 요청을 보내거나, Python 바인딩을 통해 우회적으로 연동하는 경우가 많았습니다. 이와 달리, `ai-sdk-cpp`는 C++ 네이티브 환경에서 AI 서비스 연동을 통합적으로 처리할 수 있는 몇 안 되는 오픈소스 프로젝트입니다. 개발자는 AI 모델 제공사의 복잡한 API 스펙을 모두 파악할 필요 없이, 통합된 인터페이스로 원하는 기능을 사용할 수 있습니다.

특히 다음과 같은 특징에서 차별점이 있습니다.

- **C++20 표준 활용** : 최신 C++ 문법과 타입 시스템을 적극 활용해 더 안전하고 간결한 코드 작성 가능
- **API 통합** : OpenAI, Anthropic 등 주요 AI 서비스에 대한 단일 API 제공
- **외부 의존성 최소화** : C++ 프로젝트에 쉽게 통합 가능
- **툴/함수 호출 지원** : LLM Function Calling, Toolset 등 최신 AI 기능도 네이티브 지원

## AI SDK CPP의 주요 기능 및 코드 예제

AI SDK CPP의 주요 기능은 다음과 같습니다:

- **텍스트 생성** : OpenAI, Anthropic 등 주요 AI 모델을 활용한 자연어 생성
- **실시간 스트리밍** : LLM의 답변을 실시간으로 받아오는 스트리밍 방식 지원
- **대화 히스토리** : 멀티턴 대화 지원
- **툴/함수 호출** : Function Calling 및 외부 API 연동 기능
- **비동기 툴** : 비동기 외부 함수 병렬 호출 가능
- **에러 핸들링** : Optional 타입 기반의 에러 처리 지원

각 기능들을 예시와 함께 살펴보겠습니다

### OpenAI 연동 예제

OpenAI API와 통합하여 텍스트 생성 기능을 사용할 수 있습니다. 아래 예시와 같이 간단하게 사용할 수 있습니다:

```c++
#include <ai/openai.h>
#include <ai/generate.h>
#include <iostream>

int main() {
    // OPENAI_API_KEY 환경 변수 필요
    auto client = ai::openai::create_client();
    auto result = client.generate_text({
        .model = ai::openai::models::kGpt4o,
        .system = "You are a friendly assistant!",
        .prompt = "Why is the sky blue?"
    });
    if (result) {
        std::cout << result->text << std::endl;
    }
    return 0;
}

```

### Anthropic 연동 예제

아래 예제와 같이 Anthropic API를 연동하여 Claude 모델의 답변을 얻을 수 있습니다:

```C++
#include <ai/anthropic.h>
#include <ai/generate.h>
#include <iostream>

int main() {
    // ANTHROPIC_API_KEY 환경 변수 필요
    auto client = ai::anthropic::create_client();
    auto result = client.generate_text({
        .model = ai::anthropic::models::kClaude35Sonnet,
        .system = "You are a helpful assistant.",
        .prompt = "Explain quantum computing in simple terms."
    });
    if (result) {
        std::cout << result->text << std::endl;
    }
    return 0;
}

```

### 스트리밍 응답

AI 응답을 실시간 스트리밍 방식으로 받아와 사용하는 것도 가능합니다. 다음의 예시 코드를 참고해주세요:

```c++
#include <ai/openai.h>
#include <ai/stream.h>
#include <iostream>

int main() {
    auto client = ai::openai::create_client();
    auto stream = client.stream_text({
        .model = ai::openai::models::kGpt4o,
        .system = "You are a helpful assistant.",
        .prompt = "Write a short story about a robot."
    });
    for (const auto& chunk : stream) {
        if (chunk.text) {
            std::cout << chunk.text.value() << std::flush;
        }
    }
    return 0;
}

```

### 멀티턴 대화 (대화 히스토리 유지)

AI와 여러 차례의 대화 문맥을 유지하기 위해 기존 메시지들을 포함하여 API를 호출할 수 있습니다. 다음 예시의 `messages` 객체를 참고하세요:

```auto
#include <ai/openai.h>
#include <ai/generate.h>
#include <iostream>

int main() {
    auto client = ai::openai::create_client();
    ai::Messages messages = {
        {"system", "You are a helpful math tutor."},
        {"user", "What is 2 + 2?"},
        {"assistant", "2 + 2 equals 4."},
        {"user", "Now what is 4 + 4?"}
    };
    auto result = client.generate_text({
        .model = ai::openai::models::kGpt4o,
        .messages = messages
    });
    if (result) {
        std::cout << result->text << std::endl;
    }
    return 0;
}

```

### 함수 호출 및 외부 연동(Tool Calling)

AI 모델이 Tool/Function을 직접 호출할 수 있도록 지원합니다. 아래 예시를 참고해주세요:

```c++
#include <ai/openai.h>
#include <ai/generate.h>
#include <ai/tools.h>
#include <iostream>

ai::JsonValue get_weather(const ai::JsonValue& args, const ai::ToolExecutionContext& context) {
    std::string location = args["location"].get<std::string>();
    // 실제 API 연동 로직
    return ai::JsonValue{
        {"location", location},
        {"temperature", 72},
        {"condition", "Sunny"}
    };
}

int main() {
    auto client = ai::openai::create_client();
    ai::ToolSet tools = {
        {"weather", ai::create_simple_tool(
            "weather",
            "Get current weather for a location", 
            {{"location", "string"}},
            get_weather
        )}
    };
    auto result = client.generate_text({
        .model = ai::openai::models::kGpt4o,
        .prompt = "What's the weather like in San Francisco?",
        .tools = tools,
        .max_steps = 3
    });
    if (result) {
        std::cout << result->text << std::endl;
        for (const auto& call : result->tool_calls) {
            std::cout << "Tool: " << call.tool_name 
                      << ", Args: " << call.arguments.dump() << std::endl;
        }
    }
    return 0;
}

```

### 비동기 도구/함수 호출(Async Tool Calling)

AI SDK CPP는 비동기 도구(함수)도 지원하며, 여러 API 호출을 병렬 처리할 수 있습니다:

```c++
#include <future>
#include <thread>
#include <chrono>

// Async tool that returns a future
std::future<ai::JsonValue> fetch_data_async(const ai::JsonValue& args, const ai::ToolExecutionContext& context) {
    return std::async(std::launch::async, [args]() {
        std::this_thread::sleep_for(std::chrono::seconds(1));
        return ai::JsonValue{
            {"data", "Fetched from API"},
            {"timestamp", std::time(nullptr)}
        };
    });
}

```

## 라이선스

AI SDK CPP 프로젝트는 [Apache License 2.0](https://github.com/ClickHouse/ai-sdk-cpp/blob/main/LICENSE)으로 공개 및 배포되고 있습니다. 상업적 사용을 포함한 거의 모든 용도에 제한이 없으나, 라이선스 전문에 명시된 조건(저작권 및 라이선스 고지 포함 등)을 준수해야 합니다.

## :github: AI SDK CPP 프로젝트 GitHub 저장소

[https://github.com/ClickHouse/ai-sdk-cpp](https://github.com/ClickHouse/ai-sdk-cpp)

## 🖼 더 많은 AI SDK CPP 예제

보다 다양한 실전 예제는 [GitHub 저장소의 `examples/` 디렉토리](https://github.com/ClickHouse/ai-sdk-cpp/tree/main/examples)에서 확인하실 수 있습니다.

- [Basic Chat Application](https://github.com/ClickHouse/ai-sdk-cpp/blob/main/examples/basic_chat.cpp)
- [Streaming Chat](https://github.com/ClickHouse/ai-sdk-cpp/blob/main/examples/streaming_chat.cpp)
- [Multi-provider Comparison](https://github.com/ClickHouse/ai-sdk-cpp/blob/main/examples/multi_provider.cpp)
- [Error Handling](https://github.com/ClickHouse/ai-sdk-cpp/blob/main/examples/error_handling.cpp)
- [Basic Tool Calling](https://github.com/ClickHouse/ai-sdk-cpp/blob/main/examples/tool_calling_basic.cpp)
- [Multi-Step Tool Workflows](https://github.com/ClickHouse/ai-sdk-cpp/blob/main/examples/tool_calling_multistep.cpp)
- [Async Tool Execution](https://github.com/ClickHouse/ai-sdk-cpp/blob/main/examples/tool_calling_async.cpp)

* * *

_이 글은 GPT 모델로 정리한 글을 바탕으로 한 것으로, 원문의 내용 또는 의도와 다르게 정리된 내용이 있을 수 있습니다. 관심있는 내용이시라면 원문도 함께 참고해주세요! 읽으시면서 어색하거나 잘못된 내용을 발견하시면 덧글로 알려주시기를 부탁드립니다._ 🤗

[:pytorch:파이토치 한국 사용자 모임🇰🇷](https://pytorch.kr/)이 정리한 이 글이 유용하셨나요? [회원으로 가입](https://discuss.pytorch.kr/signup)하시면 주요 글들을 이메일💌로 보내드립니다! (기본은 Weekly지만 [Daily로 변경도 가능](https://discuss.pytorch.kr/my/preferences/emails)합니다.)

🎁 아래↘쪽에 좋아요👍를 눌러주시면 새로운 소식들을 정리하고 공유하는데 힘이 됩니다~ 🤩
