temporary publish; context exceeds patch.

This commit is contained in:
shengsuan-cloud committed 2025-09-02 11:07:17 +08:00
1 parent 1c5b69c693
commit 36636c83c2
3 files changed
+90 -98

No files matched your search

+85 -91
View File
@@ -50,104 +50,98 @@ export class ShengSuanYunHandler implements ApiHandler {
@withRetry()
async *createMessage(systemPrompt: string, messages: Anthropic.Messages.MessageParam[]): ApiStream {
const client = this.ensureClient()
this.lastGenerationId = undefined
const model = this.getModel()
try {
const stream = await createOpenRouterStream(
client,
systemPrompt,
messages,
model,
this.options.reasoningEffort,
this.options.thinkingBudgetTokens,
)
const stream = await createOpenRouterStream(
client,
systemPrompt,
messages,
model,
this.options.reasoningEffort,
this.options.thinkingBudgetTokens,
)
let didOutputUsage: boolean = false
let lastChunk: any = {}
for await (const chunk of stream) {
// openrouter returns an error object instead of the openai sdk throwing an error
if ("error" in chunk) {
const error = chunk.error as OpenRouterErrorResponse["error"]
console.error(`ShengSuanYun API Error: ${error?.code} - ${error?.message}`)
// Include metadata in the error message if available
const metadataStr = error.metadata ? `\nMetadata: ${JSON.stringify(error.metadata, null, 2)}` : ""
throw new Error(`ShengSuanYun API Error ${error.code}: ${error.message}${metadataStr}`)
}
if (!chunk.choices || chunk.choices.length === 0) {
console.error("shengSuanYun stream chunk:", chunk)
continue
}
let didOutputUsage: boolean = false
let lastChunk: any = {}
for await (const chunk of stream) {
// openrouter returns an error object instead of the openai sdk throwing an error
if ("error" in chunk) {
const error = chunk.error as OpenRouterErrorResponse["error"]
console.error(`ShengSuanYun API Error: ${error?.code} - ${error?.message}`)
// Include metadata in the error message if available
const metadataStr = error.metadata ? `\nMetadata: ${JSON.stringify(error.metadata, null, 2)}` : ""
throw new Error(`ShengSuanYun API Error ${error.code}: ${error.message}${metadataStr}`)
}
if (!chunk.choices || chunk.choices.length === 0) {
console.error("shengSuanYun stream chunk:", chunk)
continue
}
lastChunk = chunk
// console.log(JSON.stringify(chunk, null, 2))
lastChunk = chunk
// console.log(JSON.stringify(chunk, null, 2))
const choice = chunk.choices?.[0]
// Use type assertion since OpenRouter uses non-standard "error" finish_reason
if ((choice?.finish_reason as string) === "error") {
// Use type assertion since OpenRouter adds non-standard error property
const choiceWithError = choice as any
if (choiceWithError.error) {
const error = choiceWithError.error
console.error(
`ShengSuanYun Mid-Stream Error: ${error?.code || "Unknown"} - ${error?.message || "Unknown error"}`,
)
// Format error details
const errorDetails = typeof error === "object" ? JSON.stringify(error, null, 2) : String(error)
throw new Error(`ShengSuanYun Mid-Stream Error: ${errorDetails}`)
} else {
// Fallback if error details are not available
throw new Error(
`ShengSuanYun Mid-Stream Error: Stream terminated with error status but no error details provided`,
)
}
}
if (!this.lastGenerationId && chunk.id) {
this.lastGenerationId = chunk.id
}
const delta = chunk.choices[0]?.delta
if (delta?.content) {
yield {
type: "text",
text: delta.content,
}
}
// Reasoning tokens are returned separately from the content
// Skip reasoning content for Grok 4 models since it only displays "thinking" without providing useful information
if ("reasoning" in delta && delta.reasoning && !shouldSkipReasoningForModel(this.options.shengSuanYunModelId)) {
yield {
type: "reasoning",
// @ts-ignore-next-line
reasoning: delta.reasoning,
}
}
if (!didOutputUsage && chunk.usage) {
yield {
type: "usage",
cacheWriteTokens: 0,
cacheReadTokens: chunk.usage.prompt_tokens_details?.cached_tokens || 0,
inputTokens: (chunk.usage.prompt_tokens || 0) - (chunk.usage.prompt_tokens_details?.cached_tokens || 0),
outputTokens: chunk.usage.completion_tokens || 0,
// @ts-ignore-next-line
totalCost: (chunk.usage.cost || 0) + (chunk.usage.cost_details?.upstream_inference_cost || 0),
}
didOutputUsage = true
const choice = chunk.choices?.[0]
// Use type assertion since OpenRouter uses non-standard "error" finish_reason
if ((choice?.finish_reason as string) === "error") {
// Use type assertion since OpenRouter adds non-standard error property
const choiceWithError = choice as any
if (choiceWithError.error) {
const error = choiceWithError.error
console.error(
`ShengSuanYun Mid-Stream Error: ${error?.code || "Unknown"} - ${error?.message || "Unknown error"}`,
)
// Format error details
const errorDetails = typeof error === "object" ? JSON.stringify(error, null, 2) : String(error)
throw new Error(`ShengSuanYun Mid-Stream Error: ${errorDetails}`)
} else {
// Fallback if error details are not available
throw new Error(
`ShengSuanYun Mid-Stream Error: Stream terminated with error status but no error details provided`,
)
}
}
// Fallback to generation endpoint if usage chunk not returned ; NotImplemented yet
if (!didOutputUsage) {
console.log("ShengSuanYunHandler.createMessage -- lastChunk", JSON.stringify(lastChunk, null, 2))
// const apiStreamUsage = await this.getApiStreamUsage()
// if (apiStreamUsage) {
// yield apiStreamUsage
// }
const delta = chunk.choices[0]?.delta
if (delta?.content) {
yield {
type: "text",
text: delta.content,
}
}
} catch (e) {
console.error("ShengSuanYunHandler.createMessage(): ", e)
console.log(client, this.options)
throw e
// Reasoning tokens are returned separately from the content
// Skip reasoning content for Grok 4 models since it only displays "thinking" without providing useful information
if ("reasoning" in delta && delta.reasoning && !shouldSkipReasoningForModel(this.options.shengSuanYunModelId)) {
yield {
type: "reasoning",
// @ts-ignore-next-line
reasoning: delta.reasoning,
}
}
if (!didOutputUsage && chunk.usage) {
const input = (chunk.usage.prompt_tokens || 0) - (chunk.usage.prompt_tokens_details?.cached_tokens || 0)
const output = chunk.usage.completion_tokens || 0
// @ts-ignore-next-line
const cost = (chunk.usage.cost || 0) + (chunk.usage.cost_details?.upstream_inference_cost || 0)
const inputPrice = model.info.inputPrice || 0
const outputPrice = model.info.outputPrice || 0
yield {
type: "usage",
cacheWriteTokens: 0,
cacheReadTokens: chunk.usage.prompt_tokens_details?.cached_tokens || 0,
inputTokens: input,
outputTokens: output,
totalCost: cost ? cost : (input / 1000000) * inputPrice + (output / 1000000) * outputPrice,
}
didOutputUsage = true
}
}
// Fallback to generation endpoint if usage chunk not returned ; NotImplemented yet
if (!didOutputUsage) {
console.log("ShengSuanYunHandler.createMessage -- lastChunk without usage", JSON.stringify(lastChunk, null, 2))
// const apiStreamUsage = await this.getApiStreamUsage()
// if (apiStreamUsage) {
// yield apiStreamUsage
// }
}
}
+4 -2
View File
@@ -83,7 +83,8 @@ export function convertToOpenAiMessages(
console.log("+++++++++++++++++++++nonToolMessages.length+++++++++++++++++++++++++", nonToolMessages.length)
openAiMessages.push({
role: "user",
content: nonToolMessages.slice(-6).map((part) => {
// content: nonToolMessages.slice(-6).map((part) => {
content: nonToolMessages.map((part) => {
if (part.type === "image") {
return {
type: "image_url",
@@ -92,11 +93,12 @@ export function convertToOpenAiMessages(
},
}
}
// return { type: "text", text: part.text }
console.log(
"+++++++++++++++++++++nonToolMessage.text.length+++++++++++++++++++++++++",
part.text.length,
)
return { type: "text", text: part.text.substring(0, 3000) }
return { type: "text", text: part.text.substring(0, 6000) }
}),
})
}
+1 -5
View File
@@ -1726,11 +1726,7 @@ export class Task {
await this.messageStateHandler.saveClineMessagesAndUpdateHistory()
// saves task history item which we use to keep track of conversation history deleted range
}
console.log(
systemPrompt,
contextManagementMetadata.truncatedConversationHistory,
"--------------------------truncatedConversationHistory--------------",
)
const stream = this.api.createMessage(systemPrompt, contextManagementMetadata.truncatedConversationHistory)
const iterator = stream[Symbol.asyncIterator]()