Skip to Content

Generate and stream text

Call Foundry-hosted language models with generateText and streamText from @osdk/aip-core, in Node.js or the browser.

Foundry docsSupported LLMs

@osdk/aip-core sends chat completions to the Foundry Language Model Service (LMS) with the same auth, governance, and usage tracking as the rest of your OSDK app. Use generateText for a complete answer and streamText to render tokens as they arrive.

@osdk/aip-core is at version 0.x, and its API can change in any minor release. The current release runs one model call per request: there is no built-in multi-step tool loop, no structured (JSON) output, and only text content parts are sent. Image and file parts are dropped with a warning.

Install

npm install @osdk/aip-core @osdk/client @osdk/oauth

@osdk/client is a peer dependency. @osdk/aip-core brings in @osdk/language-models itself.

Create a model

Every call takes a model handle from foundryModel. It needs a PlatformClient from createPlatformClient and the model's LMS API name.

src/model.ts
import { foundryModel } from "@osdk/aip-core";
import { createPlatformClient } from "@osdk/client";
import { createPublicOauthClient } from "@osdk/oauth";

const foundryUrl = "https://example.palantirfoundry.com";

export const auth = createPublicOauthClient(
  "<your-client-id>",
  foundryUrl,
  "http://localhost:8080/auth/callback",
  {
    scopes: [
      "api:read-data",
      "api:write-data",
      "api:use-ontologies-read",
      "api:use-ontologies-write",
      "api:use-language-models-execute",
    ],
  },
);

export const platformClient = createPlatformClient(foundryUrl, auth);

export const model = foundryModel({ client: platformClient, model: "gpt-4o" });

Pass a client from createPlatformClient, not the Client from createClient: foundryModel uses the client's baseUrl and authenticated fetch, and an Ontology Client does not expose them. Reuse the same token provider for both clients so the user signs in once.

OAuth applications must request the api:use-language-models-execute scope. The default scopes of createPublicOauthClient do not include it, so list every scope your app needs. See Authentication for the other token providers.

Model identifiers

model accepts an API name string or a ModelIdentifier:

ValueExampleUse it for
string"gpt-4o"A built-in LMS model, by API name. Shorthand for { type: "lmsModel", apiName }.
{ type: "lmsModel", apiName }{ type: "lmsModel", apiName: "gpt-4o" }The same, spelled out.
{ type: "registeredModel", registeredModelRid }{ type: "registeredModel", registeredModelRid: "ri.language-model-service..." }A model your organization registered in Foundry.

Which models you can call depends on your enrollment. Look up API names in Model Catalog in Foundry. The handle's modelId is foundry/<apiName or rid>, useful for logging.

Generate text

generateText sends one request and resolves with the full response.

src/summarize.ts
import { generateText } from "@osdk/aip-core";
import { model } from "./model";

const result = await generateText({
  model,
  system: "Answer in one sentence.",
  prompt: "What does an Ontology action type do?",
  temperature: 0,
  maxOutputTokens: 200,
});

console.log(result.text);
console.log(result.finishReason, result.usage.totalTokens);

Prompts, messages, and system instructions

Give the conversation as either prompt or messages. Passing both throws. At least one of system, prompt, or messages is required.

OptionTypeDescription
promptstring | Array<ModelMessage>A string becomes one user message.
messagesArray<ModelMessage>The full conversation history.
systemstring | SystemModelMessage | Array<SystemModelMessage>Instructions prepended before the conversation. An empty string is ignored.

A ModelMessage is one of:

rolecontent
"system"string
"user"string, or an array of { type: "text", text } parts. Image and file parts are accepted by the type but dropped.
"assistant"string, or an array of text and tool-call parts.
"tool"An array of tool-result parts. See Tool calling.

To hold a multi-turn conversation, keep the history and append each answer before the next question:

src/conversation.ts
import { generateText, type ModelMessage } from "@osdk/aip-core";
import { model } from "./model";

const messages: Array<ModelMessage> = [];

export async function ask(question: string): Promise<string> {
  messages.push({ role: "user", content: question });
  const result = await generateText({
    model,
    system: "You help employees find internal information.",
    messages,
  });
  messages.push({ role: "assistant", content: result.text });
  return result.text;
}

Stream text

streamText returns immediately and starts the request. Read tokens from textStream, or every event from fullStream. The other fields are promises that resolve when the stream ends.

src/stream.ts
import { streamText } from "@osdk/aip-core";
import { model } from "./model";

const result = streamText({
  model,
  prompt: "Write a short welcome note for a new engineer.",
});

for await (const delta of result.textStream) {
  process.stdout.write(delta);
}

console.log("\n", await result.usage);

Stream result

FieldTypeDescription
textStreamReadableStream<string>Text deltas only.
fullStreamReadableStream<TextStreamChunk>Every event, listed below.
textPromise<string>The full answer.
reasoningTextPromise<string | undefined>Reasoning text, for models that return it.
toolCallsPromise<Array<ToolCall>>Tool calls requested by the model.
finishReasonPromise<FinishReason>Why generation stopped.
usage, totalUsagePromise<LanguageModelUsage>Token counts. Identical while each call is a single step.
warningsPromise<Array<Warning> | undefined>Ignored inputs. Resolves even when the stream fails.
request, responsePromise<RequestMetadata | undefined>, Promise<ResponseMetadata | undefined>The request body sent, and the response id, model, timestamp, and assistant message.

fullStream emits these TextStreamChunk events:

typeFieldsWhen
"text-delta"id, deltaEach piece of answer text.
"reasoning-delta"id, deltaEach piece of reasoning text.
"tool-call"toolCallId, toolName, inputOnce per tool call, after the model finishes, with input parsed from JSON.
"finish"finishReason, rawFinishReason, usageOnce, at the end.
"error"errorThe request or stream failed. The stream then errors with the same Error.

streamText also takes onChunk, onError, and onFinish callbacks. onFinish receives finishReason, text, reasoningText, toolCalls, usage, totalUsage, warnings, request, and response.

Sampling options

generateText and streamText share these options:

OptionTypeDescription
maxOutputTokensnumberMaximum tokens to generate.
temperaturenumberRandomness. 0 is the most deterministic.
topPnumberNucleus sampling threshold.
presencePenaltynumberPenalizes tokens that have appeared at all.
frequencyPenaltynumberPenalizes tokens by how often they have appeared.
stopSequencesArray<string>Stops generation at any of these strings.
seednumberSeed for repeatable sampling, where the model supports it.
headersRecord<string, string | undefined>Extra HTTP headers on the request.
abortSignalAbortSignalCancels the request.

Models differ in which options they honor. The LMS proxy does not accept topK, so there is no such option.

Cancel a request

Pass an AbortSignal. generateText rejects, and streamText errors its streams and rejects its promises. textStream and fullStream share one source, so cancelling one of them does not abort the request; it is aborted only when both are cancelled.

src/cancel.ts
import { streamText } from "@osdk/aip-core";
import { model } from "./model";

const controller = new AbortController();
const result = streamText({
  model,
  prompt: "Write a long report on office utilization.",
  abortSignal: controller.signal,
});

setTimeout(() => controller.abort(), 5_000);

try {
  console.log(await result.text);
} catch (error) {
  if (controller.signal.aborted) {
    console.log("Stopped by the user");
  } else {
    throw error;
  }
}

Check signal.aborted rather than error.name: the client's fetch wraps the abort in its own error type.

Usage and finish reason

generateText resolves with a GenerateTextResult:

FieldTypeDescription
textstringThe answer text.
reasoningTextstring | undefinedReasoning text, for models that return it.
contentArray<ContentPart>Text, reasoning, and tool-call parts in order.
toolCallsArray<ToolCall>Tool calls requested by the model.
toolResultsArray<ToolResult>Always empty: tools are not executed for you.
finishReasonFinishReasonNormalized stop reason.
rawFinishReasonstring | undefinedThe provider's own value, such as "tool_calls".
usageLanguageModelUsageToken counts for this call.
totalUsageLanguageModelUsageSame as usage.
stepsArray<StepResult>One entry per model call. Always one.
warningsArray<Warning> | undefinedInputs that were ignored.
request, responseRequestMetadata, ResponseMetadataThe request body, plus response id, modelId, timestamp, body, and messages.

FinishReason is one of "stop", "length" (hit maxOutputTokens), "tool-calls", "content-filter", "error", or "other".

LanguageModelUsage has inputTokens, outputTokens, and totalTokens, each number | undefined, plus optional reasoningTokens and cachedInputTokens. Fields are undefined when the model does not report usage.

generateText also accepts onStepFinish(step) and onFinish(event), where event adds steps and totalUsage to the step result.

Errors and warnings

Failed requests reject with PalantirApiError from @osdk/client, which carries statusCode, errorName, and message. A 403 usually means the token lacks api:use-language-models-execute or your user cannot use the model.

Unsupported input does not throw. It is skipped and reported in warnings:

InputBehavior
Image or file parts in a user messageDropped.
Reasoning or file parts in an assistant messageDropped.
Media in a tool resultDropped.
A tool whose inputSchema is not a JSON Schema objectSent with empty parameters.
Tool-call arguments that are not valid JSONPassed through as the raw string.

Use the AI SDK

If your app already uses the AI SDK, @osdk/aip-core/ai-sdk provides a Foundry provider for it. You get the AI SDK's own generateText, streamText, and tool() helpers, including its multi-step tool loop. The provider implements the v3 provider specification, so use ai version 6.

npm install @osdk/aip-core ai @ai-sdk/provider
src/aiSdk.ts
import { createFoundryAI } from "@osdk/aip-core/ai-sdk";
import { streamText } from "ai";
import { platformClient } from "./model";

const foundry = createFoundryAI({ client: platformClient });

const result = streamText({
  model: foundry("gpt-4o"),
  prompt: "Suggest three names for an onboarding checklist app.",
});

for await (const delta of result.textStream) {
  process.stdout.write(delta);
}

foundry(model) and foundry.languageModel(model) accept the same API name or ModelIdentifier as foundryModel. The provider also ignores topK and JSON response formats, and reports them as warnings.

Call a provider SDK directly

@osdk/language-models is the lower-level package @osdk/aip-core is built on. It returns Foundry's provider-compatible proxy URLs, so you can point an OpenAI, Anthropic, or Google SDK at Foundry instead of the provider. Use it when you need a provider feature @osdk/aip-core does not cover yet, such as the OpenAI Responses API or embeddings.

FunctionReturns
getOpenAiBaseUrl(client)<foundryUrl>/api/v2/llm/proxy/openai/v1
getAnthropicBaseUrl(client)<foundryUrl>/api/v2/llm/proxy/anthropic
getGoogleBaseUrl(client)<foundryUrl>/api/v2/llm/proxy/google
createFetch(client)The client's fetch, which sets a fresh Authorization header on every request.
getFoundryToken(client)Promise<string> with the current token.

Each function accepts an Ontology Client or a PlatformClient.

src/openai.ts
import { createFetch, getFoundryToken, getOpenAiBaseUrl } from "@osdk/language-models";
import OpenAI from "openai";
import { platformClient } from "./model";

const openai = new OpenAI({
  apiKey: await getFoundryToken(platformClient),
  baseURL: getOpenAiBaseUrl(platformClient),
  fetch: createFetch(platformClient),
});

const completion = await openai.chat.completions.create({
  model: "gpt-4o",
  messages: [{ role: "user", content: "Hello" }],
});
console.log(completion.choices[0]?.message.content);

createFetch replaces the Authorization header on each request, so the client keeps working after the token from getFoundryToken expires. The proxy accepts each provider's native request format; Foundry's LLM-provider compatible APIs documentation lists the supported endpoints.

Next steps

On this page