메뉴
HN
Hacker News • 58일 전

Go 기반 AI 백엔드 SDK: 스트리밍과 도구 호출 (React 프론트엔드 라이브러리 포함)

IMP
7/10
핵심 요약

Grafana에서 Go 언어 기반의 새로운 AI SDK를 공개했습니다. 이 SDK는 Vercel AI SDK 설계를 따르며, 별도의 프로토콜 어댑터 없이도 Go 백엔드와 React 프론트엔드 간의 실시간 스트리밍(SSE)을 완벽하게 호환시켜 줍니다. 개발자는 이 도구를 통해 다양한 LLM 제공자를 호출하고 구조화된 출력 및 멀티스텝 에이전트를 손쉽게 구현할 수 있습니다.

번역된 본문

Go 언어를 사용하여 언어 모델을 호출하고, 응답을 스트리밍하며, 도구(Tools)를 실행하고 AI 기반 엔드포인트를 제공해 보세요. 이 SDK를 단독으로 사용하거나 AI SDK React 프론트엔드와 함께 사용할 수 있습니다. (빠른 시작 · 문서 · 예제 · API 참조)

왜 이 SDK인가? 이 SDK는 Go 애플리케이션에 단일 API를 제공하여, 지원되는 다양한 제공자(Providers)에 걸쳐 모델 호출, 스트리밍, 도구 실행, 구조화된 출력, 멀티스텝 에이전트를 처리할 수 있게 해줍니다. Vercel AI SDK의 설계를 따르며, TypeScript 프론트엔드 훅(Hooks)과 와이어(네트워크 통신) 수준에서 완벽하게 호환됩니다. 즉, Go 엔드포인트가 Server-Sent Events(SSE)를 통해 useChat과 같은 훅으로 직접 스트리밍할 수 있습니다.

Go 백엔드 React 프론트엔드 ────────── ────────────── aisdk.StreamText(...) ── SSE ──▶ useChat({ transport }) aisdk.WriteUIMessageStream(w, …) // 동일한 프로토콜 사용

요청이 생성, 도구 호출, 스트리밍 흐름에서 어떻게 실행되는지 확인해 보세요. 기존의 AI SDK React 프론트엔드를 그대로 재사용하거나, 프로토콜 어댑터를 추가할 필요 없이 TypeScript 백엔드를 Go로 교체할 수 있습니다.

주요 기능

  • StreamText / GenerateText: 재시도 및 멀티스텝 도구 실행과 함께 응답을 스트리밍하거나 전체 결과가 나올 때까지 대기
  • React 호환성: useChat, useCompletion, useObject 훅 지원
  • 조합 가능한 도구(Composable tools): 모델에서 일반 Go 함수를 호출하고, 중요한 작업에 대해서는 승인 요구
  • 구조화된 출력: 스키마 검증이 적용된 객체, 배열, 선택지(choices) 생성
  • 다중 제공자 지원: Anthropic, Amazon Bedrock, OpenAI, OpenAI 호환 API 및 내부 서비스인 Grafana 호스팅 엔드포인트 호출
  • 프로덕션 제어: 타임아웃, 폴백(fallback), 로깅, Prometheus 메트릭 및 에이전트 관측 가능성(Observability) 구성

설치 방법 Go 프로젝트를 생성하고 코어 모듈과 하나의 제공자를 설치합니다: mkdir ai-sdk-quickstart cd ai-sdk-quickstart go mod init example.com/ai-sdk-quickstart go get github.com/grafana/ai-sdk go get github.com/grafana/ai-sdk/providers/anthropic

Amazon Bedrock, OpenAI, OpenAI 호환 API 및 Grafana 호스팅 엔드포인트 설정은 '제공자 선택' 문서를 참조하세요.

빠른 시작 다음 완전한 프로그램 코드를 main.go로 저장하세요. 이 코드는 모델을 한 번 호출하고 응답을 출력합니다:

package main

import ( "context" "fmt" "log" "os"

aisdk "github.com/grafana/ai-sdk"
"github.com/grafana/ai-sdk/provider"
"github.com/grafana/ai-sdk/providers/anthropic"

)

func main() { apiKey := os.Getenv("ANTHROPIC_API_KEY") if apiKey == "" { log.Fatal("ANTHROPIC_API_KEY is required") }

model := anthropic.New(apiKey, "claude-sonnet-5")
result, err := aisdk.GenerateText(
	context.Background(),
	model,
	aisdk.WithModelMessages(
		provider.UserText("Explain goroutines in one sentence."),
	),
)
if err != nil {
	log.Fatal(err)
}

fmt.Println(result.Text)

}

Anthropic API 키를 사용하여 실행하세요: ANTHROPIC_API_KEY=sk-... go run .

프로젝트 초기화 및 자격 증명 가이드는 '설치' 문서를 따르세요. 이 응답을 React 클라이언트로 스트리밍하려면 '풀스택 챗 구축하기' 튜토리얼을 계속 진행하세요.

다음 단계

  • Go에서 모델 호출하기: Go에서 텍스트 생성하기
  • React 채팅 구축하기: 풀스택 챗(Full-stack chat)
  • 타입화된 데이터 반환하기: 구조화된 출력(Structured output)
  • 모델이 Go 코드를 호출하게 하기: 도구(Tools)
  • 재사용 가능한 에이전트 구축하기: 에이전트 루프(Agent loops)
  • 모델 제공자 선택하기: 제공자 개요(Provider overview)
  • 로깅 또는 관측 가능성 추가하기: 미들웨어 개요(Middleware overview)
  • 프로덕션 준비하기: 프로덕션 체크리스트(Production checklist)

전체 색인: 문서 · 실행 가능한 코드: 예제 · 정확한 API: pkg.go.dev

기여 기여를 환영합니다. CONTRIBUTING.md는 개발 환경 설정, 이 저장소를 특별하게 만드는 두 가지 관례(Vercel AI SDK와의 업스트림 패리티 유지, OpenSpec을 사용한 스펙 기반 개발), 그리고 풀 리퀘스트 체크리스트를 다루고 있습니다. 모든 참여자는 우리의 행동 강령(Code of Conduct)을 준수해야 합니다.

라이선스 Apache License 2.0. 이 SDK는 역시 Apache-2.0 라이선스를 따르는 Vercel AI SDK의 설계를 따르며, 저작권 표기는 NOTICE 파일에 기록되어 있습니다.

원문 보기
원문 보기 (영어)
Call language models, stream responses, execute tools, and serve AI-powered endpoints from Go. Use the SDK on its own or pair it with an AI SDK React frontend. Quick start · Documentation · Examples · API reference Why The SDK gives Go applications one API for model calls, streaming, tools, structured output, and multi-step agents across supported providers. It follows the design of Vercel's AI SDK and stays wire-compatible with its TypeScript frontend hooks. A Go endpoint can stream Server-Sent Events (SSE) directly to hooks such as useChat . Go backend React frontend ────────── ────────────── aisdk.StreamText(...) ── SSE ──▶ useChat({ transport }) aisdk.WriteUIMessageStream(w, …) // same protocol See How a request runs for the generation, tool, and streaming flow. Reuse an existing AI SDK React frontend or replace a TypeScript backend with Go without adding a protocol adapter. Features StreamText / GenerateText — stream a response or wait for the complete result, with retries and multi-step tool execution React compatibility — serve useChat , useCompletion , and useObject Composable tools — call plain Go functions from a model and require approval for consequential actions Structured output — generate schema-validated objects, arrays, and choices Multiple providers — call Anthropic, Amazon Bedrock, OpenAI, OpenAI-compatible APIs, and Grafana's hosted endpoint from internal services Production controls — configure timeouts, fallback, logging, Prometheus metrics, and Agent Observability Install Create a Go project and install the core module and one provider: mkdir ai-sdk-quickstart cd ai-sdk-quickstart go mod init example.com/ai-sdk-quickstart go get github.com/grafana/ai-sdk go get github.com/grafana/ai-sdk/providers/anthropic See Choose a provider for Amazon Bedrock, OpenAI, OpenAI-compatible APIs, and the internally provisioned Grafana hosted endpoint. Quick start Save this complete program as main.go . It makes one model call and prints the response: package main import ( "context" "fmt" "log" "os" aisdk "github.com/grafana/ai-sdk" "github.com/grafana/ai-sdk/provider" "github.com/grafana/ai-sdk/providers/anthropic" ) func main () { apiKey := os . Getenv ( "ANTHROPIC_API_KEY" ) if apiKey == "" { log . Fatal ( "ANTHROPIC_API_KEY is required" ) } model := anthropic . New ( apiKey , "claude-sonnet-5" ) result , err := aisdk . GenerateText ( context . Background (), model , aisdk . WithModelMessages ( provider . UserText ( "Explain goroutines in one sentence." )), ) if err != nil { log . Fatal ( err ) } fmt . Println ( result . Text ) } Run it with an Anthropic API key: ANTHROPIC_API_KEY=sk-... go run . For project initialization and credential guidance, follow Installation . To stream this response to a React client, continue with Build a full-stack chat . Where to go next Goal Start here Make model calls from Go Generate text from Go Build a React chat Full-stack chat Return typed data Structured output Let a model call Go code Tools Build a reusable agent Agent loops Choose a model provider Provider overview Add logging or observability Middleware overview Prepare for production Production checklist Full index: Documentation · Runnable code: Examples · Exact APIs: pkg.go.dev Contributing Contributions are welcome. CONTRIBUTING.md covers the development setup, the two conventions that make this repository unusual — upstream parity with the Vercel AI SDK, and spec-driven development with OpenSpec — and the pull request checklist. All participants follow our Code of Conduct . License Apache License 2.0 . This SDK follows the design of Vercel's AI SDK , also Apache-2.0 licensed; attribution is recorded in NOTICE .