> ## Documentation Index
> Fetch the complete documentation index at: https://docs.infercom.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Function Calling und JSON-Modus Funktionen implementieren - Entwicklerhandbuch

> Agentische Workflows mit Infercom Function Calling und JSON-Modus. Tools definieren, Funktionsaufrufe verarbeiten und strukturierte Ausgaben erhalten.

Function Calling ermöglicht dynamische Workflows, indem das Modell basierend auf Benutzereingaben Funktionsaufrufe auswählen und vorschlagen kann, was beim Aufbau von agentischen Workflows hilft. Durch die Definition einer Reihe von Funktionen oder Tools stellen Sie einen Kontext bereit, der es dem Modell ermöglicht, Funktionsargumente nach Bedarf zu empfehlen und auszufüllen.

## Wie Function Calling funktioniert

Function Calling ermöglicht adaptive Workflows, die Echtzeitdaten und strukturierte Ausgaben nutzen und so dynamischere und reaktionsfähigere Modellinteraktionen schaffen.

1. **Anfrage mit Tools senden:** Beginnen Sie, indem Sie eine Benutzeranfrage zusammen mit verfügbaren Tools senden, die im JSON-Schema definiert sind. Dieses Schema gibt Parameter für jede Funktion an.
2. **Das Modell verarbeitet und schlägt vor**: Das Modell interpretiert die Anfrage, bewertet die Absicht und entscheidet, ob es konversationell antworten oder Funktionsaufrufe vorschlagen wird. Wenn eine Funktion aufgerufen wird, füllt es die Argumente basierend auf dem Schema aus.
3. **Modellantwort erhalten:** Sie erhalten eine Antwort vom Modell, die einen Funktionsaufrufvorschlag enthalten kann. Führen Sie die Funktion mit den bereitgestellten Argumenten aus und geben Sie das Ergebnis zur weiteren Interaktion an das Modell zurück.

<Note>
  Nicht alle Modelle unterstützen Function Calling. Siehe [Infercom Inference Service Modelle](/de/models/infercomcloud-models) für die Liste der verfügbaren Modelle und deren Funktionen.
</Note>

<Tip>
  Bei Verwendung von `gpt-oss-120b` für Function Calling setzen Sie `reasoning_effort` auf `"high"` für beste Ergebnisse.
</Tip>

## Beispielverwendung

Die folgenden Beispiele beschreiben jeden Schritt der Verwendung von Function Calling mit einem End-to-End-Beispiel nach dem letzten Schritt.

### Schritt 1: Funktionsschema definieren

Definieren Sie ein JSON-Schema für Ihre Funktion. Sie müssen Folgendes angeben:

* Den Namen der Funktion.
* Eine Beschreibung dessen, was sie tut.
* Die Parameter, ihre Datentypen und Beschreibungen.

```json Example schema for getting the weather theme={null}
{
  "type": "function",
  "function": {
    "name": "get_weather",
    "description": "Gets the current weather information for a given city.",
    "parameters": {
      "type": "object",
      "properties": {
        "city": {
          "type": "string",
          "description": "Name of the city to get weather information for."
        }
      },
      "required": ["city"]
    }
  }
}
```

### Schritt 2: Function Calling in Ihrer Anfrage konfigurieren

Fügen Sie beim Senden einer Anfrage die Funktionsdefinition im Parameter `tools` ein und setzen Sie `tool_choice` auf einen der folgenden Werte:

* `auto` : Ermöglicht dem Modell, zwischen der Generierung einer Nachricht oder dem Aufrufen einer Funktion zu wählen. Dies ist die Standard-Tool-Auswahl, wenn das Feld nicht angegeben wird.
* `required` : Dies zwingt das Modell, einen Funktionsaufruf zu generieren. Das Modell wird dann immer eine oder mehrere Funktion(en) zum Aufrufen auswählen.
* Um einen bestimmten Funktionsaufruf zu erzwingen, setzen Sie `tool_choice = {"type": "function", "function": {"name": "get_weather"}}`. Dies stellt sicher, dass das Modell nur die angegebene Funktion verwendet.

<Note>
  Der folgende Codeblock zeigt eine gefälschte Wetterabfrage, die eine zufällige Temperatur zwischen 20°C und 50°C zurückgibt. Für genaue und Echtzeitwetterdaten verwenden Sie eine ordnungsgemäße Wetter-API.
</Note>

<CodeGroup>
  ```python Python (SambaNova) theme={null}
  import sambanova
  import random
  import json

  # Initialize the client with the SambaNova base URL and API key
  client = sambanova.SambaNova(
      base_url="https://api.infercom.ai/v1",
      api_key="ihr-infercom-api-schluessel"
  )

  MODEL = 'MiniMax-M2.5'

  def get_weather(city: str) -> dict:
      """
      Fake weather lookup: returns a random temperature between 20°C and 50°C.
      """
      temp = random.randint(20, 50)
      return {
          "city": city,
          "temperature_celsius": temp
      }

  tools = [
      {
          "type": "function",
          "function": {
              "name": "get_weather",
              "description": "Get weather of a location, the user should supply a location first",
              "parameters": {
                  "type": "object",
                  "properties": {
                      "city": {
                          "type": "string",
                          "description": "The city and state, e.g. San Francisco, CA",
                      }
                  },
                  "required": ["city"]
              },
          }
      },
  ]

  messages = [{"role": "user", "content": "What's the weather like in Paris today?"}]


  completion = client.chat.completions.create(
      model=MODEL,
      messages=messages,
      tools=tools
  )

  print(completion)
  ```

  ```python Python (OpenAI) theme={null}
  import openai
  import random
  import json

  # Initialize the client with the SambaNova base URL and API key
  client = openai.OpenAI(
      base_url="https://api.infercom.ai/v1",
      api_key="ihr-infercom-api-schluessel"
  )

  MODEL = 'MiniMax-M2.5'

  def get_weather(city: str) -> dict:
      """
      Fake weather lookup: returns a random temperature between 20°C and 50°C.
      """
      temp = random.randint(20, 50)
      return {
          "city": city,
          "temperature_celsius": temp
      }

  tools = [
      {
          "type": "function",
          "function": {
              "name": "get_weather",
              "description": "Get weather of a location, the user should supply a location first",
              "parameters": {
                  "type": "object",
                  "properties": {
                      "city": {
                          "type": "string",
                          "description": "The city and state, e.g. San Francisco, CA",
                      }
                  },
                  "required": ["city"]
              },
          }
      },
  ]

  messages = [{"role": "user", "content": "What's the weather like in Paris today?"}]


  completion = client.chat.completions.create(
      model=MODEL,
      messages=messages,
      tools=tools
  )

  print(completion)
  ```
</CodeGroup>

### Schritt 3: Tool-Aufrufe handhaben

Wenn das Modell sich entscheidet, eine Funktion aufzurufen, finden Sie `tool_calls` in der Antwort. Extrahieren Sie die Funktionsaufrufdetails und führen Sie die entsprechende Funktion mit den bereitgestellten Parametern aus.

```python Example code theme={null}
tool_call = completion.choices[0].message.tool_calls[0]
args = json.loads(tool_call.function.arguments)

result = get_weather(args["city"])
```

### Schritt 4: Funktionsergebnisse an das Modell zurückgeben

Sobald Sie das Ergebnis berechnet haben, geben Sie es an das Modell zurück, um die Konversation fortzusetzen oder die Ausgabe zu bestätigen.

```python Example code theme={null}
messages.append(completion.choices[0].message)  # append model's function call message
messages.append({                               # append result message
    "role": "tool",
    "tool_call_id": tool_call.id,
    "content": str(result)
})

completion_2 = client.chat.completions.create(
    model=MODEL,
    messages=messages,
 
)
print(completion_2.choices[0].message.content)
```

### Schritt 5: Beispielausgabe

Eine Beispielausgabe wird unten gezeigt.

```
The current weather in Paris is 25 degrees Celsius.
```

### End-to-End-Beispiel

<Note>
  Der folgende Codeblock zeigt eine gefälschte Wetterabfrage, die eine zufällige Temperatur zwischen 20°C und 50°C zurückgibt. Für genaue und Echtzeitwetterdaten verwenden Sie eine ordnungsgemäße Wetter-API.
</Note>

<CodeGroup>
  ```python Python (SambaNova) theme={null}
  import sambanova
  import random
  import json

  # Define the SambaNova client
  client = sambanova.SambaNova(
      base_url="https://api.infercom.ai/v1",
      api_key="ihr-infercom-api-schluessel"
  )

  MODEL = 'MiniMax-M2.5'

  def get_weather(city: str) -> dict: 
      """
      Fake weather lookup: returns a random temperature between 20°C and 50°C.
      """
      temp = random.randint(20, 50)
      return {
          "city": city,
          "temperature_celsius": temp
      }


  tools = [
      {
          "type": "function",
          "function": {
              "name": "get_weather",
              "description": "Get weather of a location, the user should supply a location first",
              "parameters": {
                  "type": "object",
                  "properties": {
                      "city": {
                          "type": "string",
                          "description": "The city and state, e.g. San Francisco, CA",
                      }
                  },
                  "required": ["city"]
              },
          }
      },
  ]

  messages = [{"role": "user", "content": "What's the weather like in Paris today?"}]


  completion = client.chat.completions.create(
      model=MODEL,
      messages=messages,
      tools=tools
  )

  print(completion)


  tool_call = completion.choices[0].message.tool_calls[0]
  args = json.loads(tool_call.function.arguments)

  result = get_weather(args["city"])


  messages.append({                               # append model's function call message
   "role": "assistant",
   "content": None,
   "tool_calls": [tool_call]
  })

  messages.append({                               # append result message
   "role": "tool",                           
   "tool_call_id": tool_call.id,
   "content": json.dumps(result)
  })

  completion_2 = client.chat.completions.create(
      model=MODEL,
      messages=messages,
   
  )
  print(completion_2.choices[0].message.content)
  ```

  ```python Python (OpenAI) theme={null}
  import openai
  import random
  import json

  # Define the OpenAI client
  client = openai.OpenAI(
      base_url="https://api.infercom.ai/v1",
      api_key="ihr-infercom-api-schluessel"
  )

  MODEL = 'MiniMax-M2.5'

  def get_weather(city: str) -> dict:
      """
      Fake weather lookup: returns a random temperature between 20°C and 50°C.
      """
      temp = random.randint(20, 50)
      return {
          "city": city,
          "temperature_celsius": temp
      }


  tools = [
      {
          "type": "function",
          "function": {
              "name": "get_weather",
              "description": "Get weather of a location, the user should supply a location first",
              "parameters": {
                  "type": "object",
                  "properties": {
                      "city": {
                          "type": "string",
                          "description": "The city and state, e.g. San Francisco, CA",
                      }
                  },
                  "required": ["city"]
              },
          }
      },
  ]

  messages = [{"role": "user", "content": "What's the weather like in Paris today?"}]


  completion = client.chat.completions.create(
      model=MODEL,
      messages=messages,
      tools=tools
  )

  print(completion)


  tool_call = completion.choices[0].message.tool_calls[0]
  args = json.loads(tool_call.function.arguments)

  result = get_weather(args["city"])


  messages.append({                               # append model's function call message
   "role": "assistant",
   "content": None,
   "tool_calls": [tool_call]
  })

  messages.append({                               # append result message
   "role": "tool",                           
   "tool_call_id": tool_call.id,
   "content": json.dumps(result)
  })

  completion_2 = client.chat.completions.create(
      model=MODEL,
      messages=messages,
   
  )
  print(completion_2.choices[0].message.content)
  ```
</CodeGroup>

## JSON-Schema

Sie können den Parameter `response_format` auf Ihr definiertes Schema setzen, um sicherzustellen, dass das Modell ein JSON-Objekt erzeugt, das Ihrer angegebenen Struktur entspricht.

<CodeGroup>
  ```python Python (SambaNova) theme={null}
  import sambanova
  import json

  # Define the SambaNova client
  client = sambanova.SambaNova(
      base_url="https://api.infercom.ai/v1",
      api_key="ihr-infercom-api-schluessel"
  )

  MODEL = "DeepSeek-V3.1"

  # Define the schema
  response_format = {
      "type": "json_schema",
      "json_schema": {
          "name": "data_extraction",
          "schema": {
              "type": "object",
              "properties": {
                  "section": {
                      "type": "string"
                  },
                  "products": {
                      "type": "array",
                      "items": {
                          "type": "string"
                      }
                  }
              },
              "required": ["section", "products"],
              "additionalProperties": False
          },
          "strict": False 
      }
  }

  # Call the API
  completion = client.chat.completions.create(
      model=MODEL,
      messages=[
          {
              "role": "system",
              "content": "You are an expert at structured data extraction. You will be given unstructured text and should convert it into the given structure."
          },
          {
              "role": "user",
              "content": "the section 24 has appliances, and videogames"
          }
      ],
      response_format=response_format
  )

  # Print the parsed result
  print(completion)
  ```

  ```python Python (OpenAI) theme={null}
  import openai
  import json

  # Define the OpenAI client
  client = openai.OpenAI(
      base_url="https://api.infercom.ai/v1",
      api_key="ihr-infercom-api-schluessel"
  )

  MODEL = "DeepSeek-V3.1"

  # Define the schema
  response_format = {
      "type": "json_schema",
      "json_schema": {
          "name": "data_extraction",
          "schema": {
              "type": "object",
              "properties": {
                  "section": {
                      "type": "string"
                  },
                  "products": {
                      "type": "array",
                      "items": {
                          "type": "string"
                      }
                  }
              },
              "required": ["section", "products"],
              "additionalProperties": False
          },
          "strict": False 
      }
  }

  # Call the API
  completion = client.chat.completions.create(
      model=MODEL,
      messages=[
          {
              "role": "system",
              "content": "You are an expert at structured data extraction. You will be given unstructured text and should convert it into the given structure."
          },
          {
              "role": "user",
              "content": "the section 24 has appliances, and videogames"
          }
      ],
      response_format=response_format
  )

  # Print the parsed result
  print(completion)
  ```
</CodeGroup>

<Note>
  Stellen Sie sicher, dass Sie den Parameter `"strict"` auf `false` setzen, da `true` noch nicht unterstützt wird. Wenn es verfügbar ist, wird es sicherstellen, dass das Modell Ihr Funktionsschema strikt befolgt, anstatt einen Best-Effort-Versuch zu unternehmen.
</Note>

## JSON-Modus

Sie können den Parameter `response_format` in Ihrer Anfrage auf `json_object` setzen, um sicherzustellen, dass das Modell ein gültiges JSON ausgibt. Falls der Modus kein gültiges JSON generieren kann, wird ein Fehler zurückgegeben.

<Note>
  Falls das Modell kein gültiges JSON generieren kann, erhalten Sie eine Fehlermeldung **Model did not output valid JSON**.
</Note>

<CodeGroup>
  ```json Python (SambaNova) theme={null}
  import sambanova

  # Define the SambaNova client
  client = sambanova.SambaNova(
      base_url="https://api.infercom.ai/v1",
      api_key="ihr-infercom-api-schluessel"
  )

  MODEL = 'MiniMax-M2.5'


  def run_conversation(user_prompt):
      # Initial conversation with user input
      messages = [
          {
              "role": "system",
              "content": "Always provide the response in this JSON format: {\"country\": \"name\", \"capital\": \"xx\"}"
          },

          {
              "role": "user",
              "content": user_prompt,
          }
      ]

      # First API call to get model's response
      response = client.chat.completions.create(
          model=MODEL,
          messages=messages,
          max_tokens=500,
          response_format = { "type": "json_object"},
          # stream = True
      )
      
      response_message = response.choices[0].message
      print(response_message)


  run_conversation('what is the capital of Austria')
  ```

  ```json Python (OpenAI) theme={null}
  import openai

  # Define the OpenAI client
  client = openai.OpenAI(
      base_url="https://api.infercom.ai/v1",
      api_key="ihr-infercom-api-schluessel"
  )

  MODEL = 'MiniMax-M2.5'


  def run_conversation(user_prompt):
      # Initial conversation with user input
      messages = [
          {
              "role": "system",
              "content": "Always provide the response in this JSON format: {\"country\": \"name\", \"capital\": \"xx\"}"
          },

          {
              "role": "user",
              "content": user_prompt,
          }
      ]

      # First API call to get model's response
      response = client.chat.completions.create(
          model=MODEL,
          messages=messages,
          max_tokens=500,
          response_format = { "type": "json_object"},
          # stream = True
      )
      
      response_message = response.choices[0].message
      print(response_message)


  run_conversation('what is the capital of Austria')
  ```
</CodeGroup>

```json Example response theme={null}
ChatCompletionMessage(content='{"country": "Austria", "capital": "Vienna"}', role='assistant', function_call=None, tool_calls=None)
```

### Andere Methoden für strukturierte Ausgaben

Neben dem JSON-Modus können strukturierte Ausgaben auch mithilfe der [Instructor-Bibliothek](https://python.useinstructor.com/) generiert werden, die einen praktischen Wrapper zum Extrahieren strukturierter Daten aus LLM-Antworten mittels Pydantic-Modellen bietet.
