Skip to content

Ollama:Python

Ollama Python Library

Examples

REST API Spec

Python 함수를 도구로 전달하기

먼저 일반 Python 함수를 정의합니다. 더 나은 결과를 얻으려면 매개변수와 반환 값 유형에 주석을 달고, 필요에 따라 Google 스타일 docstring을 추가합니다 .

def add_two_numbers(a: int, b: int) -> int:
  """
  Add two numbers

  Args:
    a: The first integer number
    b: The second integer number

  Returns:
    int: The sum of the two numbers
  """
  return a + b

다음으로, tools필드를 사용하여 Ollama에 도구로 함수를 전달합니다.

import ollama

response = ollama.chat(
  'llama3.1',
  messages=[{'role': 'user', 'content': 'What is 10 + 10?'}],
  tools=[add_two_numbers], # Actual function reference
)

모델에서 제공된 반환된 도구 호출과 인수를 사용하여 해당 함수를 호출합니다.

available_functions = {
  'add_two_numbers': add_two_numbers,
}

for tool in response.message.tool_calls or []:
  function_to_call = available_functions.get(tool.function.name)
  if function_to_call:
    print('Function output:', function_to_call(**tool.function.arguments))
  else:
    print('Function not found:', tool.function.name)

Troubleshooting

pydantic_core._pydantic_core.ValidationError: 1 validation error for ShowResponse

pydantic_core._pydantic_core.ValidationError: 1 validation error for ShowResponse
model_info
  Field required [type=missing, input_value={'modelfile': '# Modelfil...ization_level': 'Q8_0'}}, input_type=dict]
    For further information visit https://errors.pydantic.dev/2.11/v/missing

See also

Favorite site