summaryrefslogtreecommitdiff
path: root/packages/core/src/utils/partUtils.ts
diff options
context:
space:
mode:
Diffstat (limited to 'packages/core/src/utils/partUtils.ts')
-rw-r--r--packages/core/src/utils/partUtils.ts85
1 files changed, 85 insertions, 0 deletions
diff --git a/packages/core/src/utils/partUtils.ts b/packages/core/src/utils/partUtils.ts
new file mode 100644
index 00000000..c6bf098d
--- /dev/null
+++ b/packages/core/src/utils/partUtils.ts
@@ -0,0 +1,85 @@
+/**
+ * @license
+ * Copyright 2025 Google LLC
+ * SPDX-License-Identifier: Apache-2.0
+ */
+
+import { GenerateContentResponse, PartListUnion, Part } from '@google/genai';
+
+/**
+ * Converts a PartListUnion into a string.
+ * If verbose is true, includes summary representations of non-text parts.
+ */
+export function partToString(
+ value: PartListUnion,
+ options?: { verbose?: boolean },
+): string {
+ if (!value) {
+ return '';
+ }
+ if (typeof value === 'string') {
+ return value;
+ }
+ if (Array.isArray(value)) {
+ return value.map((part) => partToString(part, options)).join('');
+ }
+
+ // Cast to Part, assuming it might contain project-specific fields
+ const part = value as Part & {
+ videoMetadata?: unknown;
+ thought?: string;
+ codeExecutionResult?: unknown;
+ executableCode?: unknown;
+ };
+
+ if (options?.verbose) {
+ if (part.videoMetadata !== undefined) {
+ return `[Video Metadata]`;
+ }
+ if (part.thought !== undefined) {
+ return `[Thought: ${part.thought}]`;
+ }
+ if (part.codeExecutionResult !== undefined) {
+ return `[Code Execution Result]`;
+ }
+ if (part.executableCode !== undefined) {
+ return `[Executable Code]`;
+ }
+
+ // Standard Part fields
+ if (part.fileData !== undefined) {
+ return `[File Data]`;
+ }
+ if (part.functionCall !== undefined) {
+ return `[Function Call: ${part.functionCall.name}]`;
+ }
+ if (part.functionResponse !== undefined) {
+ return `[Function Response: ${part.functionResponse.name}]`;
+ }
+ if (part.inlineData !== undefined) {
+ return `<${part.inlineData.mimeType}>`;
+ }
+ }
+
+ return part.text ?? '';
+}
+
+export function getResponseText(
+ response: GenerateContentResponse,
+): string | null {
+ if (response.candidates && response.candidates.length > 0) {
+ const candidate = response.candidates[0];
+
+ if (
+ candidate.content &&
+ candidate.content.parts &&
+ candidate.content.parts.length > 0
+ ) {
+ return candidate.content.parts
+ .filter((part) => part.text)
+ .map((part) => part.text)
+ .join('');
+ }
+ }
+ return null;
+}