Skip to main content
Back to All Articles
AI & LLMs8 min read

How to Use BaZi API with OpenAI Function Calling

M
Md. Nasir Uddin
Founder & Lead Engineer
2026-09-14

Large Language Models (LLMs) like GPT-4o excel at creative narrative, psychological synthesis, and empathetic communication. However, they struggle with astronomical math, lunar calendar synchronization, and complex rule-based combinatorial matrices. If you ask ChatGPT to calculate a BaZi chart directly, it will frequently generate hallucinated pillars. This tutorial demonstrates how to pair OpenAI Function Calling with BaZi API to achieve 100% mathematical accuracy with rich AI storytelling.

The Grounding Pattern for AI Calendrical Agents

The architectural solution is Tool Calling (Function Calling). Instead of asking the model to perform calendar arithmetic, we configure the model with a tool called 'calculate_bazi_chart'. When the user shares their birth details, the model extracts the parameters, calls our API, receives verified JSON, and then uses its linguistic intelligence to interpret the chart.

Defining the Function Tool Schema

We supply OpenAI with a standardized JSON Schema describing the input arguments required by the BaZi API:

OpenAI Function Calling Tool Schema
const baziTool = {
  type: "function",
  function: {
    name: "calculate_bazi_chart",
    description: "Calculates the Four Pillars, Day Master, and Ten Gods for a user's birth data.",
    parameters: {
      type: "object",
      properties: {
        birthDate: { type: "string", description: "YYYY-MM-DD" },
        birthTime: { type: "string", description: "HH:mm in 24-hour format" },
        gender: { type: "string", enum: ["male", "female"] },
        timezone: { type: "string", description: "IANA timezone string" }
      },
      required: ["birthDate", "birthTime", "gender"]
    }
  }
};

Handling the Tool Call in Node.js / Next.js

When the OpenAI API responds with a tool call request, our backend queries the BaZi API and passes the raw JSON data back into the conversation context:

Executing the Tool Call and Forwarding to Model
// 1. Initial user message
const chat = await openai.chat.completions.create({
  model: "gpt-4o",
  messages: [{ role: "user", content: "Analyze my chart: born 1988-08-08 at 08:08 in Singapore, male." }],
  tools: [baziTool]
});

// 2. Intercept function call
const toolCall = chat.choices[0].message.tool_calls?.[0];
if (toolCall && toolCall.function.name === "calculate_bazi_chart") {
  const args = JSON.parse(toolCall.function.arguments);
  
  // 3. Fetch ground truth from BaZi API
  const response = await fetch("https://api.baziapi.pro/api/v1/bazi/calculate", {
    method: "POST",
    headers: { "Content-Type": "application/json", "x-api-key": process.env.BAZI_API_KEY! },
    body: JSON.stringify(args)
  });
  const chartData = await response.json();

  // 4. Return chart data to model for final interpretation
  const finalAnalysis = await openai.chat.completions.create({
    model: "gpt-4o",
    messages: [
      { role: "user", content: "Analyze my chart: born 1988-08-08 at 08:08 in Singapore, male." },
      chat.choices[0].message,
      { role: "tool", tool_call_id: toolCall.id, content: JSON.stringify(chartData) }
    ]
  });
  console.log(finalAnalysis.choices[0].message.content);
}

Best Practices for System Prompts

To ensure the AI interpretation remains grounded, specify clear system guidelines: (1) Instruct the model to strictly cite the provided Day Master and Ten Gods returned in the JSON payload, (2) Forbid the model from inventing non-existent element scores, and (3) Encourage constructive, growth-oriented psychological language rather than fatalistic predictions.

Conclusion & Key Takeaways

Combining the computational accuracy of BaZi API with the natural language fluency of OpenAI enables developers to build next-generation cultural and calendrical platforms that users can trust.

#OpenAI#Function Calling#LLM Agents#GPT-4o#LangChain

Build with the BaZi API Engine Today

Instant API keys, sub-500ms responses, and complete Four Pillars calculation data.