Agent skill

Openrouter Function Calling

by jeremylongshore in jeremylongshore/tons-of-skills-marketplace

Implement function/tool calling with OpenRouter models. An agent skill from jeremylongshore/tons-of-skills-marketplace.

MITAuto-check passedAI & LLM Engineering

Install Openrouter Function Calling

skills CLI
$ npx skills add jeremylongshore/tons-of-skills-marketplace --skill openrouter-function-calling -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install jeremylongshore/tons-of-skills-marketplace openrouter-function-calling --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/jeremylongshore/tons-of-skills-marketplace.git skills-src && mkdir -p .claude/skills && cp -r skills-src/skills/.curated/openrouter-function-calling .claude/skills/openrouter-function-calling && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
openrouter-function-calling
GitHub stars
2.8k
Token cost
~2.6k tokens
SKILL.md length
587 words
Files
10 (incl. references)
Skills in repo
3,342
Repo updated
First seen
Licence
MIT

At a glance

Implement function/tool calling with OpenRouter models. An agent skill from jeremylongshore/tons-of-skills-marketplace.

  • Works in 7 steps: Pick a model from the Model… → Define your tools as JSON Schema per… → Read… → …
  • Building agents
  • SKILL.md covers Overview, Prerequisites, Instructions and Basic Tool Calling, plus 9 more sections
  • Calls pip and npm; reaches openrouter.ai; needs OPENROUTER_API_KEY

What it does

Openrouter Function Calling is an agent skill from jeremylongshore/tons-of-skills-marketplace. Implement function/tool calling with OpenRouter models. Use when building agents, structured output, or tool-augmented LLM workflows. Triggers: 'openrouter function calling', 'openrouter tools', 'openrouter agent tools', 'tool use openrouter'.

Its SKILL.md is about 2.6k tokens, which your agent loads only when the skill is triggered. The skill folder holds 10 other files, including reference files (for example `references/advanced-tool-definitions.md`, `references/basic-function-calling.md` and `references/errors.md`). Compatibility notes: Designed for Claude Code

It sits in AI & LLM Engineering, covering Structured output and tool calling and Model routing and gateways. It works with OpenRouter and OpenAI. The repository describes itself as: Model-agnostic agent-skills platform with a harness-free canonical layer, verified adapters, and the ccpi package manager. Explore at tonsofskills.com. The licence is MIT.

When your agent uses it

  • Building agents
  • Structured output
  • Tool-augmented LLM workflows

Example prompts

  • “openrouter function calling”
  • “openrouter tools”
  • “openrouter agent tools”
  • “/openrouter-function-calling”

Requirements

  • Python 3
  • Node.js
  • A credential in OPENROUTER_API_KEY
  • Compatibility (from SKILL.md): Designed for Claude Code
  • Pre-approved tools (allowed-tools): Read, Write, Edit, Grep, Bash(python3:*), Bash(node:*)

Workflow steps

7 steps, taken from the first numbered list in SKILL.md.

  1. Pick a model from the Model Compatibility table that supports the features you need (tool calling, JSON mode, parallel tools).
  2. Define your tools as JSON Schema per Basic Tool Calling and send them with tool_choice="auto" (or "required" to force a call, or a…
  3. Read response.choices[0].message.tool_calls — each entry carries function.name and JSON-encoded function.arguments to parse with…
  4. For agents, wire the Multi-Turn Tool Loop: append the assistant message, execute each tool via execute_tool(), append role: "tool" results…
  5. Use the TypeScript Tool Calling section for the identical flow in Node — same schema, same tool_calls shape.
  6. When you only need structured data (no function execution), skip tools and use Structured Output (JSON Mode) with response_format={"type"…
  7. Handle failures per the Error Handling table: force tool_choice: "required" for extraction pipelines and validate arguments server-side…

What it can do on your machine

Read from SKILL.md and the folder at commit 80f86df. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves these tools, so the agent can use them without asking each time:

    • Read
    • Write
    • Edit
    • Grep
    • Bash(python3:*)
    • Bash(node:*)

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    Shell commands in SKILL.md call:

    • pip
    • npm

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    Hosts in commands or code, which the agent is likely to contact:

    • openrouter.ai

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names these keys or tokens, usually read from environment variables:

    • OPENROUTER_API_KEY

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

  • Compatibility

    Designed for Claude Code

    From compatibility in the SKILL.md frontmatter.

Context cost

Openrouter Function Calling loads about 2.6k tokens when it runs, and up to ~7k if it reads all its reference files. Until then it costs about 68 tokens; SKILL.md has 587 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~68
When it runs · the whole SKILL.md, loaded when a task matches
~2.6k
With references · SKILL.md plus every file in references/, read only if the agent opens them
~7k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from jeremylongshore/tons-of-skills-marketplace at commit 80f86df, republished under its MIT licence (© jeremylongshore). 587 words, ~2,650 tokens.

Download SKILL.mdSave it as .claude/skills/openrouter-function-calling/SKILL.md (or your agent's skills folder). This skill also uses 9 other files; get the full folder from GitHub.
name
openrouter-function-calling
description
Implement function/tool calling with OpenRouter models. Use when building agents, structured output, or tool-augmented LLM workflows. Triggers: 'openrouter function calling', 'openrouter tools', 'openrouter agent tools', 'tool use openrouter'.
allowed-tools
Read, Write, Edit, Grep, Bash(python3:*), Bash(node:*)
compatibility
Designed for Claude Code
version
1.20.0
license
MIT
author
Jeremy Longshore <jeremy@intentsolutions.io>
tags
saas, openrouter, function-calling, agents, tools

OpenRouter Function Calling

Overview

OpenRouter supports OpenAI-compatible tool/function calling across multiple providers. Define tools as JSON Schema, send them with your request, and the model returns structured tool_calls instead of free text. This works with GPT-4o, Claude 3.5, Gemini, and other tool-capable models via the same API. The key difference from direct provider APIs: OpenRouter normalizes the tool calling interface, so the same code works across providers.

Prerequisites

  • An OpenRouter API key (sk-or-v1-...) exported as OPENROUTER_API_KEY — see the openrouter-install-auth skill for setup
  • Python 3.8+ or Node.js 18+ with the OpenAI SDK (pip install openai / npm install openai)
  • A tool-capable model — check the Model Compatibility table below or query /api/v1/models (e.g., openai/gpt-4o, anthropic/claude-3.5-sonnet)
  • Real function implementations to dispatch tool calls to (the execute_tool() dispatcher below stubs get_weather and search_database)

Instructions

  1. Pick a model from the Model Compatibility table that supports the features you need (tool calling, JSON mode, parallel tools).
  2. Define your tools as JSON Schema per Basic Tool Calling and send them with tool_choice="auto" (or "required" to force a call, or a specific function name).
  3. Read response.choices[0].message.tool_calls — each entry carries function.name and JSON-encoded function.arguments to parse with json.loads().
  4. For agents, wire the Multi-Turn Tool Loop: append the assistant message, execute each tool via execute_tool(), append role: "tool" results keyed by tool_call_id, and loop until the model returns plain text (bounded by max_rounds).
  5. Use the TypeScript Tool Calling section for the identical flow in Node — same schema, same tool_calls shape.
  6. When you only need structured data (no function execution), skip tools and use Structured Output (JSON Mode) with response_format={"type": "json_object"}.
  7. Handle failures per the Error Handling table: force tool_choice: "required" for extraction pipelines and validate arguments server-side before executing.

Basic Tool Calling

python
import os, json
from openai import OpenAI

client = OpenAI(
    base_url="https://openrouter.ai/api/v1",
    api_key=os.environ["OPENROUTER_API_KEY"],
    default_headers={"HTTP-Referer": "https://my-app.com", "X-Title": "my-app"},
)

# Define tools with JSON Schema
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get current weather for a location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {"type": "string", "description": "City name"},
                    "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
                },
                "required": ["location"],
            },
        },
    },
    {
        "type": "function",
        "function": {
            "name": "search_database",
            "description": "Search the product database",
            "parameters": {
                "type": "object",
                "properties": {
                    "query": {"type": "string"},
                    "limit": {"type": "integer", "default": 10},
                },
                "required": ["query"],
            },
        },
    },
]

response = client.chat.completions.create(
    model="anthropic/claude-3.5-sonnet",  # Also works with openai/gpt-4o, etc.
    messages=[{"role": "user", "content": "What's the weather in Tokyo?"}],
    tools=tools,
    tool_choice="auto",  # "auto" | "required" | "none" | {"type":"function","function":{"name":"..."}}
    max_tokens=1024,
)

message = response.choices[0].message
if message.tool_calls:
    for tc in message.tool_calls:
        print(f"Function: {tc.function.name}")
        print(f"Args: {json.loads(tc.function.arguments)}")
        # → Function: get_weather
        # → Args: {"location": "Tokyo", "unit": "celsius"}

Multi-Turn Tool Loop

python
def tool_loop(user_prompt: str, tools: list, model: str = "openai/gpt-4o", max_rounds: int = 5):
    """Execute tool calls in a loop until the model returns a text response."""
    messages = [{"role": "user", "content": user_prompt}]

    for _ in range(max_rounds):
        response = client.chat.completions.create(
            model=model, messages=messages, tools=tools, max_tokens=1024,
        )
        msg = response.choices[0].message
        messages.append(msg)  # Add assistant message (with tool_calls)

        if not msg.tool_calls:
            return msg.content  # Final text response

        # Execute each tool call and feed results back
        for tc in msg.tool_calls:
            result = execute_tool(tc.function.name, json.loads(tc.function.arguments))
            messages.append({
                "role": "tool",
                "tool_call_id": tc.id,
                "content": json.dumps(result),
            })

    return "Max tool rounds exceeded"

def execute_tool(name: str, args: dict) -> dict:
    """Dispatch to actual function implementations."""
    TOOLS = {
        "get_weather": lambda **kw: {"temp": 22, "condition": "sunny", "location": kw["location"]},
        "search_database": lambda **kw: {"results": [f"Product matching '{kw['query']}'"], "count": 1},
    }
    fn = TOOLS.get(name)
    if not fn:
        return {"error": f"Unknown tool: {name}"}
    try:
        return fn(**args)
    except Exception as e:
        return {"error": str(e)}

# Usage
result = tool_loop("What's the weather in Tokyo and find me umbrella products?", tools)
print(result)

TypeScript Tool Calling

typescript
import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://openrouter.ai/api/v1",
  apiKey: process.env.OPENROUTER_API_KEY,
  defaultHeaders: { "HTTP-Referer": "https://my-app.com", "X-Title": "my-app" },
});

const tools: OpenAI.ChatCompletionTool[] = [
  {
    type: "function",
    function: {
      name: "calculate",
      description: "Evaluate a math expression",
      parameters: {
        type: "object",
        properties: { expression: { type: "string" } },
        required: ["expression"],
      },
    },
  },
];

const response = await client.chat.completions.create({
  model: "openai/gpt-4o",
  messages: [{ role: "user", content: "What is 42 * 17 + 3?" }],
  tools,
  tool_choice: "auto",
  max_tokens: 512,
});

const toolCalls = response.choices[0].message.tool_calls;
if (toolCalls) {
  for (const tc of toolCalls) {
    const args = JSON.parse(tc.function.arguments);
    console.log(`${tc.function.name}(${JSON.stringify(args)})`);
  }
}

Structured Output (JSON Mode)

python
# Force JSON output without tool calling (simpler for extraction tasks)
response = client.chat.completions.create(
    model="openai/gpt-4o",
    messages=[
        {"role": "system", "content": "Extract data as JSON with fields: name, email, company"},
        {"role": "user", "content": "Contact Jane Smith at jane@acme.co, she works at Acme Corp"},
    ],
    response_format={"type": "json_object"},
    max_tokens=200,
)
data = json.loads(response.choices[0].message.content)
# → {"name": "Jane Smith", "email": "jane@acme.co", "company": "Acme Corp"}

Model Compatibility

ModelTool CallingJSON ModeParallel Tools
openai/gpt-4oYesYesYes
openai/gpt-4o-miniYesYesYes
anthropic/claude-3.5-sonnetYesVia system promptSequential
google/gemini-2.0-flash-001YesYesYes
meta-llama/llama-3.1-70b-instructYes (varies)Via promptNo
Show full SKILL.md (256 more words)Show less

Output

The tool-calling flows produce:

  • message.tool_calls entries — each with a function.name and JSON-encoded function.arguments (e.g., get_weather with {"location": "Tokyo", "unit": "celsius"}) plus a tool_call_id for pairing results
  • The final assistant text once the Multi-Turn Tool Loop resolves — or the "Max tool rounds exceeded" sentinel if it hits max_rounds
  • From JSON Mode: a parseable JSON object matching your system-prompt schema (e.g., {"name": "Jane Smith", "email": "jane@acme.co", "company": "Acme Corp"})

Examples

Asking a weather question with the get_weather tool registered:

python
message = response.choices[0].message
for tc in message.tool_calls:
    print(tc.function.name, json.loads(tc.function.arguments))
# get_weather {'location': 'Tokyo', 'unit': 'celsius'}

Feed that result back as a role: "tool" message and the next completion returns prose ("It's currently 22°C and sunny in Tokyo..."). More worked examples: references/examples.md.

Error Handling

ErrorCauseFix
tool_calls is nullModel chose not to call toolsUse tool_choice: "required" to force tool use
JSON parse error on argumentsModel generated malformed JSONWrap in try/catch; retry or use more capable model
400 invalid tool schemaUnsupported JSON Schema typesStick to basic types (string, number, boolean, object, array)
Tool called with wrong argsSchema description unclearImprove parameter descriptions; add examples in description

Enterprise Considerations

  • Not all models support tool calling -- check model capabilities via /api/v1/models before sending tools
  • Use tool_choice: "required" when you must get a tool call (e.g., extraction pipelines)
  • Validate tool arguments server-side before executing -- models can hallucinate argument values
  • Set max_tokens to prevent expensive completion when model decides not to use tools
  • Use fallback chain with tool-capable models only (see openrouter-fallback-config)
  • Log tool call names and arguments for audit trails (redact sensitive args)

References

© jeremylongshore, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

SKILL.md and 9 other files (references) in skills/.curated/openrouter-function-calling of jeremylongshore/tons-of-skills-marketplace.

  • SKILL.md
  • references/advanced-tool-definitions.md
  • references/basic-function-calling.md
  • references/errors.md
  • references/examples.md
  • references/forced-tool-use.md
  • references/model-compatibility.md
  • references/parallel-tool-calls.md
  • references/streaming-with-tools.md
  • references/tool-router.md

Open the folder on GitHubat commit 80f86df

Compare with similar skills

Openrouter Function Calling next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Openrouter Function Calling compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Openrouter Function Calling this skilljeremylongshore/tons-of-skills-marketplace2.8k—~2.6kAutomated safety check: PassMIT
Embeddings via 9Routerdecolua/9router30k—~604Automated safety check: PassMIT
Using Ccproxy Inspectorstarbaser/ccproxy350—~2.7kAutomated safety check: PassCustom licence
Mecatl Model Router Configstacklok/mecatl250—~2.7kAutomated safety check: PassApache-2.0
Using Ccproxy APIstarbaser/ccproxy350—~4kAutomated safety check: PassCustom licence
Configuring Visionoxbshw/watch-skill469—~509Automated safety check: NotesMIT

Similar skills

  • Embeddings via 9Router

    decolua/9router

    Generates vector embeddings through the 9Router /v1/embeddings endpoint, using models from providers such as OpenAI, Gemini, Mistral and Voyage for RAG and semantic search.

    30k GitHub stars~604 tokensUpdated today
    AI & LLM EngineeringAuto-check passed
  • Using Ccproxy Inspector

    starbaser/ccproxy

    Operates the ccproxy inspector MITM system for intercepting, inspecting, and transforming LLM API traffic.

    350 GitHub stars~2.7k tokensUpdated 2 mo ago
    AI & LLM EngineeringAuto-check passed
  • Interviews you about provider, cost, openness and image needs, then designs the models section of a mecatl settings file with aliases, slots and router categories.

    250 GitHub stars~2.7k tokensUpdated today
    AI & LLM EngineeringAuto-check passed
  • Using Ccproxy API

    starbaser/ccproxy

    Guides users through ccproxy as an OpenAI-compatible and Anthropic-compatible LLM API server with SDK integration, OAuth authentication, sentinel key substitution, model routing, and troubleshooting.

    350 GitHub stars~4k tokensUpdated 2 mo ago
    AI & LLM EngineeringAuto-check passed
  • Configuring Vision

    oxbshw/watch-skill

    The user wants to connect an LLM or vision provider, already has an API key, asks "can I use OpenAI/Anthropic/Gemini/OpenRouter", wants local Ollama, or needs different cheap and strong models.

    469 GitHub stars~509 tokensUpdated 24 days ago
    AI & LLM EngineeringAuto-check: notes
  • Quorum

    Detrol/quorum-cli

    Run a structured debate between agent CLIs (claude, codex, agy, grok) and the user's configured API or local models (OpenAI, Anthropic, Google, xAI, OpenRouter, Ollama and more) through the Quorum…

    119 GitHub stars~807 tokensUpdated 12 days ago
    AI & LLM EngineeringAuto-check: notes

More from jeremylongshore/tons-of-skills-marketplace

All 3,342 skills in this repo
  • Performing Security Code Review

    jeremylongshore/tons-of-skills-marketplace

    Execute this skill enables AI assistant to conduct a security-focused code review using the security-agent plugin.

    2.8k GitHub starsUsed in 2 repos~1.3k tokens
    Auto-check: notes
  • Adapting Transfer Learning Models

    jeremylongshore/tons-of-skills-marketplace

    Build this skill automates the adaptation of pre-trained machine learning models using transfer learning techniques.

    2.8k GitHub stars~1.1k tokensUpdated today
    Auto-check passed
  • Agent Context Loader

    jeremylongshore/tons-of-skills-marketplace

    Execute proactive auto-loading: automatically detects and loads agents.md files.

    2.8k GitHub stars~1.1k tokensUpdated today
    Auto-check passed
  • Aggregating Performance Metrics

    jeremylongshore/tons-of-skills-marketplace

    Aggregate and centralize performance metrics from applications, systems, databases, caches, and services.

    2.8k GitHub stars~1.2k tokensUpdated today
    Auto-check passed
  • Analyzing Capacity Planning

    jeremylongshore/tons-of-skills-marketplace

    Execute this skill enables AI assistant to analyze capacity requirements and plan for future growth.

    2.8k GitHub stars~947 tokensUpdated today
    Auto-check passed
  • Analyzing Database Indexes

    jeremylongshore/tons-of-skills-marketplace

    Process use when you need to work with database indexing. An agent skill from jeremylongshore/tons-of-skills-marketplace.

    2.8k GitHub stars~2k tokensUpdated today
    Auto-check passed

Questions about Openrouter Function Calling

What does Openrouter Function Calling do?

Implement function/tool calling with OpenRouter models. An agent skill from jeremylongshore/tons-of-skills-marketplace. Openrouter Function Calling is an agent skill from jeremylongshore/tons-of-skills-marketplace. Implement function/tool calling with OpenRouter models.

When should I use Openrouter Function Calling?

Openrouter Function Calling fits situations like: building agents; structured output; tool-augmented LLM workflows.

How do I install Openrouter Function Calling in Claude Code?

Run `npx skills add jeremylongshore/tons-of-skills-marketplace --skill openrouter-function-calling -a claude-code`. Or copy the skill folder (skills/.curated/openrouter-function-calling in jeremylongshore/tons-of-skills-marketplace) into .claude/skills/openrouter-function-calling in your project. Claude Code loads it when a task matches its description.

How do I install Openrouter Function Calling in Codex?

Run `npx skills add jeremylongshore/tons-of-skills-marketplace --skill openrouter-function-calling -a codex`. Or copy the skill folder (skills/.curated/openrouter-function-calling in jeremylongshore/tons-of-skills-marketplace) into .agents/skills/openrouter-function-calling in your project. Codex loads it when a task matches its description.

Can I use Openrouter Function Calling in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add jeremylongshore/tons-of-skills-marketplace --skill openrouter-function-calling -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/openrouter-function-calling, .gemini/skills/openrouter-function-calling, .github/skills/openrouter-function-calling and .opencode/skills/openrouter-function-calling in your project.

What does Openrouter Function Calling need to run?

Going by SKILL.md and its folder, Openrouter Function Calling needs the command-line tools its instructions call (pip and npm) and credentials named OPENROUTER_API_KEY. Our summary lists: Python 3; Node.js; A credential in OPENROUTER_API_KEY. Its frontmatter pre-approves these tools: Read, Write, Edit, Grep, Bash(python3:*), Bash(node:*). Compatibility (from SKILL.md): Designed for Claude Code.

Does Openrouter Function Calling access the network?

SKILL.md names 1 domain. In commands or code: openrouter.ai; the agent is likely to contact it when it follows the instructions. This is read from the text; nothing was executed.

Is Openrouter Function Calling safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Openrouter Function Calling use?

Openrouter Function Calling is published under the MIT licence (declared in SKILL.md). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Openrouter Function Calling use?

About 2.6k tokens (SKILL.md is roughly 11k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full. Its references folder adds about 4.4k tokens, read only when the agent opens those files.

What are the alternatives to Openrouter Function Calling?

Skills that share tags, products or a category with Openrouter Function Calling: Embeddings via 9Router (decolua/9router, 30k stars), Using Ccproxy Inspector (starbaser/ccproxy, 350 stars), Mecatl Model Router Config (stacklok/mecatl, 250 stars) and Using Ccproxy API (starbaser/ccproxy, 350 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Openrouter Function Calling?

jeremylongshore (a GitHub user) maintains it in jeremylongshore/tons-of-skills-marketplace, which has 2,825 GitHub stars. The repository holds 3,342 skills in this directory. The repository was last updated on October 9, 2026.

Source: jeremylongshore/tons-of-skills-marketplace on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.