Skip to main content

katcloud

한국에이아이통신(주) KAT Cloud API 용 Python SDK 입니다. 표준 라이브러리만 쓰고 Python 3.8 이상에서 동작합니다.

KAT Cloud 는 AI 에이전트를 한국 전화망에 연결하는 통신 인프라입니다. 070 번호 발급, 문자, 통화 기록, AI 발신, 웹훅을 API 로 다룹니다.

설치

pip install katcloud

사용

from katcloud import Client, KatError

kat = Client(api_key="zpa...")          # 또는 환경 변수 KATCLOUD_API_KEY

# 번호 발급
group_id = kat.create_group(group_title="my-agent")
for group in kat.list_groups():
    print(group["phoneNumber"])

# 문자 보내기
chat_id = kat.send_message("01098765432", "예약이 확정되었습니다.", from_number="07012345678")

# AI 발신 (실제 전화가 걸리고 요금이 생길 수 있습니다)
call = kat.create_ai_outbound_call(group_id, {
    "agentId": 12,
    "callerChannelId": 34,
    "destination": "01098765432",
    "inputs": {},
})

try:
    kat.list_agents(group_id)
except KatError as e:
    print(e.status, e.code, e.message)

0.2.0 에서 늘어난 것

공개 API 의 경로를 거의 모두 메서드로 부를 수 있습니다. 메서드 하나가 API 경로 하나입니다.

  • 그룹: 요금제 목록, 그룹 조회·수정, 멤버, 예산 한도, 통화 안내멘트, 착신전환
  • 번호: 추가 견적·추가·반납, 번호별 착신 경로 조회·변경·시험
  • AI 에이전트: 만들기·수정·삭제, 변경 이력, 음성 목록, 번호 연결, 매뉴얼, 도구
  • 통화: 통화 이벤트, 녹음 중지, 통화 기록 삭제, 상대방 기록 삭제, 녹음·마스킹·보관 설정
  • 미디어 스트림: 발신·조회·종료·전환, 수신 번호 설정
  • SIP 트렁크: 목록·만들기·수정·삭제·비밀번호 재발급
  • 그룹별 웹훅, 카카오 알림톡, 채팅방, 크레딧·사용량 조회

요청 본문은 API 문서의 필드 이름 그대로 dict(객체)로 넘깁니다. 서버에 새 필드가 생겨도 SDK 를 올리지 않고 쓸 수 있습니다. 요금제나 설정에 따라 일부 경로는 403 으로 거절될 수 있습니다.

자동 재시도도 생겼습니다. 429(요청 제한)는 모든 요청을, 네트워크 오류와 502·503·504 는 조회(GET)만 다시 보냅니다. 전화 걸기나 문자 보내기 같은 요청은 두 번 실행될 수 있어 자동으로 다시 보내지 않습니다. 기본 2회이고 Client(max_retries=0) 으로 끕니다.

kat.set_number_routing(group_id, "07012345678", {...})     # 번호 착신 경로
kat.create_agent(group_id, {...})                          # AI 에이전트 만들기
kat.list_call_events(group_id, call_id)                    # 통화 이벤트
kat.get_credit_summary()                                   # 남은 크레딧

비동기로 쓰기

AsyncClient 는 Client 와 메서드 이름이 같고 전부 await 로 부릅니다. 여러 요청을 동시에 보낼 수 있습니다.

import asyncio
from katcloud import AsyncClient

async def main():
    async with AsyncClient(api_key="zpa...") as kat:
        groups, credit = await asyncio.gather(kat.list_groups(), kat.get_credit_summary())

asyncio.run(main())

동시에 보내는 요청 수는 기본 10개이고 AsyncClient(max_concurrency=20) 으로 바꿉니다.

통화 이벤트 조회(list_call_events)에는 AI 발신 요청 ID 가 아니라 통화 기록 ID(callHistoryId)를 넣습니다.

음성 에이전트 만들기

KAT Cloud 미디어 스트림은 통화 음성을 WebSocket 으로 내 서버에 이어 줍니다. katcloud.voice 는 그 서버 쪽을 대신 처리합니다. 추가 설치 없이 표준 라이브러리만 씁니다.

from katcloud.voice import MediaStreamServer

async def handle(call):
    print(call.direction, call.from_number, call.to_number)
    async for event in call:
        if event.type == "media":
            await call.send_audio(event.audio)      # 들은 소리를 그대로 돌려줍니다
        elif event.type == "dtmf":
            print("누른 키", event.digit)

MediaStreamServer(handle, port=8080, secret="whsec_...").run()
  • 받는 것: media(상대 음성, G.711 8kHz, 20ms 에 160바이트), dtmf, mark, transfer.*, stop
  • 보내는 것: call.send_audio(bytes), call.send_pcm16(pcm, sample_rate), call.mark(name), call.clear()(끼어들기), call.send_dtmf("1#"), call.transfer("01012345678", on_fail="resume"), call.hangup()
  • 음성 변환: ulaw_to_pcm16, pcm16_to_ulaw, alaw_to_pcm16, pcm16_to_alaw, resample_pcm16
  • handle 이 끝나면 전화를 끊습니다. secret 을 넣으면 KAT Cloud 서명이 없는 접속은 거절합니다.

KAT Cloud 는 공인 wss:// 주소로만 접속합니다. 이 서버 앞에 TLS 를 처리하는 프록시(nginx, 로드밸런서, 터널)를 두거나 ssl= 에 인증서를 넣습니다. 그 주소를 발신(create_media_stream_call 의 streamUrl)이나 번호의 수신 설정에 넣으면 됩니다.

음성 모델을 바로 붙이는 처리기도 들어 있습니다. 통화 음성을 변환 없이 그대로 주고받고, 상대가 말을 시작하면 모델의 말을 끊습니다.

from katcloud.voice import MediaStreamServer, openai_realtime

MediaStreamServer(
    openai_realtime(
        api_key="sk-...",
        instructions="당신은 병원 예약 상담원입니다. 짧고 공손하게 답합니다.",
        greeting="안녕하세요, 예약 상담입니다. 무엇을 도와드릴까요?",
    ),
    port=8080,
    secret="whsec_...",
).run()

음성 모델 연결 처리기는 네 가지입니다. 모두 상대가 말을 시작하면 모델의 말을 끊습니다.

처리기 붙는 곳 음성
openai_realtime(api_key, instructions, ...) OpenAI Realtime G.711 그대로
gemini_live(api_key, instructions, ...) Google Gemini Live 16비트 PCM 으로 변환
elevenlabs_agent(agent_id, api_key=None, ...) ElevenLabs 에이전트 에이전트 설정이 ulaw_8000 이면 그대로, PCM 이면 변환
deepgram_agent(api_key, instructions, ...) Deepgram Voice Agent G.711 그대로
from katcloud.voice import MediaStreamServer, gemini_live

MediaStreamServer(
    gemini_live(api_key="...", instructions="당신은 병원 예약 상담원입니다.", greeting="안녕하세요, 예약 상담입니다."),
    port=8080,
).run()

도구, 끊기, 사람에게 넘기기

네 처리기 모두 같은 인자를 받습니다.

async def check_order(order_id: str) -> str:
    """주문 상태를 확인한다."""
    return "배송 완료"

handler = openai_realtime(
    api_key="...",
    instructions="가게 상담원입니다.",
    tools=[check_order],              # 내 함수를 모델이 부른다
    transfer_to=["01012345678"],      # 받는 전화에서 사람에게 넘기기
)
  • tools: 함수 이름, 설명글(docstring), 인자 타입이 그대로 도구 정의가 됩니다. 돌려준 값은 모델에게 전달되고, 예외가 나면 그 내용을 모델이 듣습니다. 인자 이름을 call 로 두면 통화 객체를 받습니다. 이름이나 인자 형식을 직접 정하려면 @tool(name=..., description=..., parameters=...) 를 붙입니다.
  • 끊기: 모델이 통화를 스스로 끊습니다(기본 켜짐, hangup=False 로 끔). 작별 인사가 다 재생된 뒤 끊습니다.
  • transfer_to: 받는 전화에서 모델이 사람에게 통화를 넘깁니다. 아무도 받지 않으면 모델에게 돌아옵니다.
  • ElevenLabs 는 도구 정의를 ElevenLabs 화면의 에이전트(client tool)에 두고, 여기서는 같은 이름의 함수가 실행만 합니다. 에이전트가 대화를 스스로 끝내면 마지막 말이 재생된 뒤 끊습니다.
  • Deepgram 과 조립형(pipeline)은 글 모델이 답하므로 hang_up·transfer_call 도구가 마지막 말(message)을 함께 받습니다. 모델이 말없이 도구만 부르면 SDK 가 그 말을 먼저 하게 한 뒤(Deepgram 은 InjectAgentMessage) 끊거나 넘깁니다.
  • Deepgram 음성 합성(deepgram_tts, deepgram_agent 의 기본 aura 목소리)에는 2026년 12월 현재 한국어 목소리가 없습니다(Deepgram /v1/models 의 합성 언어는 de, en, es, fr, it, ja, nl). Deepgram 음성 인식은 한국어를 지원합니다. deepgram_agent 로 한국어로 말하게 하려면 speak= 에 다른 회사의 음성 합성을 지정합니다.

키패드 번호 누르기

dtmf=True 를 주면 모델이 send_dtmf 도구로 키패드 번호를 누릅니다(기본 꺼짐). 거는 전화에서 상대 회사의 ARS 메뉴를 지나가거나 번호 입력을 요구받을 때 씁니다.

handler = openai_realtime(
    api_key="...",
    instructions="병원 ARS 에 전화해 예약 창구로 연결한 뒤 예약을 확인합니다.",
    dtmf=True,
)
  • 누를 수 있는 키는 0-9, *, # 이고 한 번에 20개까지입니다. 쉼표(,)는 0.5초 쉽니다. 그 밖의 글자는 누르지 않고 오류를 모델에게 돌려줍니다.
  • 번호를 누른 뒤에는 모델이 따로 말하지 않고 메뉴 안내를 기다립니다. 누른 번호는 기록(로그·span)에 남기지 않고 개수만 남깁니다.
  • 상대가 누른 키는 설정과 관계없이 모델에게 (The caller pressed 1 on the keypad.) 같은 사용자 메시지로 전달됩니다. OpenAI Realtime 과 조립형(pipeline)은 말하던 중이면 말을 멈춥니다. OpenAI Realtime 은 대화 항목, Gemini Live 는 clientContent, ElevenLabs 는 user_message, Deepgram 은 InjectUserMessage 로 보냅니다.
  • ElevenLabs 는 다른 도구처럼 에이전트에 send_dtmf client tool(인자 digits, 문자열)을 직접 추가해야 합니다.

MCP 서버의 도구 쓰기

MCP 서버(HTTP)가 가진 도구를 그대로 통화 중 도구로 쓸 수 있습니다. 프로그램을 시작할 때 한 번 불러옵니다.

from katcloud.voice import mcp_tools

tools = await mcp_tools(
    "https://api.katcloud.kr/mcp",
    headers={"Authorization": "Bearer " + KAT_KEY},
    only=["send_message", "list_agents"],   # 통화에 필요한 것만
)
handler = openai_realtime(api_key=KEY, instructions="...", tools=tools + [check_order])

음성 모델은 도구가 적을수록 잘 고르므로 only 로 몇 개만 추리는 것을 권합니다.

음성 인식 + 글 모델 + 음성 합성으로 조립하기

음성 모델 하나에 맡기는 대신 세 부분을 골라 조립할 수 있습니다. 모델이 쓴 글이 그대로 읽히므로 인사말이나 고지 문구를 글자 그대로 말하게 할 수 있고, 글 모델은 OpenAI 호환 주소를 가진 곳이면 어디든 쓸 수 있습니다.

from katcloud.voice import MediaStreamServer, pipeline, openai_stt, openai_chat, openai_tts

handler = pipeline(
    stt=openai_stt(api_key=KEY),                       # 또는 deepgram_stt(api_key=...)
    llm=openai_chat(api_key=KEY, model="gpt-4o-mini"), # base_url 로 다른 회사 지정
    tts=openai_tts(api_key=KEY, voice="alloy"),        # 또는 elevenlabs_tts(api_key=..., voice_id=...)
    instructions="가게 상담원입니다. 한 문장씩 짧게 답합니다.",
    greeting="안녕하세요, 가게입니다.",                 # 글자 그대로 읽습니다
    tools=[check_order],
)
MediaStreamServer(handler, port=8765).run()
  • 상대가 말을 시작하면 하던 말을 멈추고(끼어들기) 새로 들은 말에 답합니다.
  • tools, 끊기(hangup), transfer_to 는 위와 같습니다. 끊거나 넘길 때 할 말은 모델이 도구 인자로 넘기고, 그 말이 다 재생된 뒤 실행합니다.
  • on_event(call, event) 로 transcript(들은 말), dtmf(상대가 누른 키, digit), speech(한 말), tool_call, error 를 받습니다. 모델·합성 요청이 실패해도 통화는 이어집니다.
  • dtmf=True 와 상대가 누른 키는 위 "키패드 번호 누르기" 와 같습니다.
  • openai_chat(base_url=...): Groq, DeepSeek, Together, Fireworks, Mistral, xAI, Ollama 처럼 /chat/completions 가 호환되는 곳.
  • Gemini 글 모델: openai_chat(api_key=GEMINI_KEY, base_url="https://generativelanguage.googleapis.com/v1beta/openai", model="gemini-flash-lite-latest"). 도구 호출에 붙는 Gemini 서명은 SDK 가 그대로 돌려줍니다.
  • 음성 합성: openai_tts, elevenlabs_tts, deepgram_tts(Deepgram Aura, model 로 목소리·언어), google_tts(Google Cloud, 기본 ko-KR, voice="ko-KR-Chirp3-HD-..."). google_tts 는 api_key 또는 access_token(토큰이나 토큰을 돌려주는 함수, 사용자 계정이면 project 도)을 받습니다. 함수가 돌려준 토큰은 5분 동안 다시 쓰고, 그 뒤나 401 을 받으면 새로 받아 한 번 더 시도합니다. 일반 함수는 별도 스레드에서 불러 통화를 멈추지 않습니다.
  • anthropic_chat(): Claude. 이 부품만 Anthropic 공식 패키지가 필요합니다: pip install "katcloud[anthropic]". 키는 api_key 또는 환경 변수 ANTHROPIC_API_KEY, 기본 모델은 claude-haiku-5-5, effort(기본 "low")로 답하기 전에 생각하는 정도를 정합니다. 전화에서 상대 말이 끝난 뒤 첫 동작까지 Opus 5.5 는 약 11초, Haiku 5.5 는 약 4~6초여서 Haiku 가 기본입니다. Opus 를 쓰려면 model="claude-opus-5-5" 를 넘깁니다.

각 처리기는 그 회사 문서(2026-12 기준)의 메시지 형식에 맞춰 만들었습니다. 모델 이름과 세부 설정은 인자(model, session, setup, init, settings)로 바꾸고, on_event(call, event) 로 모델이 보내는 이벤트(대화 내용, 도구 호출)를 받습니다. 여기에 없는 모델은 handle 안에서 call 의 음성을 직접 이어 붙이면 됩니다.

전화 없이 시험하기

FakePhone 은 KAT Cloud 쪽 역할을 대신해 내 MediaStreamServer 에 로컬(127.0.0.1)로 접속합니다. 공개 주소, 터널, 실제 전화 없이 처리기를 단위 테스트할 수 있습니다.

from katcloud.voice import FakePhone, MediaStreamServer

async def test_menu():
    async with MediaStreamServer(handle, host="127.0.0.1", port=0) as server:
        async with FakePhone(server, from_number="01012345678") as phone:
            await phone.send_file("hello.wav")        # 20 ms 씩 실제 통화 속도로
            await phone.wait_for_audio(0.5)           # 처리기가 0.5초 이상 말할 때까지
            await phone.press("1")
            assert await phone.wait_closed() == 1000  # 처리기가 통화를 끝냄
  • 접속하면 connected, start 를 보내고, 처리기가 보낸 메시지는 phone.messages 에 순서대로 쌓입니다. 재생한 소리는 phone.audio(G.711)·phone.pcm16, 누른 키는 phone.dtmf 입니다.
  • 소리 보내기: send_audio(G.711 바이트), send_pcm16(pcm, sample_rate), send_file(경로)(WAV 16비트 PCM 아무 주파수나 8 kHz G.711, 모노, 또는 G.711 원본), silence(초). realtime=False 면 기다리지 않고 한 번에 보냅니다.
  • press("12#") 로 키를 누르고, send_event("transfer.failed", {...}) 로 그 밖의 이벤트를 보냅니다. hangup() 은 stop 을 보내고 끊습니다(async with 를 벗어날 때 자동).
  • mark 는 바로 재생이 끝난 것으로 답합니다. 직접 답하려면 FakePhone(server, auto_mark=False) 로 만들고 ack_mark(name) 을 부릅니다.
  • wait_for("media") 는 처리기가 보낸 다음 메시지를 기다립니다(이전에 돌려준 것 다음부터). 조건 함수도 받습니다.
  • codec="PCMA", direction="outbound", custom_parameters={...} 로 통화 조건을 바꾸고, 서버에 secret 을 걸었다면 같은 값을 secret= 으로 주면 KAT Cloud 처럼 서명합니다.
  • 음성 모델을 쓰는 처리기는 모델 회사에 실제로 접속합니다. 모델 없이 시험하려면 모델 주소(url, base_url)를 가짜 서버로 바꿉니다(저장소의 python/tests 참고).

예제

examples/python 에 바로 돌려 볼 수 있는 짧은 예제가 있습니다. 키는 환경 변수에서만 읽습니다.

  • echo_server.py: 받은 소리를 돌려주는 기본형, 1 을 누르면 끊기
  • test_echo.py: 위 처리기를 FakePhone 으로 시험(python -m unittest examples/python/test_echo.py)
  • realtime_agent.py: OpenAI Realtime 상담원 + 주문 조회 도구 + 사람에게 넘기기
  • pipeline_agent.py: OpenAI 음성 인식·글 모델·음성 합성 조립, 키패드 번호 누르기

통화 기록과 추적

통화 시작·끝, 도구 호출(걸린 시간·실패), 끊기·넘기기, 첫 응답까지 걸린 시간을 표준 logging 의 katcloud.voice 로 남깁니다. 들은 말과 한 말은 DEBUG 에만 나옵니다.

import logging
logging.basicConfig(level=logging.INFO)   # 들은 말까지 보려면 DEBUG

pip install "katcloud[otel]" 로 OpenTelemetry 를 깔면 통화마다 katcloud.call span 이 생기고, 그 안에 대화 차례(katcloud.turn, 첫 응답 시간 포함)와 도구 실행(katcloud.tool) span 이 붙습니다. 내보내기(exporter)는 내 프로그램의 OpenTelemetry 설정을 따르고, 처리기(handler)가 통화 span 안에서 돌기 때문에 내 도구에서 만든 span 도 통화 아래에 붙습니다. 전화번호, 도구 인자, 대화 내용은 span 에 넣지 않습니다.

웹훅 서명 검증

from katcloud import construct_event

event = construct_event(raw_body, headers, secret)   # 실패하면 WebhookSignatureError

라이선스

MIT

Metadata

Release files for katcloud 0.12.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for katcloud 0.12.2
File Size Uploaded Provenance Actions
katcloud-0.12.2.tar.gz 92.1 kB With provenance Details for katcloud-0.12.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for katcloud 0.12.2
File Interpreter ABI Platform Actions
katcloud-0.12.2-py3-none-any.whl Python 3 none any Details for katcloud-0.12.2-py3-none-any.whl

Total release size: 157.1 kB

Release files / katcloud-0.12.2.tar.gz

Download URL katcloud-0.12.2.tar.gz
Size 92.1 kB
Tags Source
SHA-256 checksum
How to use checksums
e017a0e5b9e28be32d960b2fc08f639179fd567f31bc7e7c8c0a4569c588a777
BLAKE2b-256 checksum
How to use checksums
10b181335f9c57571fa2aa086896da4c214442a102fea05f8e6ce2eb020c8350
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 5, 2026.

Transparency log

Release files / katcloud-0.12.2-py3-none-any.whl

Download URL katcloud-0.12.2-py3-none-any.whl
Size 65.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
905525f5f7d6286c078b45e746e6fba9c6745494ebd3a358801085f5fbd067ac
BLAKE2b-256 checksum
How to use checksums
fefbc63902c3248fa9ee053b6dc33a3e59604eb6e81552781fd495eed9eaafdd
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 5, 2026.

Transparency log

Security for katcloud 0.12.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for katcloud-0.12.2.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 5, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page