Fireworks 함수 호출 쿡북

Fireworks 함수 호출 쿡북 (Function Calling Cookbook)

Fireworks.ai의 LLM은 OpenAI와 유사하게 함수 호출(function calling)을 지원해요. 사용 가능한 도구·함수 집합을 직접 묘사하면, 복잡한 프롬프팅 없이도 모델이 호출할 함수를 스스로 고르게 할 수 있어요.

출처: 문서

본문

Fireworks LLM은 OpenAI를 직접 서브클래싱하므로, 기존 추상화를 Fireworks와 함께 그대로 사용할 수 있어요.

이를 세 가지 수준으로 보여 줍니다. 모델 API에서 직접 쓰기, Pydantic Program의 일부로 쓰기(구조화된 출력 추출), 그리고 에이전트의 일부로 쓰기예요.

%pip install llama-index-llms-fireworks
%pip install llama-index
import os


os.environ["FIREWORKS_API_KEY"] = "fw_3ZkvBpQyjRzbicpihhrihaEP"
from llama_index.llms.fireworks import Fireworks


## 함수 호출 모델 목록: https://app.fireworks.ai/models/?filter=LLM&functionCalling=true
llm = Fireworks(
    model="accounts/fireworks/models/deepseek-v3p1-terminus", temperature=0
)

LLM 모듈에서의 함수 호출 (Function Calling on the LLM Module)

LLM 모듈에 직접 함수 호출을 입력할 수 있어요.

import os
import json
from openai import OpenAI
from pydantic import BaseModel, Field
from llama_index.llms.openai.utils import to_openai_tool




class Song(BaseModel):
    """A song with name and artist"""


    name: str = Field(description="The name of the song")
    artist: str = Field(description="The artist who performed the song")




song_fn = to_openai_tool(Song)


# Fireworks 클라이언트 초기화
client = OpenAI(
    api_key=os.environ.get("FIREWORKS_API_KEY"),
    base_url="https://api.fireworks.ai/inference/v1",
)


response = client.chat.completions.create(
    model="accounts/fireworks/models/kimi-k2-instruct-0905",
    messages=[{"role": "user", "content": "Generate a song from Beyonce"}],
    tools=[song_fn],
    temperature=0.1,
)


print(response)


if response.choices[0].message.tool_calls:
    tool_call = response.choices[0].message.tool_calls[0]
    print(f"\nTool called: {tool_call.function.name}")


    # 구조화된 출력을 얻기 위해 인자를 파싱
    arguments = json.loads(tool_call.function.arguments)
    print(f"Arguments: {arguments}")


    # 구조화된 출력으로 Song 인스턴스 생성
    song = Song(**arguments)
    print(f"\nExtracted Song:")
    print(f"Name: {song.name}")
    print(f"Artist: {song.artist}")
ChatCompletion(id='07921e74-5dca-409c-a4d3-1a2e0c7cd1e7', choices=[Choice(finish_reason='stop', index=0, logprobs=None, message=ChatCompletionMessage(content='```json\n{\n  "name": "Halo",\n  "artist": "Beyoncé"\n}\n```', refusal=None, role='assistant', annotations=None, audio=None, function_call=None, tool_calls=None))], created=1761704700, model='accounts/fireworks/models/kimi-k2-instruct-0905', object='chat.completion', service_tier=None, system_fingerprint=None, usage=CompletionUsage(completion_tokens=25, prompt_tokens=145, total_tokens=170, completion_tokens_details=None, prompt_tokens_details=PromptTokensDetails(audio_tokens=None, cached_tokens=0)))

더 알아보기 (Learn more)