https://platform.openai.com/docs/guides/function-calling
Function calling
connect language models to external data and systems
define a set of functions as tools that the model has access to,
execute those functions on the application side, and provide results back to the model
from openai import OpenAI
client = OpenAI()
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string"}
},
},
},
}
]
completion = client.chat.completions.create(
model="gpt-4o",
messages=[{"role": "user", "content": "What's the weather like in Paris today?"}],
tools=tools,
)
print(completion.choices[0].message.tool_calls)
tools로 전달해서 사용
tool_calls로 부르네
fuction call이 유용한 경우
- 데이터 가져오기: 대화형 어시스턴트가 사용자에게 응답하기 전에 내부 시스템에서 데이터를 검색 가능
- 작업 수행: 어시스턴트가 회의 예약이나 주문 반품 시작과 같은 대화를 기반으로 작업을 트리거할 수 있도록
- 풍부한 워크플로 구축: 어시스턴트가 데이터 추출 파이프라인이나 콘텐츠 개인화와 같은 다단계 워크플로를 실행 가능.
- 애플리케이션 UI와 상호작용: 함수 호출을 사용하여 지도에 핀을 렌더하거나 웹사이트 탐색처럼 사용자 입력에 따라 사용자 인터페이스를 업데이트 가능
The lifecycle of a function call
모델은 실제로 함수를 직접 실행하지 않고 함수를 호출하는 데 사용할 수 있는 매개변수만 생성
= > 코드에서 함수가 실행되는 방식을 처리할 책임은 사용자에게 있음
Function calling support
API
Chat Completions API, Assistants API, Batch API and Realtime API 사용 가능
Chat Completions | 대화 기반 상호작용 구현 | 대화 문맥 유지 가능 | AI 챗봇, 고객 지원 |
Assistants API | 고도로 특화된 AI 어시스턴트 구현 | 상태 유지 및 도메인 맞춤화 | 도메인 기반 어시스턴트 |
Batch API | 대량의 요청 처리 | 여러 요청을 한번에 처리 | 문서 처리, 대량 번역 |
Realtime API | 실시간 상호작용 | 응답을 스트리밍 형태로 제공 | 실시간 대화형 애플리케이션 |
모델
gpt-4-turbo 릴리즈 이후 All gpt-* models 사용 가능
Function definition
The starting point for function calling
=> choosing a function in your own codebase that you'd like to enable the model to generate arguments for.
create a “function definition” that describes the function to the model
=> describes
1. what the function does (and potentially when it should be called)
2.what parameters are required to call the function ( should be described using JSON Schema )
{
"name": 함수이름,
"description": 이 함수가 하는 일~ 역할 언제 호출해야 하는지~ 전반적인 설명 등,
"parameters": {# 함수의 파라미터 설명
"type": 전달되는 매개변수의 데이터 타입. 일반적으로 object로 설정
"properties": { # 각 매개변수의 이름과 세부 정보를 정의
"order_id": { # 이 파라미터 이름
"type": 이 파라미터 타입,
"description": 이 파라미터 설명
}
},
"required": 필수로 제공되어야 할 매개변수 이름들을 배열로 명시
"additionalProperties": 정의되지 않은 추가 매개변수 허용 여부를 지정. false라면 정의된 매개변수만 허용.
}
}
Model instructions
함수 정의에도 함수 호출 방법 설명프롬프트에도 함수 호출 시점 설명
Handling model responses
모델은 적절한 경우에만 함수 호출을 제안하고 정의된 함수에 대한 인수를 생성
=> 그런 다음 이러한 제안을 기반으로 애플리케이션에서 함수 실행을 처리하는 방법을 결정하는 것은 사용자의 몫
모델이 함수를 호출해야 한다고 판단하면 응답에 tool_calls 필드를 반환하며, 이를 사용하여 모델이 함수 호출을 생성했는지 여부와 인수가 무엇인지 확인할 수 있음
If the model decides that no function should be called
contain a direct reply to the user as a regular chat completion response.
chat.completionsMessage(
content='Hi there! I can help with that. Can you please provide your order ID?',
role='assistant',
function_call=None,
tool_calls=None
)
If the model generated a function call
generate the arguments for the call (based on the parameters definition you provided).
Choice(
finish_reason='tool_calls',
index=0,
logprobs=None,
message=chat.completionsMessage(
content=None,
role='assistant',
function_call=None,
tool_calls=[
chat.completionsMessageToolCall(
id='call_62136354',
function=Function(
arguments='{"order_id":"order_12345"}',
name='get_delivery_date'),
type='function')
])
)
이후 사용자가 함수 처리하기
Submitting function output
함수 응답 결과를 바탕으로 다시 모델 호출하기
Structured Outputs
Structured Outputs와 같이 쓰기~
출력 형식 고정 exactly matches a specified JSON schema
strict: true
additionalProperties: false
엄격한 스키마 준수를 보장
parallel_tool_calls: false
병렬 함수 호출 비활성화
모델이 한 번에 하나의 함수 호출을 생성
Best practices
✔️ Turn on Structured Outputs by setting strict: "true"
✔️ Name functions intuitively, with detailed descriptions
✔️ Name function parameters intuitively, with detailed descriptions\
✔️ Consider providing additional information about how and when to call functions in your system message
✔️ Use enums for function arguments when possible
✔️ Keep the number of functions low for higher accuracy
✔️ Set up evals to act as an aid in prompt engineering your function definitions and system messages
✔️ Fine-tuning may help improve accuracy for function calling
이거 왜 삭제가 안 되지
강한 인용작대기..
'🤖 AI > AI' 카테고리의 다른 글
🔬LLM 어플리케이션 개발하기 : LLM 캐시 (7) | 2025.01.15 |
---|---|
🔬LLM 어플리케이션 개발하기 : RAG 검색 증강 생성 - llamaIndex (0) | 2025.01.14 |
🔬말 잘 듣는 모델 만들기 2 : 강화 학습(PPO/RLHF), 기각 샘플링/DPO (0) | 2025.01.10 |
🔬말 잘 듣는 모델 만들기 1 : 미세 조정 (0) | 2025.01.10 |
✍️ OpenAI Cookbook : Prompting libraries & tools & guides 구경 (0) | 2025.01.09 |