@librechat/agents 4.2.7 → 4.2.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/harness/modelService.cjs +3 -29
- package/dist/cjs/harness/modelService.cjs.map +1 -1
- package/dist/cjs/llm/google/completion.cjs +49 -0
- package/dist/cjs/llm/google/completion.cjs.map +1 -0
- package/dist/cjs/llm/google/index.cjs +45 -20
- package/dist/cjs/llm/google/index.cjs.map +1 -1
- package/dist/cjs/llm/google/transport.cjs +133 -0
- package/dist/cjs/llm/google/transport.cjs.map +1 -0
- package/dist/cjs/llm/google/utils/common.cjs.map +1 -1
- package/dist/cjs/llm/stream/chunkAdapters.cjs +3 -2
- package/dist/cjs/llm/stream/chunkAdapters.cjs.map +1 -1
- package/dist/cjs/main.cjs +2 -0
- package/dist/cjs/messages/index.cjs +1 -0
- package/dist/cjs/messages/stored.cjs +34 -0
- package/dist/cjs/messages/stored.cjs.map +1 -0
- package/dist/esm/harness/modelService.mjs +4 -30
- package/dist/esm/harness/modelService.mjs.map +1 -1
- package/dist/esm/llm/google/completion.mjs +48 -0
- package/dist/esm/llm/google/completion.mjs.map +1 -0
- package/dist/esm/llm/google/index.mjs +46 -21
- package/dist/esm/llm/google/index.mjs.map +1 -1
- package/dist/esm/llm/google/transport.mjs +133 -0
- package/dist/esm/llm/google/transport.mjs.map +1 -0
- package/dist/esm/llm/google/utils/common.mjs.map +1 -1
- package/dist/esm/llm/stream/chunkAdapters.mjs +3 -2
- package/dist/esm/llm/stream/chunkAdapters.mjs.map +1 -1
- package/dist/esm/main.mjs +2 -1
- package/dist/esm/messages/index.mjs +1 -0
- package/dist/esm/messages/stored.mjs +34 -0
- package/dist/esm/messages/stored.mjs.map +1 -0
- package/dist/types/llm/google/completion.d.ts +4 -0
- package/dist/types/llm/google/index.d.ts +3 -1
- package/dist/types/llm/google/transport.d.ts +15 -0
- package/dist/types/llm/google/utils/common.d.ts +5 -3
- package/dist/types/llm/stream/chunkAdapters.d.ts +2 -1
- package/dist/types/messages/index.d.ts +1 -0
- package/dist/types/messages/stored.d.ts +7 -0
- package/package.json +2 -1
- package/src/harness/modelService.ts +3 -38
- package/src/llm/google/completion.ts +91 -0
- package/src/llm/google/index.ts +95 -34
- package/src/llm/google/transport.ts +202 -0
- package/src/llm/google/utils/common.ts +6 -2
- package/src/llm/stream/chunkAdapters.ts +3 -1
- package/src/messages/index.ts +1 -0
- package/src/messages/stored.ts +48 -0
package/dist/esm/main.mjs
CHANGED
|
@@ -44,6 +44,7 @@ import { REMOVE_ALL_MESSAGES, createRemoveAllMessage, messagesStateReducer } fro
|
|
|
44
44
|
import { DEFAULT_INTRA_TURN_RETAIN_RATIO, DEFAULT_RETAIN_RECENT_TURNS, getPairingBalancedSuffixStarts, resolveIntraTurnRetainTokens, splitAtRecencyBoundary } from "./messages/recency.mjs";
|
|
45
45
|
import { getAssistantTextPhase, getMessageCreationContentMetadata, splitAssistantTextContentByPhase } from "./messages/assistantPhase.mjs";
|
|
46
46
|
import { ProviderMessageProjectionInvariantError, inspectProviderMessageProjection, resolveProviderMessageProjectionInvariantMode } from "./messages/projectionInvariant.mjs";
|
|
47
|
+
import { toStoredMessage } from "./messages/stored.mjs";
|
|
47
48
|
import "./messages/index.mjs";
|
|
48
49
|
import { joinKeys, resetIfNotEmpty } from "./utils/graph.mjs";
|
|
49
50
|
import { resolveFetchProxyAgent, shouldBypassProxy } from "./utils/proxy.mjs";
|
|
@@ -158,4 +159,4 @@ import { HostModelAdmission, createHostModelService } from "./harness/modelServi
|
|
|
158
159
|
import { createHostToolBindings } from "./harness/index.mjs";
|
|
159
160
|
import { ProviderTextAdmission } from "./protection/providerTextAdmission.mjs";
|
|
160
161
|
import { BaseCheckpointSaver, Command, INTERRUPT, MemorySaver, interrupt, isInterrupted } from "@langchain/langgraph";
|
|
161
|
-
export { ACTIVITY_LABEL_RUN_NAME, ACTIVITY_PHASE_LABEL_RUN_NAME, ACTIVITY_PHASE_RUN_NAME, AGENT_MODEL_CALL_RUN_NAME, AIMessage, AIMessageChunk, ANTHROPIC_TOOL_TOKEN_MULTIPLIER, ASK_USER_QUESTION_ID_PATTERN, AgentSession, BASH_SHELL_GUIDANCE, BaseCheckpointSaver, BaseMessage, BaseMessageChunk, BashExecutionToolDefinition, BashExecutionToolDescription, BashExecutionToolName, BashExecutionToolSchema, BashProgrammaticToolCallingDefinition, BashProgrammaticToolCallingDescription, BashProgrammaticToolCallingName, BashProgrammaticToolCallingSchema, BashToolOutputReferencesGuide, CALIBRATION_RATIO_MAX, CALIBRATION_RATIO_MIN, CLOUDFLARE_BASH_CODING_TOOL_NAMES, CLOUDFLARE_CODING_TOOL_NAMES, CODE_API_AUTHORIZATION_ERROR_MESSAGE, CODE_API_CAPABILITY_ERROR_MESSAGE, CODE_API_EXECUTION_FAILED_ERROR_MESSAGE, CODE_API_EXPECTED_PROFILE_HEADER, CODE_API_INVALID_REQUEST_ERROR_MESSAGE, CODE_API_RATE_LIMITED_ERROR_MESSAGE, CODE_API_UNAVAILABLE_ERROR_MESSAGE, CODE_ARTIFACT_PATH_GUIDANCE, CODE_EXECUTION_TOOLS, COMMAND_TOKEN_PROVIDER, COMPACTION_SEMANTIC_INDEX_LIMITS, Calculator, CalculatorSchema, CalculatorToolDefinition, CalculatorToolDescription, CalculatorToolName, Callback, ChatModelStreamHandler, CloudflareBashExecutionToolDescription, CloudflareCodeExecutionToolDescription, CodeApiRequestError, CodeExecutionToolDefinition, CodeExecutionToolDescription, CodeExecutionToolName, CodeExecutionToolSchema, Command, CommonEvents, CompileCheckToolName, Constants, ContentTypes, DATE_RANGE, DECISION_PRESETS, DEFAULT_API_KEY_ENV, DEFAULT_CONTEXT_PRUNING_SETTINGS, DEFAULT_COUNTRY_DESCRIPTION, DEFAULT_HOOK_TIMEOUT_MS, DEFAULT_INTRA_TURN_RETAIN_RATIO, DEFAULT_MAX_SEALS, DEFAULT_MAX_STOP_CONTINUATIONS, DEFAULT_MAX_TOOL_CALL_ARG_BYTES, DEFAULT_PREEMPT_RESTART_GRACE_MS, DEFAULT_PROMPT_CACHE_TTL, DEFAULT_QUERY_DESCRIPTION, DEFAULT_RECURSION_LIMIT, DEFAULT_RESERVE_RATIO, DEFAULT_RETAIN_RECENT_TURNS, DEFAULT_STREAM_DELAY, DEFAULT_SUBAGENT_DESCRIPTION, DEFAULT_TOOL_TOKEN_MULTIPLIER, DecisionError, DynamicStructuredTool, ESTIMATED_TOKENS_PER_DOCUMENT, EnvVar, EventActorExecutor, FADING_MIN_BUDGET_TOKENS, FADING_TIER_VERSION, FAILED_EXECUTION_FILE_REMINDER, FATAL_DECISION_FAILURES, FakeChatModel, GEMINI_PARTS, GEMINI_REPLAY_UNSUPPORTED, GRAPH_SUBAGENT_HITL_VERSION, GitHubCompareTool, GitHubCompareToolDefinition, GitHubCompareToolDescription, GitHubCompareToolName, GitHubCompareToolSchema, GitHubComparisonError, Graph, GraphEvents, GraphNodeActions, GraphNodeKeys, HARD_MAX_TOOL_CALL_INPUT_CHARS, HARD_MAX_TOOL_RESULT_CHARS, HARD_MAX_TOTAL_TOOL_OUTPUT_SIZE, HOOK_EVENTS, HOOK_INJECTED_MESSAGES_CAPABLE, HOOK_PREEMPT_BOUNDARY_CAPABLE, HOOK_PREEMPT_RESTART_CAPABLE, HOOK_STOP_CONTINUATION_CAPABLE, HTTP_PROVIDER_ID, HandlerRegistry, HandoffLimitError, HookRegistry, HostChatModel, HostModelAdmission, HostModelServiceError, HumanMessage, IMAGE_TOKEN_SAFETY_MARGIN, INSTRUCTIONLESS_HANDOFF_CUE, INTENT_ARG, INTENT_DESCRIPTION, INTENT_LABEL_MARKER, INTENT_PROPERTY, INTERRUPT, InMemorySubagentTaskStore, JsonlSessionStore, LANGFUSE_OBSERVATION_METADATA_ARTIFACT_KEY, LLMStreamHandler, LOCAL_CODING_BUNDLE_NAMES, LOCAL_CODING_TOOL_NAMES, LOCAL_SPAWN_TIMEOUT_MS, LocalBashExecutionToolDescription, LocalCodeExecutionToolDescription, LocalEditFileToolName, LocalEditFileToolSchema, LocalFileCheckpointerImpl, LocalGlobSearchToolName, LocalGlobSearchToolSchema, LocalGrepSearchToolName, LocalGrepSearchToolSchema, LocalListDirectoryToolName, LocalListDirectoryToolSchema, LocalReadFileToolSchema, LocalWriteFileToolName, LocalWriteFileToolSchema, MASKED_RESULT_MIN_CHARS, MAX_ASK_USER_QUESTIONS, MAX_CACHE_SIZE, MAX_PATTERN_LENGTH, MIN_JSON_VALUE_CHARS, MULTI_AGENT_GRAPH_RUN_NAME, ManualSummarizationSkippedError, MemorySaver, ModelEndHandler, MultiAgentGraph, OPENAI_RESPONSES_ACTIVE_REASONING_ID_KEY, OPENAI_RESPONSES_REPLAY_POSITIONS_KEY, ORIGINAL_CONTENT_MAX_CHARS, PIN_SENTINEL_MODEL, PREDECESSOR_HANDOFF_CUE, PREEMPT_BOUNDARY_HOOK_TIMEOUT_MS, PRESSURE_THRESHOLD_MASKING, PROBE_MAX_WAIT_MS, PROVIDER_MESSAGE_PROVENANCE_LIMITS, PROVIDER_MESSAGE_PROVENANCE_VERSION, PROVIDER_TEXT_PROTECTION_VERSION, ProgrammaticToolCallingDefinition, ProgrammaticToolCallingDescription, ProgrammaticToolCallingName, ProgrammaticToolCallingSchema, PromptTemplate, ProviderMessageProjectionInvariantError, ProviderTextAdmission, ProviderTextProtectionError, Providers, REASONING_LABEL_RUN_NAME, REMOVE_ALL_MESSAGES, REPLY_PRIMER_TOKENS, ReadFileToolDefinition, ReadFileToolDescription, ReadFileToolName, ReadFileToolSchema, Run, Runnable, RunnableCallable, RunnableLambda, RunnableSequence, SDK_STREAM_DISPATCH, STANDARD_GRAPH_RUN_NAME, STATEFUL_BASH_NOTE, STATEFUL_ENV_NOTE, STEP_GRACE_MS, SUBAGENT_CONTEXT_VERSION, SUBAGENT_HOST_ARG_LIMITS, SessionManager, SkillToolDefinition, SkillToolDescription, SkillToolName, SkillToolSchema, StandardGraph, StatefulBashExecutionToolDescription, StatefulCodeExecutionToolDescription, StepTypes, StreamLimitExceededError, StructuredTool, SubagentExecutor, SubagentHostArgumentError, SubagentResolutionError, SubagentToolDefinition, SubagentToolDescription, SubagentToolName, SubagentToolSchema, SystemMessage, TMP_SCRATCH_OUTPUT_REMINDER, TOOL_APPROVAL_EXECUTION_SCOPE_CAPABLE, TOOL_APPROVAL_EXECUTION_SCOPE_CONFIG_KEY, TOOL_INPUT_ELISION_NOTE, TestChatStreamHandler, TestLLMStreamHandler, TitleMethod, TokenEncoderManager, Tool, ToolCallTypes, ToolEndHandler, ToolMessage, ToolNode, ToolSearchToolDefinition, ToolSearchToolDescription, ToolSearchToolName, ToolSearchToolSchema, UnsafeTokenMeasurementError, WebSearchToolDefinition, WebSearchToolDescription, WebSearchToolName, WebSearchToolSchema, _createBashProgramForTests, _resetLocalEngineWarningsForTests, _resetRipgrepCacheForTests, _resetSyntaxCheckProbeCacheForTests, _resetUnrecognizedTriggerWarnings, addBedrockCacheControl, addBedrockTailCacheControl, addCacheControl, addCacheControlToStablePrefixMessages, addCodeApiExecutionProfileHeader, addTailCacheControl, appendCodeSessionFileSummary, appendFailedExecutionFileReminder, appendInstructionlessHandoffCue, appendPredecessorHandoffCue, appendProviderMessageProvenance, appendTmpScratchReminder, applyContextPruning, applyEdit, applyFadingCaps, applyOutcome, applyPreToolUseHooksForBridge, apportionTokenCounts, askUserQuestion, askUserQuestions, attemptInvoke, bashAstFindingsToErrors, booleanQuestion, buildAnthropicCacheControl, buildBashExecutionToolDescription, buildBashExecutionToolSchema, buildBedrockCachePoint, buildChildInputs, buildCodeApiEndpoint, buildCodeApiExecutionErrorMessage, buildCodeApiHttpErrorMessage, buildCodeExecutionToolDescription, buildCodeExecutionToolSchema, buildSandboxRuntimeConfig, buildSubagentHostArgProperties, buildSubagentToolParams, buildSummarizationInstruction, buildSummaryCarrierText, calculateMaxToolCallInputChars, calculateMaxToolResultChars, calculateMaxTotalToolOutputSize, calculateTotalTokens, canSealPreempt, canonicalizeServerName, captureGeminiReplayParts, checkValidNumber, choiceQuestion, clampCalibrationRatio, classifyAttachment, clientExecTimeoutMs, clientFsTimeoutMs, cloneMessage, coalesceAdjacentUserTurns, commandAvailabilityEnvCacheKey, commandToken, compactSyntheticProviderContextMessage, compareGitHubCommits, composeAbortSignals, composeEventHandlers, computeAdaptivePieceSize, constructorChainHasLcName, convertInjectedMessages, convertMessagesToContent, corpusStats, countNestedGroups, countrySchema, createAgentSession, createBashExecutionTool, createBashProgrammaticToolCallingSchema, createBashProgrammaticToolCallingTool, createBm25Reranker, createBreaker, createCloudflareBashExecutionTool, createCloudflareBashProgrammaticToolCallingTool, createCloudflareBridgeRuntime, createCloudflareCodeExecutionTool, createCloudflareCodingToolBundle, createCloudflareCodingTools, createCloudflareExecutionTool, createCloudflareExecutionWorld, createCloudflareLocalExecutionConfig, createCloudflareProgrammaticToolCallingTool, createCloudflareWorkspaceFS, createCodeExecutionTool, createCompileCheckTool, createCompileCheckToolDefinition, createContentAggregator, createCrossEncoderReranker, createDecisionModel, createEventActorExecutor, createFadingTier, createFakeStreamingLLM, createGraph, createHandlers, createHostModelService, createHostProviderTextProtection, createHostProviderTextService, createHostToolBindings, createHttpDecisionModel, createLocalBashExecutionTool, createLocalBashProgrammaticToolCallingTool, createLocalCodeExecutionTool, createLocalCodingToolBundle, createLocalCodingToolDefinitions, createLocalCodingToolRegistry, createLocalCodingTools, createLocalEditFileTool, createLocalFileCheckpointer, createLocalGlobSearchTool, createLocalGrepSearchTool, createLocalListDirectoryTool, createLocalProgrammaticToolCallingTool, createLocalReadFileTool, createLocalWriteFileTool, createMetadataAggregator, createProgrammaticToolCallingSchema, createProgrammaticToolCallingTool, createPruneMessages, createRemoveAllMessage, createRunHandlers, createSchemaOnlyTool, createSchemaOnlyTools, createScoreCache, createSearchTool, createSemaphore, createStructuredChatDecisionModel, createSubagentToolDefinition, createSystemOneReranker, createTokenCounter, createToolErrorOwnership, createToolPolicyHook, createToolSearch, createTransport, createWebSearchReranker, createWorkspacePolicyHook, dateSchema, decisionPreset, decisionProviderNames, decodeFile, defaultOmitOptions, deriveMessages, deserializeMessage, deserializeProviderTextProtectionError, dispatchesChatModelStream, dropIncompleteToolStreamContent, emptyOutputMessage, emptyRerankUsage, encodeFile, encodingForModel, encodingOfTokenCounter, enforceOriginalContentCap, ensureThinkingBlockInMessages, escapeRegexSpecialChars, estimateAnthropicImageTokens, estimateDocumentBlockTokens, estimateImageBlockTokens, estimateOpenAIImageTokens, estimateTimedMediaBlockTokens, estimatedUsage, execWithClientTimeout, executeCloudflareBash, executeCloudflareCode, executeHooks, executeLocalBash, executeLocalBashWithArgs, executeLocalCode, executeParallelSearches, executeTools, extractErrorMessage, extractImageDimensions, extractMcpServerName, extractTextFromContent, extractToolDiscoveries, extractUsedBashToolNames, extractUsedToolNames, fadingBudgetTokens, fadingRungForBudget, fadingRungForExchangeChars, fadingRungForResultChars, failureForStatus, fetchSessionFiles, filterBashToolsByUsage, filterGraphSubagentResult, filterSubagentResult, filterToolsByLocalAllowlist, filterToolsByUsage, findLastIndex, flattenLegacyContent, foldToolBlocksForToollessAgent, formatAgentMessages, formatAnthropicArtifactContent, formatAnthropicMessage, formatArtifactPayload, formatCloudflareOutput, formatCompletedResponse, formatContentStrings, formatFromLangChain, formatLangChainMessages, formatMediaMessage, formatMessage, formatServerListing, formatSkillCatalog, getAssistantTextPhase, getAvailableMcpServers, getBaseToolName, getBufferString, getChatModelClass, getChunkContent, getCloudflareWorkspaceRoot, getCodeBaseURL, getContextOverflowInfo, getConverseOverrideMessage, getDeferredToolsListing, getExecutionWorld, getLocalCwd, getLocalSessionId, getMaxOutputTokensKey, getMessageCreationContentMetadata, getMessageId, getMessagesWithinTokenLimit, getPairingBalancedSuffixStarts, getProviderMessageProvenance, getProviderSourceMessageIds, getReadRoots, getSpawn, getSubagentHostArgumentFailureMessage, getSubagentResolutionFailureMessage, getTokenCountForMessage, getWorkspaceFS, getWorkspaceRoots, getWriteRoots, handleServerToolResult, handleToolCallChunks, handleToolCalls, hasBijectiveProviderContentPartMapping, hasNestedQuantifier, hasNestedQuantifiers, hasNonEmptyTextContent, hasToolSearchInCurrentTurn, hasUnsafeStructuredSerialization, identityOutcome, imageAttachmentContent, imagesSchema, initializeModel, inspectProviderMessageProjection, inspectProviderMessageProvenance, inspectProviderSourceMessageIds, interrupt, isAIMessage, isAnthropicLike, isAskUserQuestionsInterrupt, isBaseMessage, isBooleanAnswer, isChoiceAnswer, isContextOverflowError, isDangerousPattern, isDecisionObject, isFadingTier, isFatalDecisionError, isFromAnyMcpServer, isFromMcpServer, isGeminiReplayParts, isGoogleLike, isGraphSubagentConfig, isInformativeFadingTier, isIntentLabelProperty, isInterrupted, isLegacyConvertible, isLegacyFadingTier, isLibreChatOpenAIModel, isLikelyContextOverflowError, isOpenAILike, isPresent, isProgrammaticRunnerAutoBound, isProgrammaticRunnerResolvedDirectly, isProviderCancellation, isReasoningContentBlock, isRerankPermutation, isScoreAnswer, isSyntheticProviderContextMessage, isThinkingEnabled, isToolMessage, isZodSchema, joinKeys, labelContentByAgent, locateEdit, makeIsDeferred, makeRequest, mapChatMessagesToStoredMessages, mapStoredMessagesToChatMessages, markTokenCounterCacheCompatible, maskConsumedToolResults, matchesQuery, maxFadingRung, mergeAggregatedHookResults, mergeDecisionSettings, messagesStateReducer, modifyDeltaProperties, newsSchema, nodeExecutionWorld, noneReranker, normalizeBashToolResultsForReplay, normalizeCodeApiRequestError, normalizeSearchResultData, normalizeServerFilter, normalizeSubagentConfigEntries, normalizeSubagentConfigs, normalizeToBashIdentifier, normalizeToPythonIdentifier, outcomeFieldsFromResult, parseBooleanEnv, parseEnvelope, partitionAndMarkAnthropicToolCache, performLocalSearch, preFlightTruncateToolCallInputs, preFlightTruncateToolResults, prepareBashProgrammaticCode, prepareProviderRequest, probe, probeLocalCommandAvailability, probePin, probeRequest, projectAgentContextUsage, projectAnthropicArtifactContent, projectArtifactPayload, projectCacheControlledToolOutputsToText, projectComputerCallOutputsToText, projectOpenAIChatToolMessageContent, projectOpenAIResponsesToolMessageContent, projectOpenAIToolMessageContent, projectOpenRouterToolMessageContent, projectSingleTextToolOutputsToText, projectStructuredToolOutputsToText, projectToolCallInputs, projectToolMessagesForProvider, projectToolStreamContentForProvider, querySchema, rankedEntries, readAnswer, readDecisionUsage, readIntent, readOutcomeFields, readTokenMetadataProperty, redact, registerProvider, removePredecessorHandoffCue, repairOrphanedToolMessages, rerankCost, resetIfNotEmpty, resolveBedrockPromptCacheTtl, resolveCloudflareSandbox, resolveCodeApiAuthHeaders, resolveContextPruningSettings, resolveFadingCaps, resolveFadingTier, resolveFetchProxyAgent, resolveIntraTurnRetainTokens, resolveLocalExecutionConfig, resolveLocalExecutionTools, resolveLocalImplementationNames, resolveLocalToolRegistry, resolveLocalToolsForBinding, resolvePromptCacheTtl, resolveProviderMessageProjectionInvariantMode, resolveSearchOutcome, resolveServerFilters, resolveStreamDelay, resolveStreamLimits, resolveSubagentConfigEntries, resolveSubagentConfigs, resolveSubagentHostArgs, resolveToolOutcome, resolveWorkspacePath, resolveWorkspacePathSafe, restoreGeminiReplayParts, retryAfterMs, runBashAstChecks, runPlainExecution, runPostEditSyntaxCheck, sanitizeOrphanToolBlocks, sanitizeRegex, scoreQuestion, seedFadingTier, selectRuntimeSessionHint, separateSummarizationParameters, serializeMessage, serializeProviderTextProtectionError, serializeToolCallInput, setCommandAvailabilityCacheEntry, setFreshProviderMessageProvenance, setInvalidProviderMessageProvenance, setProviderMessageProvenance, shellQuote, shiftIndexTokenCountMap, shouldBypassProxy, shouldTriggerSummarization, sleep, sliceWithoutSplittingSurrogates, smoothStream, snapshotExecutionIdentity, spawnLocalProcess, splitAssistantTextContentByPhase, splitAtRecencyBoundary, stampSyntheticProviderMessage, strictAlternationProviders, stripAnthropicCacheControl, stripBedrockCacheControl, stripCodeSessionFileSummary, stripIntent, summarizeEvent, supportsBedrockToolCache, syncBudgetDerivedFields, toJsonSchema, toOutcomeReranker, toWireQuestion, tokenizeCode, tool, toolResultTypes, toolsCondition, truncateLocalOutput, truncateToolInput, truncateToolResultContent, tryFallbackProviders, unescapeObject, unwrapToolResponse, validateBashCommand, validateCloudflareBashCommand, validateDecisionQuestions, videosSchema, withBreaker, withClientTimeout, withDecisionDeadline, withFallback, withInstructionlessHandoffCue, withIntent, withMessageRole, withoutIntent, wrapPythonForPlainExecution };
|
|
162
|
+
export { ACTIVITY_LABEL_RUN_NAME, ACTIVITY_PHASE_LABEL_RUN_NAME, ACTIVITY_PHASE_RUN_NAME, AGENT_MODEL_CALL_RUN_NAME, AIMessage, AIMessageChunk, ANTHROPIC_TOOL_TOKEN_MULTIPLIER, ASK_USER_QUESTION_ID_PATTERN, AgentSession, BASH_SHELL_GUIDANCE, BaseCheckpointSaver, BaseMessage, BaseMessageChunk, BashExecutionToolDefinition, BashExecutionToolDescription, BashExecutionToolName, BashExecutionToolSchema, BashProgrammaticToolCallingDefinition, BashProgrammaticToolCallingDescription, BashProgrammaticToolCallingName, BashProgrammaticToolCallingSchema, BashToolOutputReferencesGuide, CALIBRATION_RATIO_MAX, CALIBRATION_RATIO_MIN, CLOUDFLARE_BASH_CODING_TOOL_NAMES, CLOUDFLARE_CODING_TOOL_NAMES, CODE_API_AUTHORIZATION_ERROR_MESSAGE, CODE_API_CAPABILITY_ERROR_MESSAGE, CODE_API_EXECUTION_FAILED_ERROR_MESSAGE, CODE_API_EXPECTED_PROFILE_HEADER, CODE_API_INVALID_REQUEST_ERROR_MESSAGE, CODE_API_RATE_LIMITED_ERROR_MESSAGE, CODE_API_UNAVAILABLE_ERROR_MESSAGE, CODE_ARTIFACT_PATH_GUIDANCE, CODE_EXECUTION_TOOLS, COMMAND_TOKEN_PROVIDER, COMPACTION_SEMANTIC_INDEX_LIMITS, Calculator, CalculatorSchema, CalculatorToolDefinition, CalculatorToolDescription, CalculatorToolName, Callback, ChatModelStreamHandler, CloudflareBashExecutionToolDescription, CloudflareCodeExecutionToolDescription, CodeApiRequestError, CodeExecutionToolDefinition, CodeExecutionToolDescription, CodeExecutionToolName, CodeExecutionToolSchema, Command, CommonEvents, CompileCheckToolName, Constants, ContentTypes, DATE_RANGE, DECISION_PRESETS, DEFAULT_API_KEY_ENV, DEFAULT_CONTEXT_PRUNING_SETTINGS, DEFAULT_COUNTRY_DESCRIPTION, DEFAULT_HOOK_TIMEOUT_MS, DEFAULT_INTRA_TURN_RETAIN_RATIO, DEFAULT_MAX_SEALS, DEFAULT_MAX_STOP_CONTINUATIONS, DEFAULT_MAX_TOOL_CALL_ARG_BYTES, DEFAULT_PREEMPT_RESTART_GRACE_MS, DEFAULT_PROMPT_CACHE_TTL, DEFAULT_QUERY_DESCRIPTION, DEFAULT_RECURSION_LIMIT, DEFAULT_RESERVE_RATIO, DEFAULT_RETAIN_RECENT_TURNS, DEFAULT_STREAM_DELAY, DEFAULT_SUBAGENT_DESCRIPTION, DEFAULT_TOOL_TOKEN_MULTIPLIER, DecisionError, DynamicStructuredTool, ESTIMATED_TOKENS_PER_DOCUMENT, EnvVar, EventActorExecutor, FADING_MIN_BUDGET_TOKENS, FADING_TIER_VERSION, FAILED_EXECUTION_FILE_REMINDER, FATAL_DECISION_FAILURES, FakeChatModel, GEMINI_PARTS, GEMINI_REPLAY_UNSUPPORTED, GRAPH_SUBAGENT_HITL_VERSION, GitHubCompareTool, GitHubCompareToolDefinition, GitHubCompareToolDescription, GitHubCompareToolName, GitHubCompareToolSchema, GitHubComparisonError, Graph, GraphEvents, GraphNodeActions, GraphNodeKeys, HARD_MAX_TOOL_CALL_INPUT_CHARS, HARD_MAX_TOOL_RESULT_CHARS, HARD_MAX_TOTAL_TOOL_OUTPUT_SIZE, HOOK_EVENTS, HOOK_INJECTED_MESSAGES_CAPABLE, HOOK_PREEMPT_BOUNDARY_CAPABLE, HOOK_PREEMPT_RESTART_CAPABLE, HOOK_STOP_CONTINUATION_CAPABLE, HTTP_PROVIDER_ID, HandlerRegistry, HandoffLimitError, HookRegistry, HostChatModel, HostModelAdmission, HostModelServiceError, HumanMessage, IMAGE_TOKEN_SAFETY_MARGIN, INSTRUCTIONLESS_HANDOFF_CUE, INTENT_ARG, INTENT_DESCRIPTION, INTENT_LABEL_MARKER, INTENT_PROPERTY, INTERRUPT, InMemorySubagentTaskStore, JsonlSessionStore, LANGFUSE_OBSERVATION_METADATA_ARTIFACT_KEY, LLMStreamHandler, LOCAL_CODING_BUNDLE_NAMES, LOCAL_CODING_TOOL_NAMES, LOCAL_SPAWN_TIMEOUT_MS, LocalBashExecutionToolDescription, LocalCodeExecutionToolDescription, LocalEditFileToolName, LocalEditFileToolSchema, LocalFileCheckpointerImpl, LocalGlobSearchToolName, LocalGlobSearchToolSchema, LocalGrepSearchToolName, LocalGrepSearchToolSchema, LocalListDirectoryToolName, LocalListDirectoryToolSchema, LocalReadFileToolSchema, LocalWriteFileToolName, LocalWriteFileToolSchema, MASKED_RESULT_MIN_CHARS, MAX_ASK_USER_QUESTIONS, MAX_CACHE_SIZE, MAX_PATTERN_LENGTH, MIN_JSON_VALUE_CHARS, MULTI_AGENT_GRAPH_RUN_NAME, ManualSummarizationSkippedError, MemorySaver, ModelEndHandler, MultiAgentGraph, OPENAI_RESPONSES_ACTIVE_REASONING_ID_KEY, OPENAI_RESPONSES_REPLAY_POSITIONS_KEY, ORIGINAL_CONTENT_MAX_CHARS, PIN_SENTINEL_MODEL, PREDECESSOR_HANDOFF_CUE, PREEMPT_BOUNDARY_HOOK_TIMEOUT_MS, PRESSURE_THRESHOLD_MASKING, PROBE_MAX_WAIT_MS, PROVIDER_MESSAGE_PROVENANCE_LIMITS, PROVIDER_MESSAGE_PROVENANCE_VERSION, PROVIDER_TEXT_PROTECTION_VERSION, ProgrammaticToolCallingDefinition, ProgrammaticToolCallingDescription, ProgrammaticToolCallingName, ProgrammaticToolCallingSchema, PromptTemplate, ProviderMessageProjectionInvariantError, ProviderTextAdmission, ProviderTextProtectionError, Providers, REASONING_LABEL_RUN_NAME, REMOVE_ALL_MESSAGES, REPLY_PRIMER_TOKENS, ReadFileToolDefinition, ReadFileToolDescription, ReadFileToolName, ReadFileToolSchema, Run, Runnable, RunnableCallable, RunnableLambda, RunnableSequence, SDK_STREAM_DISPATCH, STANDARD_GRAPH_RUN_NAME, STATEFUL_BASH_NOTE, STATEFUL_ENV_NOTE, STEP_GRACE_MS, SUBAGENT_CONTEXT_VERSION, SUBAGENT_HOST_ARG_LIMITS, SessionManager, SkillToolDefinition, SkillToolDescription, SkillToolName, SkillToolSchema, StandardGraph, StatefulBashExecutionToolDescription, StatefulCodeExecutionToolDescription, StepTypes, StreamLimitExceededError, StructuredTool, SubagentExecutor, SubagentHostArgumentError, SubagentResolutionError, SubagentToolDefinition, SubagentToolDescription, SubagentToolName, SubagentToolSchema, SystemMessage, TMP_SCRATCH_OUTPUT_REMINDER, TOOL_APPROVAL_EXECUTION_SCOPE_CAPABLE, TOOL_APPROVAL_EXECUTION_SCOPE_CONFIG_KEY, TOOL_INPUT_ELISION_NOTE, TestChatStreamHandler, TestLLMStreamHandler, TitleMethod, TokenEncoderManager, Tool, ToolCallTypes, ToolEndHandler, ToolMessage, ToolNode, ToolSearchToolDefinition, ToolSearchToolDescription, ToolSearchToolName, ToolSearchToolSchema, UnsafeTokenMeasurementError, WebSearchToolDefinition, WebSearchToolDescription, WebSearchToolName, WebSearchToolSchema, _createBashProgramForTests, _resetLocalEngineWarningsForTests, _resetRipgrepCacheForTests, _resetSyntaxCheckProbeCacheForTests, _resetUnrecognizedTriggerWarnings, addBedrockCacheControl, addBedrockTailCacheControl, addCacheControl, addCacheControlToStablePrefixMessages, addCodeApiExecutionProfileHeader, addTailCacheControl, appendCodeSessionFileSummary, appendFailedExecutionFileReminder, appendInstructionlessHandoffCue, appendPredecessorHandoffCue, appendProviderMessageProvenance, appendTmpScratchReminder, applyContextPruning, applyEdit, applyFadingCaps, applyOutcome, applyPreToolUseHooksForBridge, apportionTokenCounts, askUserQuestion, askUserQuestions, attemptInvoke, bashAstFindingsToErrors, booleanQuestion, buildAnthropicCacheControl, buildBashExecutionToolDescription, buildBashExecutionToolSchema, buildBedrockCachePoint, buildChildInputs, buildCodeApiEndpoint, buildCodeApiExecutionErrorMessage, buildCodeApiHttpErrorMessage, buildCodeExecutionToolDescription, buildCodeExecutionToolSchema, buildSandboxRuntimeConfig, buildSubagentHostArgProperties, buildSubagentToolParams, buildSummarizationInstruction, buildSummaryCarrierText, calculateMaxToolCallInputChars, calculateMaxToolResultChars, calculateMaxTotalToolOutputSize, calculateTotalTokens, canSealPreempt, canonicalizeServerName, captureGeminiReplayParts, checkValidNumber, choiceQuestion, clampCalibrationRatio, classifyAttachment, clientExecTimeoutMs, clientFsTimeoutMs, cloneMessage, coalesceAdjacentUserTurns, commandAvailabilityEnvCacheKey, commandToken, compactSyntheticProviderContextMessage, compareGitHubCommits, composeAbortSignals, composeEventHandlers, computeAdaptivePieceSize, constructorChainHasLcName, convertInjectedMessages, convertMessagesToContent, corpusStats, countNestedGroups, countrySchema, createAgentSession, createBashExecutionTool, createBashProgrammaticToolCallingSchema, createBashProgrammaticToolCallingTool, createBm25Reranker, createBreaker, createCloudflareBashExecutionTool, createCloudflareBashProgrammaticToolCallingTool, createCloudflareBridgeRuntime, createCloudflareCodeExecutionTool, createCloudflareCodingToolBundle, createCloudflareCodingTools, createCloudflareExecutionTool, createCloudflareExecutionWorld, createCloudflareLocalExecutionConfig, createCloudflareProgrammaticToolCallingTool, createCloudflareWorkspaceFS, createCodeExecutionTool, createCompileCheckTool, createCompileCheckToolDefinition, createContentAggregator, createCrossEncoderReranker, createDecisionModel, createEventActorExecutor, createFadingTier, createFakeStreamingLLM, createGraph, createHandlers, createHostModelService, createHostProviderTextProtection, createHostProviderTextService, createHostToolBindings, createHttpDecisionModel, createLocalBashExecutionTool, createLocalBashProgrammaticToolCallingTool, createLocalCodeExecutionTool, createLocalCodingToolBundle, createLocalCodingToolDefinitions, createLocalCodingToolRegistry, createLocalCodingTools, createLocalEditFileTool, createLocalFileCheckpointer, createLocalGlobSearchTool, createLocalGrepSearchTool, createLocalListDirectoryTool, createLocalProgrammaticToolCallingTool, createLocalReadFileTool, createLocalWriteFileTool, createMetadataAggregator, createProgrammaticToolCallingSchema, createProgrammaticToolCallingTool, createPruneMessages, createRemoveAllMessage, createRunHandlers, createSchemaOnlyTool, createSchemaOnlyTools, createScoreCache, createSearchTool, createSemaphore, createStructuredChatDecisionModel, createSubagentToolDefinition, createSystemOneReranker, createTokenCounter, createToolErrorOwnership, createToolPolicyHook, createToolSearch, createTransport, createWebSearchReranker, createWorkspacePolicyHook, dateSchema, decisionPreset, decisionProviderNames, decodeFile, defaultOmitOptions, deriveMessages, deserializeMessage, deserializeProviderTextProtectionError, dispatchesChatModelStream, dropIncompleteToolStreamContent, emptyOutputMessage, emptyRerankUsage, encodeFile, encodingForModel, encodingOfTokenCounter, enforceOriginalContentCap, ensureThinkingBlockInMessages, escapeRegexSpecialChars, estimateAnthropicImageTokens, estimateDocumentBlockTokens, estimateImageBlockTokens, estimateOpenAIImageTokens, estimateTimedMediaBlockTokens, estimatedUsage, execWithClientTimeout, executeCloudflareBash, executeCloudflareCode, executeHooks, executeLocalBash, executeLocalBashWithArgs, executeLocalCode, executeParallelSearches, executeTools, extractErrorMessage, extractImageDimensions, extractMcpServerName, extractTextFromContent, extractToolDiscoveries, extractUsedBashToolNames, extractUsedToolNames, fadingBudgetTokens, fadingRungForBudget, fadingRungForExchangeChars, fadingRungForResultChars, failureForStatus, fetchSessionFiles, filterBashToolsByUsage, filterGraphSubagentResult, filterSubagentResult, filterToolsByLocalAllowlist, filterToolsByUsage, findLastIndex, flattenLegacyContent, foldToolBlocksForToollessAgent, formatAgentMessages, formatAnthropicArtifactContent, formatAnthropicMessage, formatArtifactPayload, formatCloudflareOutput, formatCompletedResponse, formatContentStrings, formatFromLangChain, formatLangChainMessages, formatMediaMessage, formatMessage, formatServerListing, formatSkillCatalog, getAssistantTextPhase, getAvailableMcpServers, getBaseToolName, getBufferString, getChatModelClass, getChunkContent, getCloudflareWorkspaceRoot, getCodeBaseURL, getContextOverflowInfo, getConverseOverrideMessage, getDeferredToolsListing, getExecutionWorld, getLocalCwd, getLocalSessionId, getMaxOutputTokensKey, getMessageCreationContentMetadata, getMessageId, getMessagesWithinTokenLimit, getPairingBalancedSuffixStarts, getProviderMessageProvenance, getProviderSourceMessageIds, getReadRoots, getSpawn, getSubagentHostArgumentFailureMessage, getSubagentResolutionFailureMessage, getTokenCountForMessage, getWorkspaceFS, getWorkspaceRoots, getWriteRoots, handleServerToolResult, handleToolCallChunks, handleToolCalls, hasBijectiveProviderContentPartMapping, hasNestedQuantifier, hasNestedQuantifiers, hasNonEmptyTextContent, hasToolSearchInCurrentTurn, hasUnsafeStructuredSerialization, identityOutcome, imageAttachmentContent, imagesSchema, initializeModel, inspectProviderMessageProjection, inspectProviderMessageProvenance, inspectProviderSourceMessageIds, interrupt, isAIMessage, isAnthropicLike, isAskUserQuestionsInterrupt, isBaseMessage, isBooleanAnswer, isChoiceAnswer, isContextOverflowError, isDangerousPattern, isDecisionObject, isFadingTier, isFatalDecisionError, isFromAnyMcpServer, isFromMcpServer, isGeminiReplayParts, isGoogleLike, isGraphSubagentConfig, isInformativeFadingTier, isIntentLabelProperty, isInterrupted, isLegacyConvertible, isLegacyFadingTier, isLibreChatOpenAIModel, isLikelyContextOverflowError, isOpenAILike, isPresent, isProgrammaticRunnerAutoBound, isProgrammaticRunnerResolvedDirectly, isProviderCancellation, isReasoningContentBlock, isRerankPermutation, isScoreAnswer, isSyntheticProviderContextMessage, isThinkingEnabled, isToolMessage, isZodSchema, joinKeys, labelContentByAgent, locateEdit, makeIsDeferred, makeRequest, mapChatMessagesToStoredMessages, mapStoredMessagesToChatMessages, markTokenCounterCacheCompatible, maskConsumedToolResults, matchesQuery, maxFadingRung, mergeAggregatedHookResults, mergeDecisionSettings, messagesStateReducer, modifyDeltaProperties, newsSchema, nodeExecutionWorld, noneReranker, normalizeBashToolResultsForReplay, normalizeCodeApiRequestError, normalizeSearchResultData, normalizeServerFilter, normalizeSubagentConfigEntries, normalizeSubagentConfigs, normalizeToBashIdentifier, normalizeToPythonIdentifier, outcomeFieldsFromResult, parseBooleanEnv, parseEnvelope, partitionAndMarkAnthropicToolCache, performLocalSearch, preFlightTruncateToolCallInputs, preFlightTruncateToolResults, prepareBashProgrammaticCode, prepareProviderRequest, probe, probeLocalCommandAvailability, probePin, probeRequest, projectAgentContextUsage, projectAnthropicArtifactContent, projectArtifactPayload, projectCacheControlledToolOutputsToText, projectComputerCallOutputsToText, projectOpenAIChatToolMessageContent, projectOpenAIResponsesToolMessageContent, projectOpenAIToolMessageContent, projectOpenRouterToolMessageContent, projectSingleTextToolOutputsToText, projectStructuredToolOutputsToText, projectToolCallInputs, projectToolMessagesForProvider, projectToolStreamContentForProvider, querySchema, rankedEntries, readAnswer, readDecisionUsage, readIntent, readOutcomeFields, readTokenMetadataProperty, redact, registerProvider, removePredecessorHandoffCue, repairOrphanedToolMessages, rerankCost, resetIfNotEmpty, resolveBedrockPromptCacheTtl, resolveCloudflareSandbox, resolveCodeApiAuthHeaders, resolveContextPruningSettings, resolveFadingCaps, resolveFadingTier, resolveFetchProxyAgent, resolveIntraTurnRetainTokens, resolveLocalExecutionConfig, resolveLocalExecutionTools, resolveLocalImplementationNames, resolveLocalToolRegistry, resolveLocalToolsForBinding, resolvePromptCacheTtl, resolveProviderMessageProjectionInvariantMode, resolveSearchOutcome, resolveServerFilters, resolveStreamDelay, resolveStreamLimits, resolveSubagentConfigEntries, resolveSubagentConfigs, resolveSubagentHostArgs, resolveToolOutcome, resolveWorkspacePath, resolveWorkspacePathSafe, restoreGeminiReplayParts, retryAfterMs, runBashAstChecks, runPlainExecution, runPostEditSyntaxCheck, sanitizeOrphanToolBlocks, sanitizeRegex, scoreQuestion, seedFadingTier, selectRuntimeSessionHint, separateSummarizationParameters, serializeMessage, serializeProviderTextProtectionError, serializeToolCallInput, setCommandAvailabilityCacheEntry, setFreshProviderMessageProvenance, setInvalidProviderMessageProvenance, setProviderMessageProvenance, shellQuote, shiftIndexTokenCountMap, shouldBypassProxy, shouldTriggerSummarization, sleep, sliceWithoutSplittingSurrogates, smoothStream, snapshotExecutionIdentity, spawnLocalProcess, splitAssistantTextContentByPhase, splitAtRecencyBoundary, stampSyntheticProviderMessage, strictAlternationProviders, stripAnthropicCacheControl, stripBedrockCacheControl, stripCodeSessionFileSummary, stripIntent, summarizeEvent, supportsBedrockToolCache, syncBudgetDerivedFields, toJsonSchema, toOutcomeReranker, toStoredMessage, toWireQuestion, tokenizeCode, tool, toolResultTypes, toolsCondition, truncateLocalOutput, truncateToolInput, truncateToolResultContent, tryFallbackProviders, unescapeObject, unwrapToolResponse, validateBashCommand, validateCloudflareBashCommand, validateDecisionQuestions, videosSchema, withBreaker, withClientTimeout, withDecisionDeadline, withFallback, withInstructionlessHandoffCue, withIntent, withMessageRole, withoutIntent, wrapPythonForPlainExecution };
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { isAIMessage, isAIMessageChunk, isBaseMessageChunk, isChatMessage, isToolMessage } from "@langchain/core/messages";
|
|
2
|
+
//#region src/messages/stored.ts
|
|
3
|
+
function toStoredMessage(message) {
|
|
4
|
+
if (Object.keys(message.lc_secrets ?? {}).length > 0) throw new Error("SDK native message secrets require an explicit codec");
|
|
5
|
+
const data = {
|
|
6
|
+
...message.lc_kwargs,
|
|
7
|
+
content: message.content,
|
|
8
|
+
additional_kwargs: message.additional_kwargs,
|
|
9
|
+
response_metadata: message.response_metadata,
|
|
10
|
+
id: message.id,
|
|
11
|
+
name: message.name,
|
|
12
|
+
role: isChatMessage(message) ? message.role : void 0,
|
|
13
|
+
tool_call_id: void 0,
|
|
14
|
+
...isAIMessage(message) ? {
|
|
15
|
+
tool_calls: message.tool_calls,
|
|
16
|
+
invalid_tool_calls: message.invalid_tool_calls,
|
|
17
|
+
usage_metadata: message.usage_metadata
|
|
18
|
+
} : {},
|
|
19
|
+
...isBaseMessageChunk(message) && isAIMessageChunk(message) ? { tool_call_chunks: message.tool_call_chunks } : {},
|
|
20
|
+
...isToolMessage(message) ? {
|
|
21
|
+
tool_call_id: message.tool_call_id,
|
|
22
|
+
artifact: message.artifact,
|
|
23
|
+
status: message.status
|
|
24
|
+
} : {}
|
|
25
|
+
};
|
|
26
|
+
return {
|
|
27
|
+
type: message.getType(),
|
|
28
|
+
data
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
//#endregion
|
|
32
|
+
export { toStoredMessage };
|
|
33
|
+
|
|
34
|
+
//# sourceMappingURL=stored.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"stored.mjs","names":[],"sources":["../../../src/messages/stored.ts"],"mappings":";;AAcA,SAAgB,gBAAgB,SAAqC;CACnE,IAAI,OAAO,KAAK,QAAQ,cAAc,CAAC,CAAC,CAAC,CAAC,SAAS,GACjD,MAAM,IAAI,MAAM,sDAAsD;CAExE,MAAM,OAAO;EACX,GAAG,QAAQ;EACX,SAAS,QAAQ;EACjB,mBAAmB,QAAQ;EAC3B,mBAAmB,QAAQ;EAC3B,IAAI,QAAQ;EACZ,MAAM,QAAQ;EACd,MAAM,cAAc,OAAO,IAAI,QAAQ,OAAO,KAAA;EAC9C,cAAc,KAAA;EACd,GAAI,YAAY,OAAO,IACnB;GACA,YAAY,QAAQ;GACpB,oBAAoB,QAAQ;GAC5B,gBAAgB,QAAQ;EAC1B,IACE,CAAC;EACL,GAAI,mBAAmB,OAAO,KAAK,iBAAiB,OAAO,IACvD,EAAE,kBAAkB,QAAQ,iBAAiB,IAC7C,CAAC;EACL,GAAI,cAAc,OAAO,IACrB;GACA,cAAc,QAAQ;GACtB,UAAU,QAAQ;GAClB,QAAQ,QAAQ;EAClB,IACE,CAAC;CACP;CAEA,OAAO;EAAE,MAAM,QAAQ,QAAQ;EAAG;CAAK;AACzC"}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { Part, GenerateContentRequest, GenerateContentResponse, EnhancedGenerateContentResponse } from '@google/generative-ai';
|
|
2
|
+
export declare function formatRequest(input: GenerateContentRequest | string | (string | Part)[]): GenerateContentRequest;
|
|
3
|
+
/** Compatibility helpers promised by the inherited completionWithRetry API. */
|
|
4
|
+
export declare function enhanceResponse(response: GenerateContentResponse): EnhancedGenerateContentResponse;
|
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import { ChatGenerationChunk } from '@langchain/core/outputs';
|
|
2
2
|
import { ChatGoogleGenerativeAI } from '@langchain/google-genai';
|
|
3
|
-
import type { GenerateContentRequest } from '@google/generative-ai';
|
|
3
|
+
import type { GenerateContentRequest, CachedContent, ModelParams, RequestOptions } from '@google/generative-ai';
|
|
4
4
|
import type { CallbackManagerForLLMRun } from '@langchain/core/callbacks/manager';
|
|
5
5
|
import type { BaseMessage } from '@langchain/core/messages';
|
|
6
6
|
import type { GoogleClientOptions } from '@/types';
|
|
7
7
|
export declare class CustomChatGoogleGenerativeAI extends ChatGoogleGenerativeAI {
|
|
8
8
|
_lc_stream_delay: number;
|
|
9
|
+
private transport;
|
|
9
10
|
thinkingConfig?: ChatGoogleGenerativeAI['thinkingConfig'];
|
|
10
11
|
includeServerSideToolInvocations?: boolean;
|
|
11
12
|
/**
|
|
@@ -14,6 +15,7 @@ export declare class CustomChatGoogleGenerativeAI extends ChatGoogleGenerativeAI
|
|
|
14
15
|
/** Gemini 3 and later accept image, audio, video and PDF input. */
|
|
15
16
|
get _isMultimodalModel(): boolean;
|
|
16
17
|
constructor(fields: GoogleClientOptions);
|
|
18
|
+
useCachedContent(cachedContent: CachedContent, modelParams?: ModelParams, requestOptions?: RequestOptions): void;
|
|
17
19
|
static lc_name(): 'LibreChatGoogleGenerativeAI';
|
|
18
20
|
/**
|
|
19
21
|
* Helper function to convert Gemini API usage metadata to LangChain format
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { Part, GenerateContentResult, GenerateContentRequest, GenerateContentResponse, ModelParams, RequestOptions, SingleRequestOptions } from '@google/generative-ai';
|
|
2
|
+
/** Follows LangChainJS's GenerateContentApiHandler fetch/SSE flow, retaining our wire contract. */
|
|
3
|
+
export declare class GoogleTransport {
|
|
4
|
+
private readonly apiKey;
|
|
5
|
+
private readonly params;
|
|
6
|
+
private readonly options;
|
|
7
|
+
private readonly cachedContent?;
|
|
8
|
+
readonly generationConfig: NonNullable<ModelParams['generationConfig']>;
|
|
9
|
+
constructor(apiKey: string, params: ModelParams, options?: RequestOptions, cachedContent?: string | undefined);
|
|
10
|
+
private request;
|
|
11
|
+
generateContent(request: GenerateContentRequest | string | (string | Part)[], options?: SingleRequestOptions): Promise<GenerateContentResult>;
|
|
12
|
+
generateContentStream(request: GenerateContentRequest, options?: SingleRequestOptions): Promise<{
|
|
13
|
+
stream: AsyncGenerator<GenerateContentResponse>;
|
|
14
|
+
}>;
|
|
15
|
+
}
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { ChatGenerationChunk } from '@langchain/core/outputs';
|
|
2
2
|
import { BaseMessage, UsageMetadata } from '@langchain/core/messages';
|
|
3
|
-
import { POSSIBLE_ROLES, type Part, type Content, type EnhancedGenerateContentResponse, type FunctionDeclarationsTool as GoogleGenerativeAIFunctionDeclarationsTool } from '@google/generative-ai';
|
|
3
|
+
import { POSSIBLE_ROLES, type Part, type Content, type GenerateContentResponse, type EnhancedGenerateContentResponse, type FunctionDeclarationsTool as GoogleGenerativeAIFunctionDeclarationsTool } from '@google/generative-ai';
|
|
4
4
|
import type { ChatResult } from '@langchain/core/outputs';
|
|
5
5
|
import { GoogleGenerativeAIToolType } from '../types';
|
|
6
6
|
export declare const _FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY = "__gemini_function_call_thought_signatures__";
|
|
7
|
+
type GoogleResponse = GenerateContentResponse & Partial<EnhancedGenerateContentResponse>;
|
|
7
8
|
/**
|
|
8
9
|
* Executes a function immediately and returns its result.
|
|
9
10
|
* Functional utility similar to an Immediately Invoked Function Expression (IIFE).
|
|
@@ -34,7 +35,7 @@ export declare function rejectsModelTurnPrefill(model?: string): boolean;
|
|
|
34
35
|
export declare function dropUnsupportedModelTurnPrefill<T extends {
|
|
35
36
|
role: string;
|
|
36
37
|
}>(contents: T[] | undefined, model?: string): T[] | undefined;
|
|
37
|
-
export declare function convertResponseContentToChatGenerationChunk(response:
|
|
38
|
+
export declare function convertResponseContentToChatGenerationChunk(response: GoogleResponse, extra: {
|
|
38
39
|
usageMetadata?: UsageMetadata | undefined;
|
|
39
40
|
index: number;
|
|
40
41
|
model?: string;
|
|
@@ -42,8 +43,9 @@ export declare function convertResponseContentToChatGenerationChunk(response: En
|
|
|
42
43
|
/**
|
|
43
44
|
* Maps a Google GenerateContentResult to a LangChain ChatResult
|
|
44
45
|
*/
|
|
45
|
-
export declare function mapGenerateContentResultToChatResult(response:
|
|
46
|
+
export declare function mapGenerateContentResultToChatResult(response: GoogleResponse, extra?: {
|
|
46
47
|
usageMetadata: UsageMetadata | undefined;
|
|
47
48
|
model?: string;
|
|
48
49
|
}): ChatResult;
|
|
49
50
|
export declare function convertToGenerativeAITools(tools: GoogleGenerativeAIToolType[]): GoogleGenerativeAIFunctionDeclarationsTool[];
|
|
51
|
+
export {};
|
|
@@ -40,9 +40,10 @@ export declare function toGenerationSmoothItem(chunk: ChatGenerationChunk, getAt
|
|
|
40
40
|
* callbacks itself — callback-echo consumers would otherwise observe the
|
|
41
41
|
* unsmoothed deltas.
|
|
42
42
|
*/
|
|
43
|
-
export declare function smoothGenerationChunks({ chunks, delayMs, signal, runManager, }: {
|
|
43
|
+
export declare function smoothGenerationChunks({ chunks, delayMs, signal, runManager, abortUpstream, }: {
|
|
44
44
|
chunks: AsyncGenerator<ChatGenerationChunk>;
|
|
45
45
|
delayMs: number;
|
|
46
46
|
signal?: AbortSignal;
|
|
47
47
|
runManager?: CallbackManagerForLLMRun;
|
|
48
|
+
abortUpstream?: () => void;
|
|
48
49
|
}): AsyncGenerator<ChatGenerationChunk>;
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { BaseMessage, StoredMessage } from '@langchain/core/messages';
|
|
2
|
+
/**
|
|
3
|
+
* Native stored-message data without LangChain's JSON-oriented object escaping.
|
|
4
|
+
* Values retain their native types and references: callers must snapshot/encode
|
|
5
|
+
* with their own bounded codec before retaining or transmitting the result.
|
|
6
|
+
*/
|
|
7
|
+
export declare function toStoredMessage(message: BaseMessage): StoredMessage;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@librechat/agents",
|
|
3
|
-
"version": "4.2.
|
|
3
|
+
"version": "4.2.8",
|
|
4
4
|
"reova": {
|
|
5
5
|
"enabled": true,
|
|
6
6
|
"endpoint": "https://telemetry.reo.dev/data"
|
|
@@ -352,6 +352,7 @@
|
|
|
352
352
|
"cheerio": "^1.2.0",
|
|
353
353
|
"diff": "^9.0.0",
|
|
354
354
|
"dotenv": "^16.4.7",
|
|
355
|
+
"eventsource-parser": "^3.1.1",
|
|
355
356
|
"https-proxy-agent": "^7.0.6",
|
|
356
357
|
"mathjs": "^15.2.0",
|
|
357
358
|
"nanoid": "^3.3.18",
|
|
@@ -7,9 +7,6 @@ import {
|
|
|
7
7
|
import {
|
|
8
8
|
isAIMessage,
|
|
9
9
|
isAIMessageChunk,
|
|
10
|
-
isToolMessage,
|
|
11
|
-
isChatMessage,
|
|
12
|
-
isBaseMessageChunk,
|
|
13
10
|
isBaseMessage,
|
|
14
11
|
mapStoredMessagesToChatMessages,
|
|
15
12
|
} from '@langchain/core/messages';
|
|
@@ -40,6 +37,7 @@ import {
|
|
|
40
37
|
} from './model';
|
|
41
38
|
import { modelStreamCallbacks } from './modelStreamCallbacks';
|
|
42
39
|
import { getProviderFamily } from '@/llm/providers';
|
|
40
|
+
import { toStoredMessage } from '@/messages/stored';
|
|
43
41
|
|
|
44
42
|
interface ModelLease {
|
|
45
43
|
charge(bytes: number): void;
|
|
@@ -144,39 +142,6 @@ const requestSchema = z.object({
|
|
|
144
142
|
.optional(),
|
|
145
143
|
});
|
|
146
144
|
|
|
147
|
-
/** Preserve current native fields; BaseMessage.toDict() JSON-coerces structured metadata. */
|
|
148
|
-
function storedMessage(message: BaseMessage): StoredMessage {
|
|
149
|
-
const data = {
|
|
150
|
-
...message.lc_kwargs,
|
|
151
|
-
content: message.content,
|
|
152
|
-
additional_kwargs: message.additional_kwargs,
|
|
153
|
-
response_metadata: message.response_metadata,
|
|
154
|
-
id: message.id,
|
|
155
|
-
name: message.name,
|
|
156
|
-
role: isChatMessage(message) ? message.role : undefined,
|
|
157
|
-
tool_call_id: undefined,
|
|
158
|
-
...(isAIMessage(message)
|
|
159
|
-
? {
|
|
160
|
-
tool_calls: message.tool_calls,
|
|
161
|
-
invalid_tool_calls: message.invalid_tool_calls,
|
|
162
|
-
usage_metadata: message.usage_metadata,
|
|
163
|
-
}
|
|
164
|
-
: {}),
|
|
165
|
-
...(isBaseMessageChunk(message) && isAIMessageChunk(message)
|
|
166
|
-
? { tool_call_chunks: message.tool_call_chunks }
|
|
167
|
-
: {}),
|
|
168
|
-
...(isToolMessage(message)
|
|
169
|
-
? {
|
|
170
|
-
tool_call_id: message.tool_call_id,
|
|
171
|
-
artifact: message.artifact,
|
|
172
|
-
status: message.status,
|
|
173
|
-
}
|
|
174
|
-
: {}),
|
|
175
|
-
};
|
|
176
|
-
// LangChain's StoredMessageData types content as string, but its codec supports native blocks.
|
|
177
|
-
return { type: message.getType(), data } as StoredMessage;
|
|
178
|
-
}
|
|
179
|
-
|
|
180
145
|
function messageBytes(
|
|
181
146
|
messages: readonly BaseMessage[],
|
|
182
147
|
maxBytes: number
|
|
@@ -184,7 +149,7 @@ function messageBytes(
|
|
|
184
149
|
let bytes = 2;
|
|
185
150
|
try {
|
|
186
151
|
for (const message of messages) {
|
|
187
|
-
bytes += serializeNativeValue(
|
|
152
|
+
bytes += serializeNativeValue(toStoredMessage(message)).byteLength + 1;
|
|
188
153
|
if (bytes > maxBytes) throw new HostModelServiceError('overflow');
|
|
189
154
|
}
|
|
190
155
|
return bytes;
|
|
@@ -355,7 +320,7 @@ export function createHostModelService(options: {
|
|
|
355
320
|
if (bytes > limits.maxRequestBytes)
|
|
356
321
|
throw new HostModelServiceError('overflow');
|
|
357
322
|
for (const message of value.messages) {
|
|
358
|
-
const serialized = serializeNativeValue(
|
|
323
|
+
const serialized = serializeNativeValue(toStoredMessage(message));
|
|
359
324
|
const added = serialized.byteLength + 1;
|
|
360
325
|
bytes += added;
|
|
361
326
|
if (bytes > limits.maxRequestBytes)
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import {
|
|
2
|
+
FinishReason,
|
|
3
|
+
GoogleGenerativeAIRequestInputError,
|
|
4
|
+
GoogleGenerativeAIResponseError,
|
|
5
|
+
} from '@google/generative-ai';
|
|
6
|
+
import type {
|
|
7
|
+
Part,
|
|
8
|
+
FunctionCall,
|
|
9
|
+
GenerateContentRequest,
|
|
10
|
+
GenerateContentResponse,
|
|
11
|
+
EnhancedGenerateContentResponse,
|
|
12
|
+
} from '@google/generative-ai';
|
|
13
|
+
|
|
14
|
+
export function formatRequest(
|
|
15
|
+
input: GenerateContentRequest | string | (string | Part)[]
|
|
16
|
+
): GenerateContentRequest {
|
|
17
|
+
if (typeof input !== 'string' && !Array.isArray(input)) return input;
|
|
18
|
+
const parts: Part[] = [];
|
|
19
|
+
let functionParts = 0;
|
|
20
|
+
for (const value of typeof input === 'string' ? [input] : input) {
|
|
21
|
+
const part = typeof value === 'string' ? { text: value } : value;
|
|
22
|
+
if ('functionResponse' in part) functionParts++;
|
|
23
|
+
parts.push(part);
|
|
24
|
+
}
|
|
25
|
+
if (parts.length === 0) {
|
|
26
|
+
throw new GoogleGenerativeAIRequestInputError(
|
|
27
|
+
'No content is provided for sending chat message.'
|
|
28
|
+
);
|
|
29
|
+
}
|
|
30
|
+
if (functionParts !== 0 && functionParts !== parts.length) {
|
|
31
|
+
throw new GoogleGenerativeAIRequestInputError(
|
|
32
|
+
'Within a single message, FunctionResponse cannot be mixed with other types of part.'
|
|
33
|
+
);
|
|
34
|
+
}
|
|
35
|
+
return {
|
|
36
|
+
contents: [{ role: functionParts > 0 ? 'function' : 'user', parts }],
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Compatibility helpers promised by the inherited completionWithRetry API. */
|
|
41
|
+
export function enhanceResponse(
|
|
42
|
+
response: GenerateContentResponse
|
|
43
|
+
): EnhancedGenerateContentResponse {
|
|
44
|
+
function parts(): Part[] {
|
|
45
|
+
const candidate = response.candidates?.[0];
|
|
46
|
+
if (candidate == null && response.promptFeedback != null) {
|
|
47
|
+
throw new GoogleGenerativeAIResponseError(
|
|
48
|
+
'Response was blocked',
|
|
49
|
+
response
|
|
50
|
+
);
|
|
51
|
+
}
|
|
52
|
+
if (
|
|
53
|
+
candidate?.finishReason === FinishReason.SAFETY ||
|
|
54
|
+
candidate?.finishReason === FinishReason.RECITATION ||
|
|
55
|
+
candidate?.finishReason === FinishReason.LANGUAGE
|
|
56
|
+
) {
|
|
57
|
+
throw new GoogleGenerativeAIResponseError(
|
|
58
|
+
`Candidate was blocked due to ${candidate.finishReason}`,
|
|
59
|
+
response
|
|
60
|
+
);
|
|
61
|
+
}
|
|
62
|
+
const content = candidate?.content;
|
|
63
|
+
return content?.parts ?? [];
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function functionCalls(): FunctionCall[] | undefined {
|
|
67
|
+
const calls: FunctionCall[] = [];
|
|
68
|
+
for (const part of parts()) {
|
|
69
|
+
if (part.functionCall) calls.push(part.functionCall);
|
|
70
|
+
}
|
|
71
|
+
return calls.length > 0 ? calls : undefined;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
return Object.assign(response, {
|
|
75
|
+
text(): string {
|
|
76
|
+
let text = '';
|
|
77
|
+
for (const part of parts()) {
|
|
78
|
+
text += part.text ?? '';
|
|
79
|
+
if (part.executableCode) {
|
|
80
|
+
text += `\n\`\`\`${part.executableCode.language}\n${part.executableCode.code}\n\`\`\`\n`;
|
|
81
|
+
}
|
|
82
|
+
if (part.codeExecutionResult) {
|
|
83
|
+
text += `\n\`\`\`\n${part.codeExecutionResult.output}\n\`\`\`\n`;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return text;
|
|
87
|
+
},
|
|
88
|
+
functionCall: (): FunctionCall | undefined => functionCalls()?.[0],
|
|
89
|
+
functionCalls,
|
|
90
|
+
});
|
|
91
|
+
}
|
package/src/llm/google/index.ts
CHANGED
|
@@ -5,10 +5,13 @@ import { ChatGoogleGenerativeAI } from '@langchain/google-genai';
|
|
|
5
5
|
import { getEnvironmentVariable } from '@langchain/core/utils/env';
|
|
6
6
|
import {
|
|
7
7
|
FunctionCallingMode,
|
|
8
|
-
|
|
8
|
+
GoogleGenerativeAIRequestInputError,
|
|
9
9
|
} from '@google/generative-ai';
|
|
10
10
|
import type {
|
|
11
11
|
GenerateContentRequest,
|
|
12
|
+
CachedContent,
|
|
13
|
+
ModelParams,
|
|
14
|
+
RequestOptions,
|
|
12
15
|
SafetySetting,
|
|
13
16
|
ToolConfig,
|
|
14
17
|
} from '@google/generative-ai';
|
|
@@ -25,6 +28,7 @@ import {
|
|
|
25
28
|
} from './utils/common';
|
|
26
29
|
import { smoothGenerationChunks } from '@/llm/stream/chunkAdapters';
|
|
27
30
|
import { resolveStreamDelay } from '@/llm/stream/smoother';
|
|
31
|
+
import { GoogleTransport } from './transport';
|
|
28
32
|
|
|
29
33
|
type GoogleToolConfigWithServerSideInvocations = ToolConfig & {
|
|
30
34
|
includeServerSideToolInvocations?: boolean;
|
|
@@ -40,6 +44,7 @@ type GoogleToolConfigWithServerSideInvocations = ToolConfig & {
|
|
|
40
44
|
|
|
41
45
|
export class CustomChatGoogleGenerativeAI extends ChatGoogleGenerativeAI {
|
|
42
46
|
_lc_stream_delay: number;
|
|
47
|
+
private transport: GoogleTransport;
|
|
43
48
|
thinkingConfig?: ChatGoogleGenerativeAI['thinkingConfig'];
|
|
44
49
|
includeServerSideToolInvocations?: boolean;
|
|
45
50
|
|
|
@@ -126,8 +131,8 @@ export class CustomChatGoogleGenerativeAI extends ChatGoogleGenerativeAI {
|
|
|
126
131
|
this.streaming = fields.streaming ?? this.streaming;
|
|
127
132
|
this.json = fields.json;
|
|
128
133
|
|
|
129
|
-
|
|
130
|
-
|
|
134
|
+
this.transport = new GoogleTransport(
|
|
135
|
+
this.apiKey,
|
|
131
136
|
{
|
|
132
137
|
model: this.model,
|
|
133
138
|
safetySettings: this.safetySettings as SafetySetting[],
|
|
@@ -148,9 +153,64 @@ export class CustomChatGoogleGenerativeAI extends ChatGoogleGenerativeAI {
|
|
|
148
153
|
customHeaders: fields.customHeaders,
|
|
149
154
|
}
|
|
150
155
|
);
|
|
156
|
+
// @ts-ignore - The parent keeps its transport private.
|
|
157
|
+
this.client = this.transport;
|
|
151
158
|
this.streamUsage = fields.streamUsage ?? this.streamUsage;
|
|
152
159
|
}
|
|
153
160
|
|
|
161
|
+
useCachedContent(
|
|
162
|
+
cachedContent: CachedContent,
|
|
163
|
+
modelParams?: ModelParams,
|
|
164
|
+
requestOptions?: RequestOptions
|
|
165
|
+
): void {
|
|
166
|
+
if (this.apiKey == null || this.apiKey === '') return;
|
|
167
|
+
if (
|
|
168
|
+
cachedContent.name == null ||
|
|
169
|
+
cachedContent.name === '' ||
|
|
170
|
+
cachedContent.model == null ||
|
|
171
|
+
cachedContent.model === ''
|
|
172
|
+
) {
|
|
173
|
+
throw new GoogleGenerativeAIRequestInputError(
|
|
174
|
+
'Cached content must contain `name` and `model` fields.'
|
|
175
|
+
);
|
|
176
|
+
}
|
|
177
|
+
if (
|
|
178
|
+
modelParams?.model != null &&
|
|
179
|
+
modelParams.model !== '' &&
|
|
180
|
+
modelParams.model.replace(/^models\//, '') !==
|
|
181
|
+
cachedContent.model.replace(/^models\//, '')
|
|
182
|
+
) {
|
|
183
|
+
throw new GoogleGenerativeAIRequestInputError(
|
|
184
|
+
'Different model specified in modelParams and cachedContent.'
|
|
185
|
+
);
|
|
186
|
+
}
|
|
187
|
+
if (
|
|
188
|
+
modelParams?.systemInstruction != null &&
|
|
189
|
+
modelParams.systemInstruction !== '' &&
|
|
190
|
+
cachedContent.systemInstruction != null &&
|
|
191
|
+
cachedContent.systemInstruction !== '' &&
|
|
192
|
+
modelParams.systemInstruction !== cachedContent.systemInstruction
|
|
193
|
+
) {
|
|
194
|
+
throw new GoogleGenerativeAIRequestInputError(
|
|
195
|
+
'Different systemInstruction specified in modelParams and cachedContent.'
|
|
196
|
+
);
|
|
197
|
+
}
|
|
198
|
+
this.transport = new GoogleTransport(
|
|
199
|
+
this.apiKey,
|
|
200
|
+
{
|
|
201
|
+
...modelParams,
|
|
202
|
+
model: cachedContent.model,
|
|
203
|
+
systemInstruction: cachedContent.systemInstruction,
|
|
204
|
+
tools: cachedContent.tools,
|
|
205
|
+
toolConfig: cachedContent.toolConfig,
|
|
206
|
+
},
|
|
207
|
+
requestOptions,
|
|
208
|
+
cachedContent.name
|
|
209
|
+
);
|
|
210
|
+
// @ts-ignore - The parent keeps its transport private.
|
|
211
|
+
this.client = this.transport;
|
|
212
|
+
}
|
|
213
|
+
|
|
154
214
|
static lc_name(): 'LibreChatGoogleGenerativeAI' {
|
|
155
215
|
return 'LibreChatGoogleGenerativeAI';
|
|
156
216
|
}
|
|
@@ -212,15 +272,6 @@ export class CustomChatGoogleGenerativeAI extends ChatGoogleGenerativeAI {
|
|
|
212
272
|
options?: this['ParsedCallOptions']
|
|
213
273
|
): Omit<GenerateContentRequest, 'contents'> {
|
|
214
274
|
const params = super.invocationParams(options);
|
|
215
|
-
if (this.thinkingConfig) {
|
|
216
|
-
/** @ts-ignore */
|
|
217
|
-
this.client.generationConfig = {
|
|
218
|
-
/** @ts-ignore */
|
|
219
|
-
...this.client.generationConfig,
|
|
220
|
-
/** @ts-ignore */
|
|
221
|
-
thinkingConfig: this.thinkingConfig,
|
|
222
|
-
};
|
|
223
|
-
}
|
|
224
275
|
if (
|
|
225
276
|
this.includeServerSideToolInvocations === true &&
|
|
226
277
|
Array.isArray(params.tools) &&
|
|
@@ -258,41 +309,38 @@ export class CustomChatGoogleGenerativeAI extends ChatGoogleGenerativeAI {
|
|
|
258
309
|
this.model
|
|
259
310
|
);
|
|
260
311
|
let actualPrompt = prompt;
|
|
312
|
+
let systemInstruction: GenerateContentRequest['systemInstruction'];
|
|
261
313
|
if (prompt?.[0].role === 'system') {
|
|
262
|
-
|
|
263
|
-
/** @ts-ignore */
|
|
264
|
-
this.client.systemInstruction = systemInstruction;
|
|
314
|
+
[systemInstruction] = prompt;
|
|
265
315
|
actualPrompt = prompt.slice(1);
|
|
266
316
|
}
|
|
267
317
|
actualPrompt = dropUnsupportedModelTurnPrefill(actualPrompt, this.model);
|
|
268
318
|
const parameters = this.invocationParams(options);
|
|
269
319
|
const request = {
|
|
270
320
|
...parameters,
|
|
271
|
-
|
|
321
|
+
...(systemInstruction != null ? { systemInstruction } : {}),
|
|
322
|
+
contents: actualPrompt ?? [],
|
|
272
323
|
};
|
|
273
324
|
|
|
274
325
|
const res = await this.caller.callWithOptions(
|
|
275
326
|
{ signal: options.signal },
|
|
276
327
|
async () =>
|
|
277
|
-
|
|
278
|
-
this.client.generateContent(request)
|
|
328
|
+
this.transport.generateContent(request, { signal: options.signal })
|
|
279
329
|
);
|
|
280
330
|
|
|
281
331
|
const response = res.response;
|
|
282
332
|
const usageMetadata = this._convertToUsageMetadata(
|
|
283
|
-
|
|
284
|
-
response.usageMetadata,
|
|
333
|
+
response.usageMetadata as GeminiApiUsageMetadata | undefined,
|
|
285
334
|
this.model
|
|
286
335
|
);
|
|
287
336
|
|
|
288
|
-
/** @ts-ignore */
|
|
289
337
|
const generationResult = mapGenerateContentResultToChatResult(response, {
|
|
290
338
|
usageMetadata,
|
|
291
339
|
model: this.model,
|
|
292
340
|
});
|
|
293
341
|
|
|
294
342
|
await runManager?.handleLLMNewToken(
|
|
295
|
-
generationResult.generations[0]
|
|
343
|
+
generationResult.generations[0]?.text || '',
|
|
296
344
|
undefined,
|
|
297
345
|
undefined,
|
|
298
346
|
undefined,
|
|
@@ -307,12 +355,24 @@ export class CustomChatGoogleGenerativeAI extends ChatGoogleGenerativeAI {
|
|
|
307
355
|
options: this['ParsedCallOptions'],
|
|
308
356
|
runManager?: CallbackManagerForLLMRun
|
|
309
357
|
): AsyncGenerator<ChatGenerationChunk> {
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
358
|
+
const controller = new AbortController();
|
|
359
|
+
const upstreamSignal = options.signal
|
|
360
|
+
? AbortSignal.any([options.signal, controller.signal])
|
|
361
|
+
: controller.signal;
|
|
362
|
+
try {
|
|
363
|
+
yield* smoothGenerationChunks({
|
|
364
|
+
chunks: this._streamProviderChunks(messages, {
|
|
365
|
+
...options,
|
|
366
|
+
signal: upstreamSignal,
|
|
367
|
+
}),
|
|
368
|
+
delayMs: this._lc_stream_delay,
|
|
369
|
+
signal: options.signal,
|
|
370
|
+
runManager,
|
|
371
|
+
abortUpstream: () => controller.abort(),
|
|
372
|
+
});
|
|
373
|
+
} finally {
|
|
374
|
+
controller.abort();
|
|
375
|
+
}
|
|
316
376
|
}
|
|
317
377
|
|
|
318
378
|
private async *_streamProviderChunks(
|
|
@@ -326,23 +386,24 @@ export class CustomChatGoogleGenerativeAI extends ChatGoogleGenerativeAI {
|
|
|
326
386
|
this.model
|
|
327
387
|
);
|
|
328
388
|
let actualPrompt = prompt;
|
|
389
|
+
let systemInstruction: GenerateContentRequest['systemInstruction'];
|
|
329
390
|
if (prompt?.[0].role === 'system') {
|
|
330
|
-
|
|
331
|
-
/** @ts-ignore */
|
|
332
|
-
this.client.systemInstruction = systemInstruction;
|
|
391
|
+
[systemInstruction] = prompt;
|
|
333
392
|
actualPrompt = prompt.slice(1);
|
|
334
393
|
}
|
|
335
394
|
actualPrompt = dropUnsupportedModelTurnPrefill(actualPrompt, this.model);
|
|
336
395
|
const parameters = this.invocationParams(options);
|
|
337
396
|
const request = {
|
|
338
397
|
...parameters,
|
|
339
|
-
|
|
398
|
+
...(systemInstruction != null ? { systemInstruction } : {}),
|
|
399
|
+
contents: actualPrompt ?? [],
|
|
340
400
|
};
|
|
341
401
|
const stream = await this.caller.callWithOptions(
|
|
342
402
|
{ signal: options.signal },
|
|
343
403
|
async () => {
|
|
344
|
-
|
|
345
|
-
|
|
404
|
+
const { stream } = await this.transport.generateContentStream(request, {
|
|
405
|
+
signal: options.signal,
|
|
406
|
+
});
|
|
346
407
|
return stream;
|
|
347
408
|
}
|
|
348
409
|
);
|