Funktionen
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
Abschnitt betitelt „Wie Function Calling funktioniert“Function Calling ermöglicht adaptive Workflows, die Echtzeitdaten und strukturierte Ausgaben nutzen und so dynamischere und reaktionsfähigere Modellinteraktionen schaffen.
- 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.
- 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.
- 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.
Modellunterstützung
Abschnitt betitelt „Modellunterstützung“Function Calling wird von den unten aufgeführten Modellen unterstützt. Prüfen Sie stets Unterstützte Modelle auf die aktuelle Verfügbarkeit.
| Modell-ID | Region | Tools | Erzwungenes tool_choice |
response_format |
Tools mit Bild |
|---|---|---|---|---|---|
MiniMax-M2.7 |
EU | Ja | Ja | Ja | Nicht zutreffend - nur Text |
gpt-oss-120b |
EU | Ja | Ja | Ja | Nicht zutreffend - nur Text |
gemma-4-31B-it |
EU | Ja | Siehe Warnung unten | Ja | Ja |
DeepSeek-V3.1 |
Nicht-EU | Ja | Ja | Ja | Nicht zutreffend - nur Text |
DeepSeek-V3.2 |
Nicht-EU | Ja | Ja | Ja | Nicht zutreffend - nur Text |
Meta-Llama-3.3-70B-Instruct |
Nicht-EU | Ja | Ja | Ja | Nicht zutreffend - nur Text |
Vision-Anfragen unterstützen dieselben Optionen tools, tool_choice und response_format wie reine Textanfragen. Die Einschränkung wird während der Generierung angewendet. Siehe Vision.
Beispielverwendung
Abschnitt betitelt „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
Abschnitt betitelt „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.
{ "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
Abschnitt betitelt „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.
import sambanovaimport randomimport json
# Initialize the client with the SambaNova base URL and API keyclient = sambanova.SambaNova( base_url="https://api.infercom.ai/v1", api_key="ihr-infercom-api-schluessel")
MODEL = 'MiniMax-M2.7'
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)import openaiimport randomimport json
# Initialize the client with the SambaNova base URL and API keyclient = openai.OpenAI( base_url="https://api.infercom.ai/v1", api_key="ihr-infercom-api-schluessel")
MODEL = 'MiniMax-M2.7'
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)Schritt 3: Tool-Aufrufe handhaben
Abschnitt betitelt „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.
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
Abschnitt betitelt „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.
messages.append(completion.choices[0].message) # append model's function call messagemessages.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
Abschnitt betitelt „Schritt 5: Beispielausgabe“Eine Beispielausgabe wird unten gezeigt.
The current weather in Paris is 25 degrees Celsius.End-to-End-Beispiel
Abschnitt betitelt „End-to-End-Beispiel“import sambanovaimport randomimport json
# Define the SambaNova clientclient = sambanova.SambaNova( base_url="https://api.infercom.ai/v1", api_key="ihr-infercom-api-schluessel")
MODEL = 'MiniMax-M2.7'
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)import openaiimport randomimport json
# Define the OpenAI clientclient = openai.OpenAI( base_url="https://api.infercom.ai/v1", api_key="ihr-infercom-api-schluessel")
MODEL = 'MiniMax-M2.7'
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)Tool-Aufrufe streamen
Abschnitt betitelt „Tool-Aufrufe streamen“Setzen Sie stream: true, um Tool-Aufrufe während der Generierung zu erhalten. Die Argumente treffen im Feld tool_calls des Deltas ein. In delta.content erscheint kein Reasoning-Gerüst.
JSON-Schema
Abschnitt betitelt „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.
import sambanovaimport json
# Define the SambaNova clientclient = sambanova.SambaNova( base_url="https://api.infercom.ai/v1", api_key="ihr-infercom-api-schluessel")
MODEL = "DeepSeek-V3.1"
# Define the schemaresponse_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 APIcompletion = 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 resultprint(completion)import openaiimport json
# Define the OpenAI clientclient = openai.OpenAI( base_url="https://api.infercom.ai/v1", api_key="ihr-infercom-api-schluessel")
MODEL = "DeepSeek-V3.1"
# Define the schemaresponse_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 APIcompletion = 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 resultprint(completion)JSON-Modus
Abschnitt betitelt „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.
import sambanova
# Define the SambaNova clientclient = sambanova.SambaNova( base_url="https://api.infercom.ai/v1", api_key="ihr-infercom-api-schluessel")
MODEL = 'MiniMax-M2.7'
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')import openai
# Define the OpenAI clientclient = openai.OpenAI( base_url="https://api.infercom.ai/v1", api_key="ihr-infercom-api-schluessel")
MODEL = 'MiniMax-M2.7'
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')ChatCompletionMessage(content='{"country": "Austria", "capital": "Vienna"}', role='assistant', function_call=None, tool_calls=None)Andere Methoden für strukturierte Ausgaben
Abschnitt betitelt „Andere Methoden für strukturierte Ausgaben“Neben dem JSON-Modus können strukturierte Ausgaben auch mithilfe der Instructor-Bibliothek generiert werden, die einen praktischen Wrapper zum Extrahieren strukturierter Daten aus LLM-Antworten mittels Pydantic-Modellen bietet.