Para ver una guía detallada sobre cómo contar tokens con la API de Gemini y cómo se cuentan las imágenes, el audio y el video, consulta la guía de recuento de tokens y la receta del manual de soluciones incluida.
Método: models.countTokens
- Extremo
- Parámetros de ruta de acceso
- Cuerpo de la solicitud
- Cuerpo de la respuesta
- Permisos de autorización
- Ejemplo de solicitud
- GenerateContentRequest
Ejecuta el tokenizador de un modelo en la entrada Content
y muestra el recuento de tokens. Consulta la guía de tokens para obtener más información al respecto.
Extremo
publicación
https://generativelanguage.googleapis.com/v1beta/{model=models/*}:countTokens
Parámetros de ruta
model
string
Obligatorio. El nombre del recurso del modelo. Esto sirve como un ID para que use el modelo.
Este nombre debe coincidir con el nombre de modelo que muestra el método models.list
.
Formato: models/{model}
Toma la forma models/{model}
.
Cuerpo de la solicitud
El cuerpo de la solicitud contiene datos con la siguiente estructura:
contents[]
object (Content
)
Opcional. La entrada proporcionada al modelo como instrucción. Este campo se ignora cuando se configura generateContentRequest
.
generateContentRequest
object (GenerateContentRequest
)
Opcional. La entrada general otorgada a Model
. Esto incluye la instrucción y otra información de dirección del modelo, como las instrucciones del sistema o declaraciones de funciones para las llamadas a funciones. Los objetos Model
, Content
y generateContentRequest
son excluyentes mutuamente. Puedes enviar Model
+ Content
o generateContentRequest
, pero nunca ambos.
Ejemplo de solicitud
Texto
Python
Node.js
Go
Una caracola
Kotlin
Swift
Dart
Java
Chat
Python
Node.js
Go
Una caracola
Kotlin
Swift
Dart
Java
Contenido multimedia intercalado
Python
Node.js
Go
Una caracola
Kotlin
Swift
Dart
Java
Video
Python
Node.js
Go
Una caracola
Python
Caché
Python
Node.js
Go
Instrucción del sistema
Python
Node.js
Go
Kotlin
Swift
Dart
Java
Herramientas
Python
Node.js
Kotlin
Swift
Dart
Java
Cuerpo de la respuesta
Una respuesta de models.countTokens
.
Muestra el tokenCount
del modelo para el prompt
.
Si se ejecuta correctamente, el cuerpo de la respuesta contendrá datos con la siguiente estructura:
totalTokens
integer
La cantidad de tokens en los que Model
asigna un token a prompt
. Siempre no es negativo.
Representación JSON |
---|
{ "totalTokens": integer } |
GenerateContentRequest
Solicitud para generar una finalización a partir del modelo.
model
string
Obligatorio. Es el nombre de Model
que se usará para generar la finalización.
Formato: name=models/{model}
.
contents[]
object (Content
)
Obligatorio. El contenido de la conversación actual con el modelo.
Para consultas de un solo turno, esta es una instancia única. Para consultas de varios turnos, como chat, es un campo repetido que contiene el historial de la conversación y la última solicitud.
tools[]
object (Tool
)
Opcional. Una lista de Tools
que Model
puede usar para generar la siguiente respuesta.
Un Tool
es un fragmento de código que permite que el sistema interactúe con sistemas externos para realizar una acción, o un conjunto de acciones, fuera del conocimiento y el alcance de Model
. Los elementos Tool
admitidos son Function
y codeExecution
. Consulta las guías Llamada a función y Ejecución de código para obtener más información.
toolConfig
object (ToolConfig
)
Opcional. Configuración de herramientas para cualquier Tool
especificado en la solicitud. Consulta la guía de llamada a funciones para ver un ejemplo de uso.
safetySettings[]
object (SafetySetting
)
Opcional. Una lista de instancias de SafetySetting
únicas para bloquear contenido no seguro.
Esto se aplicará de manera forzosa en GenerateContentRequest.contents
y GenerateContentResponse.candidates
. No debe haber más de un parámetro de configuración para cada tipo de SafetyCategory
. La API bloqueará cualquier contenido y respuesta que no cumpla con los umbrales establecidos por esta configuración. Esta lista anula la configuración predeterminada para cada SafetyCategory
especificado en SafetySettings. Si no hay un SafetySetting
para un SafetyCategory
determinado proporcionado en la lista, la API usará la configuración de seguridad predeterminada para esa categoría. Se admiten las categorías de daños HARM_CATEGORY_HATE_SPEECH, HARM_CATEGORY_SEXUALLY_EXPLICIT, HARM_CATEGORY_DANGEROUS_CONTENT, HARM_CATEGORY_HARASSMENT. Consulta la guía para obtener información detallada sobre la configuración de seguridad disponible. Además, consulta la Guía de seguridad para aprender a incorporar consideraciones de seguridad en tus aplicaciones de IA.
systemInstruction
object (Content
)
Opcional. El desarrollador establece las instrucciones del sistema. Actualmente, es solo texto.
generationConfig
object (GenerationConfig
)
Opcional. Opciones de configuración para la generación y la salida de modelos.
cachedContent
string
Opcional. Es el nombre del contenido almacenado en caché para usar como contexto y entregar la predicción. Formato: cachedContents/{cachedContent}
Representación JSON |
---|
{ "model": string, "contents": [ { object ( |