Skip to content

Ollama unterstützt den Tool-Aufruf (auch bekannt als Funktionsaufruf), der es einem Modell ermöglicht, Tools aufzurufen und deren Ergebnisse in seine Antworten zu integrieren.

Aufruf eines einzelnen Tools

Rufen Sie ein einzelnes Tool auf und binden Sie dessen Antwort in eine Folgeanfrage ein.

Auch bekannt als „Single-Shot“-Tool-Aufruf.

cURL

```shell
curl -s http://localhost:11434/api/chat -H "Content-Type: application/json" -d '{
  "model": "qwen3",
  "messages": [{"role": "user", "content": "What is the temperature in New York?"}],
  "stream": false,
  "tools": [
    {
      "type": "function",
      "function": {
        "name": "get_temperature",
        "description": "Get the current temperature for a city",
        "parameters": {
          "type": "object",
          "required": ["city"],
          "properties": {
            "city": {"type": "string", "description": "The name of the city"}
          }
        }
      }
    }
  ]
}'
```

**Generieren einer Antwort mit einem einzelnen Tool-Ergebnis**
```shell
curl -s http://localhost:11434/api/chat -H "Content-Type: application/json" -d '{
  "model": "qwen3",
  "messages": [
    {"role": "user", "content": "What is the temperature in New York?"},
    {
      "role": "assistant",
      "tool_calls": [
        {
          "type": "function",
          "function": {
            "index": 0,
            "name": "get_temperature",
            "arguments": {"city": "New York"}
          }
        }
      ]
    },
    {"role": "tool", "tool_name": "get_temperature", "content": "22°C"}
  ],
  "stream": false
}'
```

Python

Installieren Sie das Ollama Python SDK:
```bash
# with pip
pip install ollama -U

# with uv
uv add ollama
```

```python
from ollama import chat

def get_temperature(city: str) -> str:
  """Holen Sie die aktuelle Temperatur für eine Stadt ab

  Argumente:
    city: Der Name der Stadt

  Rückgabewert:
    Die aktuelle Temperatur für die Stadt
  """
  temperatures = {
    "New York": "22°C",
    "London": "15°C",
    "Tokyo": "18°C",
  }
  return temperatures.get(city, "Unknown")

messages = [{"role": "user", "content": "What is the temperature in New York?"}]

# Übergeben Sie Funktionen direkt als Tools in der Tool-Liste oder als JSON-Schema
response = chat(model="qwen3", messages=messages, tools=[get_temperature], think=True)

messages.append(response.message)
if response.message.tool_calls:
  # Nur für Modelle empfohlen, die nur einen einzelnen Tool-Aufruf zurückgeben
  call = response.message.tool_calls[0]
  result = get_temperature(**call.function.arguments)
  # Fügen Sie das Tool-Ergebnis zu den Nachrichten hinzu
  messages.append({"role": "tool", "tool_name": call.function.name, "content": str(result)})

  final_response = chat(model="qwen3", messages=messages, tools=[get_temperature], think=True)
  print(final_response.message.content)
```

JavaScript

Installieren Sie die Ollama JavaScript-Bibliothek:
```bash
# with npm
npm i ollama

# with bun
bun i ollama
```

```typescript
import ollama from 'ollama'

function getTemperature(city: string): string {
  const temperatures: Record<string, string> = {
    'New York': '22°C',
    'London': '15°C',
    'Tokyo': '18°C',
  }
  return temperatures[city] ?? 'Unknown'
}

const tools = [
  {
    type: 'function',
    function: {
      name: 'get_temperature',
      description: 'Get the current temperature for a city',
      parameters: {
        type: 'object',
        required: ['city'],
        properties: {
          city: { type: 'string', description: 'The name of the city' },
        },
      },
    },
  },
]

const messages = [{ role: 'user', content: "What is the temperature in New York?" }]

const response = await ollama.chat({
  model: 'qwen3',
  messages,
  tools,
  think: true,
})

messages.push(response.message)
if (response.message.tool_calls?.length) {
  // Nur für Modelle empfohlen, die nur einen einzelnen Tool-Aufruf zurückgeben
  const call = response.message.tool_calls[0]
  const args = call.function.arguments as { city: string }
  const result = getTemperature(args.city)
  // Fügen Sie das Tool-Ergebnis zu den Nachrichten hinzu
  messages.push({ role: 'tool', tool_name: call.function.name, content: result })

  // Generieren Sie die endgültige Antwort
  const finalResponse = await ollama.chat({ model: 'qwen3', messages, tools, think: true })
  console.log(finalResponse.message.content)
}
```

Paralleler Tool-Aufruf

cURL

Senden Sie mehrere Tool-Aufrufe parallel und senden Sie anschließend alle Tool-Antworten zurück an das Modell.

```shell
curl -s http://localhost:11434/api/chat -H "Content-Type: application/json" -d '{
  "model": "qwen3",
  "messages": [{"role": "user", "content": "What are the current weather conditions and temperature in New York and London?"}],
  "stream": false,
  "tools": [
    {
      "type": "function",
      "function": {
        "name": "get_temperature",
        "description": "Ruft die aktuelle Temperatur für eine Stadt ab",
        "parameters": {
          "type": "object",
          "required": ["city"],
          "properties": {
            "city": {"type": "string", "description": "Der Name der Stadt"}
          }
        }
      }
    },
    {
      "type": "function",
      "function": {
        "name": "get_conditions",
        "description": "Ruft die aktuellen Wetterbedingungen für eine Stadt ab",
        "parameters": {
          "type": "object",
          "required": ["city"],
          "properties": {
            "city": {"type": "string", "description": "Der Name der Stadt"}
          }
        }
      }
    }
  ]
}'
```

**Generieren Sie eine Antwort mit mehreren Tool-Ergebnissen**
```shell
curl -s http://localhost:11434/api/chat -H "Content-Type: application/json" -d '{
  "model": "qwen3",
  "messages": [
    {"role": "user", "content": "What are the current weather conditions and temperature in New York and London?"},
    {
      "role": "assistant",
      "tool_calls": [
        {
          "type": "function",
          "function": {
            "index": 0,
            "name": "get_temperature",
            "arguments": {"city": "New York"}
          }
        },
        {
          "type": "function",
          "function": {
            "index": 1,
            "name": "get_conditions",
            "arguments": {"city": "New York"}
          }
        },
        {
          "type": "function",
          "function": {
            "index": 2,
            "name": "get_temperature",
            "arguments": {"city": "London"}
          }
        },
        {
          "type": "function",
          "function": {
            "index": 3,
            "name": "get_conditions",
            "arguments": {"city": "London"}
          }
        }
      ]
    },
    {"role": "tool", "tool_name": "get_temperature", "content": "22°C"},
    {"role": "tool", "tool_name": "get_conditions", "content": "Partly cloudy"},
    {"role": "tool", "tool_name": "get_temperature", "content": "15°C"},
    {"role": "tool", "tool_name": "get_conditions", "content": "Rainy"}
  ],
  "stream": false
}'
```

Python

```python
from ollama import chat

def get_temperature(city: str) -> str:
  """Ruft die aktuelle Temperatur für eine Stadt ab

  Args:
    city: Der Name der Stadt

  Returns:
    Die aktuelle Temperatur der Stadt
  """
  temperatures = {
    "New York": "22°C",
    "London": "15°C",
    "Tokyo": "18°C"
  }
  return temperatures.get(city, "Unknown")

def get_conditions(city: str) -> str:
  """Ruft die aktuellen Wetterbedingungen für eine Stadt ab

  Args:
    city: Der Name der Stadt

  Returns:
    Die aktuellen Wetterbedingungen der Stadt
  """
  conditions = {
    "New York": "Partly cloudy",
    "London": "Rainy",
    "Tokyo": "Sunny"
  }
  return conditions.get(city, "Unknown")


messages = [{'role': 'user', 'content': 'What are the current weather conditions and temperature in New York and London?'}]

# Der Python-Client analysiert Funktionen automatisch als Tool-Schema, sodass wir sie direkt übergeben können
# Schemas können ebenfalls direkt in der Tool-Liste übergeben werden
response = chat(model='qwen3', messages=messages, tools=[get_temperature, get_conditions], think=True)

# Füge die Assistenten-Nachricht zu den Nachrichten hinzu
messages.append(response.message)
if response.message.tool_calls:
  # Verarbeite jeden Tool-Aufruf
  for call in response.message.tool_calls:
    # Führe den entsprechenden Tool aus
    if call.function.name == 'get_temperature':
      result = get_temperature(**call.function.arguments)
    elif call.function.name == 'get_conditions':
      result = get_conditions(**call.function.arguments)
    else:
      result = 'Unknown tool'
    # Füge das Tool-Ergebnis zu den Nachrichten hinzu
    messages.append({'role': 'tool',  'tool_name': call.function.name, 'content': str(result)})

  # Generiere die finale Antwort
  final_response = chat(model='qwen3', messages=messages, tools=[get_temperature, get_conditions], think=True)
  print(final_response.message.content)
```

JavaScript

```typescript
import ollama from 'ollama'

function getTemperature(city: string): string {
  const temperatures: { [key: string]: string } = {
    "New York": "22°C",
    "London": "15°C",
    "Tokyo": "18°C"
  }
  return temperatures[city] || "Unknown"
}

function getConditions(city: string): string {
  const conditions: { [key: string]: string } = {
    "New York": "Partly cloudy",
    "London": "Rainy",
    "Tokyo": "Sunny"
  }
  return conditions[city] || "Unknown"
}

const tools = [
  {
    type: 'function',
    function: {
      name: 'get_temperature',
      description: 'Ruft die aktuelle Temperatur für eine Stadt ab',
      parameters: {
        type: 'object',
        required: ['city'],
        properties: {
          city: { type: 'string', description: 'Der Name der Stadt' },
        },
      },
    },
  },
  {
    type: 'function',
    function: {
      name: 'get_conditions',
      description: 'Ruft die aktuellen Wetterbedingungen für eine Stadt ab',
      parameters: {
        type: 'object',
        required: ['city'],
        properties: {
          city: { type: 'string', description: 'Der Name der Stadt' },
        },
      },
    },
  }
]

const messages = [{ role: 'user', content: 'What are the current weather conditions and temperature in New York and London?' }]

const response = await ollama.chat({
  model: 'qwen3',
  messages,
  tools,
  think: true
})

// Füge die Assistenten-Nachricht zu den Nachrichten hinzu
messages.push(response.message)
if (response.message.tool_calls) {
  // Verarbeite jeden Tool-Aufruf
  for (const call of response.message.tool_calls) {
    // Führe den entsprechenden Tool aus
    let result: string
    if (call.function.name === 'get_temperature') {
      const args = call.function.arguments as { city: string }
      result = getTemperature(args.city)
    } else if (call.function.name === 'get_conditions') {
      const args = call.function.arguments as { city: string }
      result = getConditions(args.city)
    } else {
      result = 'Unknown tool'
    }
    // Füge das Tool-Ergebnis zu den Nachrichten hinzu
    messages.push({ role: 'tool', tool_name: call.function.name, content: result })
  }

  // Generiere die finale Antwort
  const finalResponse = await ollama.chat({ model: 'qwen3', messages, tools, think: true })
  console.log(finalResponse.message.content)
}
```

Multi-Turn-Tool-Aufruf (Agenten-Schleife)

Eine Agenten-Schleife ermöglicht es dem Modell, selbst zu entscheiden, wann es Tools aufrufen und deren Ergebnisse in seine Antworten einbinden soll. Es kann außerdem hilfreich sein, dem Modell mitzuteilen, dass es sich in einer Schleife befindet und mehrere Tool-Aufrufe durchführen kann.

Python

```python
from ollama import chat, ChatResponse


def add(a: int, b: int) -> int:
  """Addiert zwei Zahlen"""
  """
  Args:
    a: Die erste Zahl
    b: Die zweite Zahl

  Returns:
    Die Summe der beiden Zahlen
  """
  return a + b


def multiply(a: int, b: int) -> int:
  """Multipliziert zwei Zahlen"""
  """
  Args:
    a: Die erste Zahl
    b: Die zweite Zahl

  Returns:
    Das Produkt der beiden Zahlen
  """
  return a * b


available_functions = {
  'add': add,
  'multiply': multiply,
}

messages = [{'role': 'user', 'content': 'What is (11434+12341)*412?'}]
while True:
    response: ChatResponse = chat(
        model='qwen3',
        messages=messages,
        tools=[add, multiply],
        think=True,
    )
    messages.append(response.message)
    print("Thinking: ", response.message.thinking)
    print("Content: ", response.message.content)
    if response.message.tool_calls:
        for tc in response.message.tool_calls:
            if tc.function.name in available_functions:
                print(f"Calling {tc.function.name} with arguments {tc.function.arguments}")
                result = available_functions[tc.function.name](./**tc.function.arguments)
                print(f"Result: {result}")
                # Füge das Tool-Ergebnis zu den Nachrichten hinzu
                messages.append({'role': 'tool', 'tool_name': tc.function.name, 'content': str(result)})
    else:
        # Beende die Schleife, wenn keine weiteren Tool-Aufrufe mehr vorhanden sind
        break
  # Fahre die Schleife mit den aktualisierten Nachrichten fort
```

JavaScript

```typescript
import ollama from 'ollama'

type ToolName = 'add' | 'multiply'

function add(a: number, b: number): number {
  return a + b
}

function multiply(a: number, b: number): number {
  return a * b
}

const availableFunctions: Record&lt;ToolName, (a: number, b: number) =&gt; number&gt; = {
  add,
  multiply,
}

const tools = [
  {
    type: 'function',
    function: {
      name: 'add',
      description: 'Addiert zwei Zahlen',
      parameters: {
        type: 'object',
        required: ['a', 'b'],
        properties: {
          a: { type: 'integer', description: 'Die erste Zahl' },
          b: { type: 'integer', description: 'Die zweite Zahl' },
        },
      },
    },
  },
  {
    type: 'function',
    function: {
      name: 'multiply',
      description: 'Multipliziert zwei Zahlen',
      parameters: {
        type: 'object',
        required: ['a', 'b'],
        properties: {
          a: { type: 'integer', description: 'Die erste Zahl' },
          b: { type: 'integer', description: 'Die zweite Zahl' },
        },
      },
    },
  },
]

async function agentLoop() {
  const messages = [{ role: 'user', content: 'What is (11434+12341)*412?' }]

  while (true) {
    const response = await ollama.chat({
      model: 'qwen3',
      messages,
      tools,
      think: true,
    })

    messages.push(response.message)
    console.log('Thinking:', response.message.thinking)
    console.log('Content:', response.message.content)

    const toolCalls = response.message.tool_calls ?? []
    if (toolCalls.length) {
      for (const call of toolCalls) {
        const fn = availableFunctions[call.function.name as ToolName]
        if (!fn) {
          continue
        }

        const args = call.function.arguments as { a: number; b: number }
        console.log(`Calling ${call.function.name} with arguments`, args)
        const result = fn(args.a, args.b)
        console.log(`Result: ${result}`)
        messages.push({ role: 'tool', tool_name: call.function.name, content: String(result) })
      }
    } else {
      break
    }
  }
}

agentLoop().catch(console.error)
```

Tool-Aufruf mit Streaming

Beim Streaming sammelst du jedes Chunk von thinking, content und tool_calls und gibst diese Felder zusammen mit allen Tool-Ergebnissen in der Folgeanfrage zurück.

Python

python
from ollama import chat


def get_temperature(city: str) -> str:
  """Ruft die aktuelle Temperatur für eine Stadt ab

  Args:
    city: Der Name der Stadt

  Returns:
    Die aktuelle Temperatur für die Stadt
  """
  temperatures = {
    'New York': '22°C',
    'London': '15°C',
  }
  return temperatures.get(city, 'Unknown')


messages = [{'role': 'user', 'content': "What is the temperature in New York?"}]

while True:
  stream = chat(
    model='qwen3',
    messages=messages,
    tools=[get_temperature],
    stream=True,
    think=True,
  )

  thinking = ''
  content = ''
  tool_calls = []

  done_thinking = False
  # Sammle die partiellen Felder
  for chunk in stream:
    if chunk.message.thinking:
      thinking += chunk.message.thinking
      print(chunk.message.thinking, end='', flush=True)
    if chunk.message.content:
      if not done_thinking:
        done_thinking = True
        print('\n')
      content += chunk.message.content
      print(chunk.message.content, end='', flush=True)
    if chunk.message.tool_calls:
      tool_calls.extend(chunk.message.tool_calls)
      print(chunk.message.tool_calls)

  # Füge die gesammelten Felder zu den Nachrichten hinzu
  if thinking or content or tool_calls:
    messages.append({'role': 'assistant', 'thinking': thinking, 'content': content, 'tool_calls': tool_calls})

  if not tool_calls:
    break

  for call in tool_calls:
    if call.function.name == 'get_temperature':
      result = get_temperature(**call.function.arguments)
    else:
      result = 'Unknown tool'
    messages.append({'role': 'tool', 'tool_name': call.function.name, 'content': result})

JavaScript

typescript


function getTemperature(city: string): string {
  const temperatures: Record<string, string> = {
    'New York': '22°C',
    'London': '15°C',
  }
  return temperatures[city] ?? 'Unknown'
}

const getTemperatureTool = {
  type: 'function',
  function: {
    name: 'get_temperature',
    description: 'Get the current temperature for a city',
    parameters: {
      type: 'object',
      required: ['city'],
      properties: {
        city: { type: 'string', description: 'The name of the city' },
      },
    },
  },
}

async function agentLoop() {
  const messages = [{ role: 'user', content: "What is the temperature in New York?" }]

  while (true) {
    const stream = await ollama.chat({
      model: 'qwen3',
      messages,
      tools: [getTemperatureTool],
      stream: true,
      think: true,
    })

    let thinking = ''
    let content = ''
    const toolCalls: any[] = []
    let doneThinking = false

    for await (const chunk of stream) {
      if (chunk.message.thinking) {
        thinking += chunk.message.thinking
        process.stdout.write(chunk.message.thinking)
      }
      if (chunk.message.content) {
        if (!doneThinking) {
          doneThinking = true
          process.stdout.write('\n')
        }
        content += chunk.message.content
        process.stdout.write(chunk.message.content)
      }
      if (chunk.message.tool_calls?.length) {
        toolCalls.push(...chunk.message.tool_calls)
        console.log(chunk.message.tool_calls)
      }
    }

    if (thinking || content || toolCalls.length) {
      messages.push({ role: 'assistant', thinking, content, tool_calls: toolCalls } as any)
    }

    if (!toolCalls.length) {
      break
    }

    for (const call of toolCalls) {
      if (call.function.name === 'get_temperature') {
        const args = call.function.arguments as { city: string }
        const result = getTemperature(args.city)
        messages.push({ role: 'tool', tool_name: call.function.name, content: result } )
      } else {
        messages.push({ role: 'tool', tool_name: call.function.name, content: 'Unknown tool' } )
      }
    }
  }
}

agentLoop().catch(console.error)
    ```


Diese Schleife streamt die Antwort des Assistenten, sammelt partielle Felder, gibt sie zusammen zurück und fügt die Tool-Ergebnisse hinzu, damit das Modell seine Antwort vervollständigen kann.


## Verwenden von Funktionen als Tools mit dem Ollama Python SDK
Das Python SDK parst Funktionen automatisch als Tool-Schema, sodass wir sie direkt übergeben können.
Schemas können weiterhin bei Bedarf übergeben werden.

```python
from ollama import chat

def get_temperature(city: str) -> str:
  """Ruft die aktuelle Temperatur für eine Stadt ab

  Args:
    city: Der Name der Stadt

  Returns:
    Die aktuelle Temperatur für die Stadt
  """
  temperatures = {
    'New York': '22°C',
    'London': '15°C',
  }
  return temperatures.get(city, 'Unknown')

available_functions = {
  'get_temperature': get_temperature,
}
# Übergib die Funktion direkt als Teil der Tool-Liste
response = chat(model='qwen3', messages=messages, tools=available_functions.values(), think=True)