AI/LLM

tool calling

아나엘 2025. 2. 10. 09:37

response.choices[0].message.tool_calls

 

tool_calls.function.name

 

create 시 tools=tools

 

def get_response(chat_log: list, tools: dict = None) -> ChatCompletionMessage:
    response = client.chat.completions.create(model="gpt-4o-mini", messages=chat_log, tools=tools)
    if response.choices[0].message.tool_calls:
        tool_call_results = []
        for tool_call in response.choices[0].message.tool_calls:
            call_id = tool_call.id

            if tool_call.function.name == "find_products":
                keywords = json.loads(tool_call.function.arguments)["keywords"]
                products = find_products(keywords)

                call_result_message = {
                    "tool_call_id": call_id,
                    "role": "tool",
                    "content": json.dumps(
                        {"keywords": keywords, "products": str(products)},
                        ensure_ascii=False,
                    ),
                }
                tool_call_results.append(call_result_message)

        messages = chat_log + [response.choices[0].message] + tool_call_results
        response = client.chat.completions.create(
            model="gpt-4o-mini",
            messages=messages,
            tools=tools,
        )

    return response.choices[0].message
    
    
    find_products_info = {
    "name": "find_products",
    "description": "제품 설명에 keywords가 포함된 제품을 찾아서 반환합니다. 찾고자 하는 keywords는 사용자가 요청한 내용과 관련된 제품을 필터링할 수 있는 적절한 키워드여야 합니다.",
    "parameters": {
        "type": "object",
        "properties": {
            "keywords": {
                "type": "array",
                "items": {"type": "string"},
                "description": "사용자가 요청한 내용의 핵심 키워드를 추출합니다.", 
            },
        },
        "required": ["keywords"],
        "additionalProperties": False,
    },
}

tools = [{"type": "function", "function": find_products_info}]

 

openai api를 바로 활용할 때는 chat.completions.create 시 tools=tools로 하고

langchain 활용 시 model.bind_tools(tools)활용 가능

02. 도구 바인딩(Binding Tools) - <랭체인LangChain 노트> - LangChain 한국어 튜토리얼🇰🇷

 

02. 도구 바인딩(Binding Tools)

.custom { background-color: #008d8d; color: white; padding: 0.25em 0.5…

wikidocs.net

 

 

 

sql

def get_response(chat_log: list, tools: dict = None) -> ChatCompletionMessage:
    response = client.chat.completions.create(
        model="gpt-4o-mini", messages=chat_log, tools=tools
    )
    if response.choices[0].message.tool_calls:
        tool_call_results = []
        for tool_call in response.choices[0].message.tool_calls:
            call_id = tool_call.id

            if tool_call.function.name == "query_db":
                keywords = json.loads(tool_call.function.arguments)["query"]
                result = query_db(keywords)

                call_result_message = {
                    "tool_call_id": call_id,
                    "role": "tool",
                    "content": json.dumps(
                        {"result": str(result)},
                        ensure_ascii=False,
                    ),
                }
                tool_call_results.append(call_result_message)

        messages = chat_log + [response.choices[0].message] + tool_call_results
        response = client.chat.completions.create(
            model="gpt-4o-mini",
            messages=messages,
            tools=tools,
        )

    return response.choices[0].message


query_db_info = {
    "name": "query_db",
    "description": "데이터베이스에 쿼리를 실행하고 결과를 반환합니다."
    + DB_SCHEMA,  # DB 스키마 정보 추가
    "parameters": {
        "type": "object",
        "properties": {
            "query": {"type": "string", "description": "실행할 sql 쿼리문"}
        },  
        "required": ["query"],
        "additionalProperties": False,
    },
}
반응형