Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow users to set request option headers for Anthropic's LLMs #4785

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 44 additions & 17 deletions core/llm/llms/Anthropic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -179,30 +179,34 @@ class Anthropic extends BaseLLM {
);

const msgs = this.convertMessages(messages);

// Set anthropic-beta headers directly into this.requestOptions
this.setBetaHeaders(shouldCacheSystemMessage);

// Create the request body
const requestBody = {
...this.convertArgs(options),
messages: msgs,
system: shouldCacheSystemMessage
? [
{
type: "text",
text: this.systemMessage,
cache_control: { type: "ephemeral" },
},
]
: systemMessage,
};

const response = await this.fetch(new URL("messages", this.apiBase), {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
"anthropic-version": "2023-06-01",
"x-api-key": this.apiKey as string,
...(shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation
? { "anthropic-beta": "prompt-caching-2024-07-31" }
: {}),
"x-api-key": this.apiKey as string
},
body: JSON.stringify({
...this.convertArgs(options),
messages: msgs,
system: shouldCacheSystemMessage
? [
{
type: "text",
text: this.systemMessage,
cache_control: { type: "ephemeral" },
},
]
: systemMessage,
}),
body: JSON.stringify(requestBody),
signal,
});

Expand Down Expand Up @@ -285,6 +289,29 @@ class Anthropic extends BaseLLM {
}
}
}

private setBetaHeaders(shouldCacheSystemMessage: boolean | undefined) {
if (!this.requestOptions) this.requestOptions = {};
if (!this.requestOptions.headers) this.requestOptions.headers = {};

const betaValues = new Set<string>();

const existingBetaHeaders = this.requestOptions.headers["anthropic-beta"];
if (existingBetaHeaders) {
existingBetaHeaders
.split(",")
.map((v) => v.trim())
.forEach((v) => betaValues.add(v));
}

if (shouldCacheSystemMessage || this.cacheBehavior?.cacheConversation) {
betaValues.add("prompt-caching-2024-07-31");
}

if (betaValues.size > 0) {
this.requestOptions.headers["anthropic-beta"] = Array.from(betaValues).join(",");
}
}
}

export default Anthropic;
Loading