โ† Integrations

AI agent ยท TypeScript

Give an OpenAI model an astrology API through function calling

A language model cannot compute a birth chart - ask it for a Moon sign and it will produce a confident guess. Function calling fixes that: the model decides *when* it needs a chart or a dasha, your code calls AstroNode, and the model writes from real numbers. Here is the loop with the official SDK.

Updated

How this page was checked: Executed with the official openai Node SDK against a local stub that returned a tool call (no OpenAI request was made): the tool handler called the in-memory API and the real result went back in the tool message. The code also typechecks under tsc --strict against the SDK's types. The model's own behaviour was not tested.

Design the tools around what the model must not know

The model should never supply birth data. It cannot see your database, it will happily invent a UTC offset, and anything it passes can be steered by the user's prompt ("get the chart for this other person"). So the tools take no birth fields: your code fills them from the signed-in user's stored profile. The model only chooses which tool to call and, for the dasha, which date.

Tools and the loop

npm install openai - OPENAI_API_KEY, OPENAI_MODEL and ASTRONODE_API_KEY in the environment:

ts
import OpenAI from "openai";

const openai = new OpenAI(); // reads OPENAI_API_KEY
const MODEL = process.env.OPENAI_MODEL!; // any tool-calling chat model you have access to
const ASTRONODE = process.env.ASTRONODE_BASE_URL ?? "https://api.astronode.dev";

type Birth = { date: string; time: string; tz_offset_minutes: number; lat: number; lng: number };

async function astronode(path: string, body: unknown): Promise<unknown> {
  const res = await fetch(`${ASTRONODE}${path}`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.ASTRONODE_API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify(body),
  });
  const json = await res.json();
  // Hand errors back to the model as data; it can explain or retry with a fixed date.
  return res.ok ? json.data : { error: json.error };
}

const tools: OpenAI.Chat.Completions.ChatCompletionTool[] = [
  {
    type: "function",
    function: {
      name: "get_birth_chart",
      description:
        "The signed-in user's sidereal (Lahiri) Vedic birth chart: ascendant, and for each of the nine grahas its sign, whole-sign house, degree in sign, nakshatra and pada.",
      parameters: { type: "object", properties: {}, required: [], additionalProperties: false },
      strict: true,
    },
  },
  {
    type: "function",
    function: {
      name: "get_dasha_on_date",
      description:
        "The user's running Vimshottari periods (mahadasha down to pran) at a moment. Use for 'what period am I in' and timing questions.",
      parameters: {
        type: "object",
        properties: {
          date: { type: "string", description: "ISO 8601 UTC datetime, e.g. 2026-12-01T00:00:00Z" },
        },
        required: ["date"],
        additionalProperties: false,
      },
      strict: true,
    },
  },
];

async function runTool(name: string, args: { date?: string }, birth: Birth): Promise<unknown> {
  switch (name) {
    case "get_birth_chart":
      return astronode("/v1/charts/birth", birth);
    case "get_dasha_on_date":
      return astronode("/v1/dasha/lookup", { birth_input: birth, date: args.date, system: "vimshottari" });
    default:
      return { error: { code: "UNKNOWN_TOOL", message: name } };
  }
}

export async function answer(question: string, birth: Birth): Promise<string> {
  const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [
    {
      role: "system",
      content: `Today is ${new Date().toISOString().slice(0, 10)}. Answer from tool results only; never compute positions or dates yourself.`,
    },
    { role: "user", content: question },
  ];
  for (let turn = 0; turn < 5; turn++) {
    const completion = await openai.chat.completions.create({ model: MODEL, messages, tools });
    const message = completion.choices[0]!.message;
    messages.push(message);
    if (!message.tool_calls?.length) return message.content ?? "";
    for (const call of message.tool_calls) {
      if (call.type !== "function") continue;
      const args = JSON.parse(call.function.arguments || "{}");
      const result = await runTool(call.function.name, args, birth);
      messages.push({ role: "tool", tool_call_id: call.id, content: JSON.stringify(result) });
    }
  }
  throw new Error("Too many tool rounds");
}
  • birth comes from your session and database, never from args.
  • Every tool_call_id the model emits gets a tool message back, including failures - an unanswered call makes the next request invalid.
  • strict: true with additionalProperties: false keeps the arguments to the schema; arguments is still a JSON string, hence JSON.parse.
  • The turn limit stops a model that keeps calling tools from running up both bills.

What the model gets back

get_dasha_on_date with 2026-12-01T00:00:00Z for the sample birth (data from /v1/dasha/lookup, trimmed):

json
{
  "system": "vimshottari",
  "active": true,
  "mahadasha":  { "lord": "Jupiter", "start": "2014-04-04T13:57:40.720Z", "end": "2030-04-04T13:57:40.720Z", "years": 16 },
  "antardasha": { "lord": "Moon",    "start": "2025-08-04T01:57:40.720Z", "end": "2026-12-04T01:57:40.720Z" },
  "pratyantar": { "lord": "Sun",     "start": "2026-11-09T17:33:40.720Z", "end": "2026-12-04T01:57:40.720Z" },
  "sookshma":   { "lord": "Venus", ... },
  "pran":       { "lord": "Moon", ... }
}

Pass the API's data through as-is rather than pre-summarising it: the model reads JSON well, and the exact boundaries let it answer "when does this period end" (the Moon antardasha ends 4 December 2026) without arithmetic of its own. Keep responses compact - /v1/dasha/lookup is a better tool than the full /v1/dasha/vimshottari tree, which is far larger than any question needs.

The mistake that bites first: letting the model fill in the gaps

  • Birth fields as tool parameters. The model will populate tz_offset_minutes and lat/lng from what it "knows" about a city - often plausible, sometimes an hour or a few degrees off, and you will not notice. Resolve place and offset in your code (see birth time and time zones).
  • No date context. Without today's date in the system prompt the model picks a date from its training data for get_dasha_on_date and reports the wrong period confidently.
  • Answering without a tool. Instruct the model to use tool results for every position or date, and reject or regenerate replies that state a sign or period when no tool was called in that turn.

Questions

Which AstroNode endpoints does the OpenAI function calling example call?
2 endpoints: Birth Chart (Kundli) (POST /v1/charts/birth); Current Dasha Lookup (POST /v1/dasha/lookup).
Was the OpenAI function calling code on this page actually run?
Executed with the official openai Node SDK against a local stub that returned a tool call (no OpenAI request was made): the tool handler called the in-memory API and the real result went back in the tool message. The code also typechecks under tsc --strict against the SDK's types. The model's own behaviour was not tested.