첨부파일

·3분 읽기

원문: Koog Documentation — Attachments 이 글은 Koog 공식 문서의 Attachments 페이지를 한국어로 옮긴 번역본입니다. 문서 구조와 링크 의미를 유지하되, MkDocs 전용 UI 문법은 블로그에서 읽기 좋도록 정리했습니다.

첨부파일

:material-github: Open on GitHub{ .md-button .md-button--기본 } :material-download: Download .ipynb{ .md-버튼 }

환경 설정

코드를 살펴보기 전에 Kotlin Notebook이 준비되었는지 확인합니다. 여기서는 최신 설명자를 로드하고 Koog 라이브러리를 활성화합니다. AI 모델 제공자와 작업하기 위한 깔끔한 API를 제공합니다.

1// Loads the latest descriptors and activates Koog integration for Kotlin Notebook.2// This makes Koog DSL types and executors available in further cells.3%useLatestDescriptors4%use koog

API 키 구성

환경 변수에서 API 키를 읽습니다. 이를 통해 노트북 파일의 비밀을 유지하고 다음을 수행할 수 있습니다. 공급자를 전환하십시오. OPENAI_API_KEY, ANTHROPIC_API_KEY 또는 GEMINI_API_KEY를 설정할 수 있습니다.

1val apiKey = System.getenv("OPENAI_API_KEY") // or ANTHROPIC_API_KEY, or GEMINI_API_KEY

간단한 OpenAI 실행자 만들기

실행자는 인증, 기본 URL 및 올바른 기본값을 캡슐화합니다. 여기서는 간단한 OpenAI 실행기를 사용합니다. 하지만 나머지 코드를 변경하지 않고도 Anthropic 또는 Gemini로 바꿀 수 있습니다.

1// --- Provider selection ---2// For OpenAI-compatible models. Alternatives include:3//   val executor = simpleAnthropicExecutor(System.getenv("ANTHROPIC_API_KEY"))4//   val executor = simpleGeminiExecutor(System.getenv("GEMINI_API_KEY"))5// All executors expose the same high‑level API.6val executor = simpleOpenAIExecutor(apiKey)

Koog의 프롬프트 DSL을 사용하면 구조화된 마크다운첨부 파일을 추가할 수 있습니다. 이 셀에서는 모델에 짧은 블로그 스타일의 "콘텐츠 카드"를 생성하도록 요청하는 프롬프트를 구축하고 로컬 images/ 디렉터리에서 두 개의 이미지를 첨부합니다.

1import ai.koog.prompt.markdown.markdown2import kotlinx.io.files.Path34val prompt = prompt("images-prompt") {5    system("You are professional assistant that can write cool and funny descriptions for Instagram posts.")67    user {8        markdown {9            +"I want to create a new post on Instagram."10            br()11            +"Can you write something creative under my instagram post with the following photos?"12            br()13            h2("Requirements")14            bulleted {15                item("It must be very funny and creative")16                item("It must increase my chance of becoming an ultra-famous blogger!!!!")17                item("It not contain explicit content, harassment or bullying")18                item("It must be a short catching phrase")19                item("You must include relevant hashtags that would increase the visibility of my post")20            }21        }2223        attachments {24            image(Path("images/kodee-loving.png"))25            image(Path("images/kodee-electrified.png"))26        }27    }28}

응답 실행 및 검사

gpt-4.1에 대해 프롬프트를 실행하고 첫 번째 메시지를 수집하고 해당 내용을 인쇄합니다. 스트리밍을 원할 경우 Koog의 스트리밍 API로 전환하세요. 도구를 사용하려면 emptyList() 대신 도구 목록을 전달하세요.

문제 해결:

  • 401/403 — API 키/환경 변수를 확인하세요.
  • 파일을 찾을 수 없음images/ 경로를 확인하세요.
  • 속도 제한 — 필요한 경우 통화에 최소한의 재시도/백오프를 추가합니다.
1import kotlinx.coroutines.runBlocking23runBlocking {4    val response = executor.execute(prompt = prompt, model = OpenAIModels.Chat.GPT4_1, tools = emptyList()).first()5    println(response.content)6}

표제: 귀여움과 엄청난 웃음력으로 달리세요! 경고: 부작용에는 심장 도둑의 분위기와 즉흥적인 댄스 파티가 포함될 수 있습니다. 💜🤖💃

해시태그: #ViralVibes #UltraFamousBlogger #CutieAlert #기발한 콘텐츠 #InstaFun #SpreadTheLove #DancingToFame #RobotLife #InstaFamous #FeedGoals

1runBlocking {2    val response = executor.executeStreaming(prompt = prompt, model = OpenAIModels.Chat.GPT4_1)3    response.collect { print(it) }4}

표제: 좋은 분위기와 Wi-Fi에서만 실행됩니다! 🤖💜 서킷의 즐거움을 느끼신다면 좋아요를 눌러주세요! #BlogBotInTheWild #심장배달서비스 #DancingWithWiFi #UltraFamousBlogger #MoreFunYourAICat #ViralVibes #InstaFun #BeepBoopFamous