LLM 툴 호출을 활용한 Go 및 Ollama 구현 방법
카테고리
프로그래밍/소프트웨어 개발
서브카테고리
인공지능
대상자
LLM(대규모 언어 모델) 및 Go 언어를 활용한 애플리케이션 개발자
난이도: 중급 (Ollama API 및 Go 클라이언트 사용 경험 필요)
핵심 요약
- LLM은 직접 함수를 호출하지 않고, JSON 형식의
tool_call
데이터를 생성하여 외부 시스템과 상호작용 - Ollama의 Modelfile을 통해 모델에 툴 정의(
getCurrentWeather
,getAllTours
등)를 명시하고, Go 클라이언트로 API 통신 tool_call
처리 시,tool_response
JSON 데이터를 모델에 전달하여 최종 응답 생성
섹션별 세부 요약
1. LLM 툴 호출 기초 개념
- LLM은 직접 외부 시스템과 상호작용하지 않고, JSON 형식의
tool_call
구조를 생성 - 모델은
tool_input
의 파라미터를 기반으로 함수 호출을 시뮬레이션 (예:getCurrentWeather
) - 외부 시스템에서의 실제 함수 실행은 컨트롤러 프로그램이 담당 (예: Go 클라이언트)
2. Ollama와 Modelfile을 통한 툴 정의
Modelfile
을 통해 시스템 프롬프트에 툴(getCurrentWeather
,getAllTours
)의 이름, 설명, 파라미터 스키마 정의- 예시 JSON 형식:
```json
"tool": "
"tool_input": {"location": "New York City", "unit": "fahrenheit"}
```
- 모델은
tool_call
을 생성 후, 컨트롤러가 JSON 응답(tool_response
)을 제공
3. Go 클라이언트로 Ollama API 통신
- Ollama API의
ChatRequest
를 사용한 툴 호출 예제:
```go
req := &api.ChatRequest{
Model: "llama3.2:3b",
Messages: []api.Message{
{Role: "user", Content: "What is the weather in New York City?"},
},
Tools: api.Tools{
api.Tool{
Name: "getCurrentWeather",
Parameters: api.ToolFunctionParameters{
Required: []string{"location"},
Properties: map[string]api.ToolFunctionProperty{
"location": {Type: "string", Description: "City and state, e.g. San Francisco, CA"},
},
},
},
},
}
```
tool_call
처리 로직:
```go
handler := func(resp api.ChatResponse) error {
if len(resp.Message.ToolCalls) > 0 {
tc := resp.Message.ToolCalls[0].Function
switch tc.Name {
case "getCurrentWeather":
output, _ := getCurrentWeather(tc.Arguments)
messages = append(messages, api.Message{Role: "tool", Content: output})
}
}
return nil
}
```
4. 툴 기반 애플리케이션 확장 사례
walks-of-italy
프로그램 예시:
- getAllTours
: 데이터베이스에서 투어 이름 및 UUID 목록 조회
- getTourAvailability
: 특정 날짜의 투어 가용성, 가격, 수용 인원 확인
- LLM 기반 질문 예시:
- "Vatican 투어 7월 5일 가용성?"
- "로마 8월 3-4일 추천 투어?"
결론
- Ollama API와 Go 클라이언트를 활용한
tool_call
구현은 실제 외부 시스템과의 상호작용을 시뮬레이션 - 모델의 응답을 JSON 형식으로 처리하고,
tool_response
를 기반으로 최종 답변 생성 - 구현 시
tool_call
파라미터 스키마 정의와 컨트롤러 로직을 철저히 검증