Skip to main content

OpenAI Functions Integration

← Docs

Use Wikitopia with OpenAI's function calling for grounded AI responses.

Tool Definitions

import openai
import requests
import json

API_URL = "https://api.wikitopia.org"

tools = [
    {
        "type": "function",
        "function": {
            "name": "search_wikitopia",
            "description": "Search Wikitopia for verified facts about AI tools, models, frameworks, and companies.",
            "parameters": {
                "type": "object",
                "properties": {
                    "query": {
                        "type": "string",
                        "description": "Search query, e.g. 'open source vector databases'"
                    }
                },
                "required": ["query"]
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "get_entity",
            "description": "Get detailed profile of a specific AI entity by canonical name.",
            "parameters": {
                "type": "object",
                "properties": {
                    "name": {
                        "type": "string",
                        "description": "Entity name, e.g. 'LangChain', 'OpenAI', 'GPT-4'"
                    }
                },
                "required": ["name"]
            }
        }
    }
]

Tool Execution

def execute_tool(name: str, args: dict) -> str:
    if name == "search_wikitopia":
        res = requests.get(f"{API_URL}/v1/search",
            params={"q": args["query"], "mode": "hybrid", "limit": 5})
        results = res.json().get("results", [])
        return json.dumps([{
            "name": r["canonical_name"],
            "type": r["entity_type"],
            "description": r.get("description", "")[:150],
        } for r in results])

    elif name == "get_entity":
        res = requests.get(f"{API_URL}/v1/entities/{args['name']}")
        if res.status_code == 404:
            return json.dumps({"error": f"Entity '{args['name']}' not found"})
        e = res.json()
        return json.dumps({
            "name": e["canonical_name"],
            "type": e["entity_type"],
            "description": e.get("description"),
            "claims": e.get("claim_count", 0),
            "properties": {k: v for k, v in e.get("properties", {}).items() if v},
        })

    return json.dumps({"error": "Unknown tool"})

Full Conversation Loop

client = openai.OpenAI()

messages = [
    {"role": "system", "content":
        "You are an AI assistant with access to Wikitopia, a verified knowledge graph "
        "of AI tools, models, and companies. Always use the tools to look up facts "
        "before answering questions about specific entities."},
    {"role": "user", "content": "Compare Pinecone and Weaviate for a RAG pipeline"}
]

# Multi-turn tool-calling loop
for _ in range(5):  # max iterations
    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=messages,
        tools=tools,
    )
    msg = response.choices[0].message
    messages.append(msg)

    if not msg.tool_calls:
        print(msg.content)
        break

    for call in msg.tool_calls:
        result = execute_tool(call.function.name, json.loads(call.function.arguments))
        messages.append({
            "role": "tool",
            "tool_call_id": call.id,
            "content": result,
        })

TypeScript / Node.js

import OpenAI from "openai";

const client = new OpenAI();
const API_URL = "https://api.wikitopia.org";

const tools: OpenAI.Chat.ChatCompletionTool[] = [
  {
    type: "function",
    function: {
      name: "search_wikitopia",
      description: "Search for AI tools, models, and companies",
      parameters: {
        type: "object",
        properties: {
          query: { type: "string", description: "Search query" },
        },
        required: ["query"],
      },
    },
  },
];

async function handleToolCall(name: string, args: Record<string, string>) {
  if (name === "search_wikitopia") {
    const res = await fetch(
      `${API_URL}/v1/search?q=${encodeURIComponent(args.query)}&limit=5`
    );
    return await res.json();
  }
  return { error: "Unknown tool" };
}

See also