---
title: "cosmos-reason1-7b"
publisher: "nvidia"
type: "endpoint"
updated: "2025-08-11T14:42:14.657Z"
description: "Reasoning vision language model (VLM) for physical AI and robotics."
canonical: "https://build.nvidia.com/nvidia/cosmos-reason1-7b"
---

# Cosmos-Reason1-7B Overview

## Description
NVIDIA Cosmos Reason – an open, customizable, 7B-parameter reasoning vision language model (VLM) for physical AI and robotics - enables robots and vision AI agents to reason like humans, using prior knowledge, physics understanding and common sense to understand and act in the real world. This model understands space, time, and fundamental physics, and can serve as a planning model to reason what steps an embodied agent might take next.

Cosmos Reason excels at navigating the long tail of diverse scenarios of the physical world with spatial-temporal understanding. Cosmos Reason is post-trained with physical common sense and embodied reasoning data with supervised fine-tuning and reinforcement learning. It uses chain-of-thought reasoning capabilities to understand world dynamics without human annotations.

Given a video and a text prompt, the model first converts the video into tokens using a vision encoder and a special translator called a projector. These video tokens are combined with the text prompt and fed into the core model, which uses a mix of LLM modules and techniques. This enables the model to think step-by-step and provide detailed, logical responses.

Cosmos Reason can be used for robotics and physical AI applications including:

Data curation and annotation — Enable developers to automate high-quality curation and annotation of massive, diverse training datasets.
Robot planning and reasoning — Act as the brain for deliberate, methodical decision-making in a robot vision language action (VLA) model. Now robots such as humanoids and autonomous vehicles can interpret environments and given complex commands, break them down into tasks and execute them using common sense, even in unfamiliar environments.
Video analytics AI agents — Extract valuable insights and perform root-cause analysis on massive volumes of video data. These agents can be used to analyze and understand recorded or live video streams across city and industrial operations.

The model is ready for commercial use.

**Model Developer:** NVIDIA

## License and Terms of Use:
**GOVERNING TERMS:** This trial service is governed by the [NVIDIA API Trial Terms of Service](https://assets.ngc.nvidia.com/products/api-catalog/legal/NVIDIA%20API%20Trial%20Terms%20of%20Service.pdf). Use of the model is governed by the [NVIDIA Open Model License Agreement](https://www.nvidia.com/en-us/agreements/enterprise-software/nvidia-open-model-license/).Additional Information: [Apache License 2.0](https://huggingface.co/datasets/choosealicense/licenses/blob/main/markdown/apache-2.0.md)

Models are commercially usable.

You are free to create and distribute Derivative Models.
NVIDIA does not claim ownership to any outputs generated using the Models or Derivative Models.

**Important Note**: If You bypass, disable, reduce the efficacy of, or circumvent any technical limitation, safety guardrail or associated safety guardrail hyperparameter, encryption, security, digital rights management, or authentication mechanism (collectively “Guardrail”) contained in the Model without a substantially similar Guardrail appropriate for your use case, your rights under this Agreement [NVIDIA Open Model License](https://www.nvidia.com/en-us/agreements/enterprise-software/nvidia-open-model-license) will automatically terminate.

## Deployment Geography:

Global

## Use Case:
Robotics engineers and AI researchers developing embodied agents—such as autonomous vehicles and robotic systems—would use Physical AI to equip their machines with spatiotemporal reasoning and a fundamental physics understanding for navigation, manipulation, and decision-making tasks

### Reference: [Technical Paper](https://arxiv.org/pdf/2503.15558)

## Release Date:
**Build.NVIDIA.com** 08/11/2025 via [link](https://build.nvidia.com/nvidia/cosmos-reason1-7b) 

**Huggingface** 08/01/2025 via [link](https://huggingface.co/nvidia/Cosmos-Reason1-7B/commit/0caf724f837efea5e25bf6d5818dcdeec0a36604) 

## Model Architecture:
**Architecture Type:** A Multi-modal LLM consists of a Vision Transformer (ViT) for vision encoder and a Dense Transformer model for LLM. 

**Network Architecture:** Qwen2.5-VL-7B-Instruct. 

Cosmos-Reason-7B is post-trained based on [Qwen2.5-VL-7B-Instruct](https://huggingface.co/Qwen/Qwen2.5-VL-7B-Instruct) and follows the same model architecture.<br>

**Number of model parameters:**

Cosmos-Reason1-7B:

- Vision Transformer (ViT): 675.76M (675,759,104)
- Language Model (LLM): 7.07B (7,070,619,136)
- Other components (output projection layer): 545.00M (544,997,376)

**Computational Load:**
- Cumulative Compute: 3.2603016e+21 FLOPS
- Estimated Energy and Emissions for Model Training:
- Total kWh = 16658432
- Total Emissions (tCO2e) = 5380.674

### Input:
**Input Types:** Text, Video <br>
**Input Formats:** Text:String, Video:MP4<br>
**Input Parameters:** Text: One Dimensional (1D), Video:Three-dimensional (3D) <br>
**Other Input Properties:** 
- Use FPS=4 for input video to match the training setup.
- Append `Answer the question in the following format: <think>\nyour reasoning\n</think>\n\n<answer>\nyour answer\n</answer>.` in the system prompt to encourage long chain-of-thought reasoning response.

<br>

**Input Context Length (ISL):** 128K <br>

### Output:
**Output Type:** Text <br>
**Output Format:** String <br>
**Output Parameters:** One Dimensional (1D) <br>
**Other Output Properties:** 
- Recommend using 4096 or more output max tokens to avoid truncation of long chain-of-thought response.

- Our AI model recognizes timestamps added at the bottom of each frame for accurate temporal localization.

- Our AI models are designed and/or optimized to run on NVIDIA GPU-accelerated systems. By leveraging NVIDIA's hardware (e.g. GPU cores) and software frameworks (e.g., CUDA libraries), the model achieves faster training and inference times compared to CPU-only solutions.__

## Software Integration:
**Runtime Engines:**
- vLLM

**Supported Hardware:**
- **NVIDIA Blackwell:** <br>
- **NVIDIA Hopper:**  <br>

## Training, Testing, and Evaluation Datasets:
**[05/17/2025](https://huggingface.co/nvidia/Cosmos-Reason1-7B#05172025)**

Please see our [technical paper](https://arxiv.org/pdf/2503.15558) for detailed evaluations on physical common sense and embodied reasoning. Part of the evaluation datasets are released under [Cosmos-Reason1-Benchmark](https://huggingface.co/datasets/nvidia/Cosmos-Reason1-Benchmark). The embodied reasoning datasets and benchmarks focus on the following areas: robotics (RoboVQA, BridgeDataV2, Agibot, RobFail), ego-centric human demonstration (HoloAssist), and Autonomous Vehicle (AV) driving video data. The AV dataset is collected and annotated by NVIDIA.

All datasets go through the data annotation process described in the technical paper to prepare training and evaluation data and annotations.

**[08/01/2025](https://huggingface.co/nvidia/Cosmos-Reason1-7B#08012025)**

We enhance the model capability with the augmented training data. PLM-Video-Human and Nexar are used to enable dense temporal captioning. Describe Anything is added to enhance a set of mark (SoM) prompting. We enrich data in intelligent transportation systems (ITS) and warehouse applications. 

Lastly, Visual Critics dataset contains a collection of AI generated videos from Cosmos-Predict2 and Wan2.1 with human annotations to describe the physical correctness in AI videos.

### Training Dataset

- Data Modalities: Video, Text
- Text Training Data Size: Not specified (included in multimodal inputs)
- Video Training Data Size: Less than 10,000 Hours (~2M video-text pairs in SFT + RL datasets)

**Data Collection Method by dataset:**

- RoboVQA: Hybrid: Automatic/Sensors
- BridgeDataV2: Automatic/Sensors
- AgiBot: Automatic/Sensors
- RoboFail: Automatic/Sensors
- HoloAssist: Human
- AV: Automatic/Sensors
- PLM-Video-Human: Human
- Nexar: Automatic/Sensors
- Describe Anything: Human
- ITS / Warehouse: Human, Automatic
- Visual Critics: Automatic

**Labeling Method by dataset:**

- RoboVQA: Hybrid: Human,Automated
- BridgeDataV2: Hybrid: Human,Automated
- AgiBot: Hybrid: Human,Automated
- RoboFail: Hybrid: Human,Automated
- HoloAssist: Hybrid: Human,Automated
- AV: Hybrid: Human,Automated
- PLM-Video-Human: Human,Automated
- Nexar: Human
- Describe Anything: Human,Automated
- ITS / Warehouse: Human, Automated
- Visual Critics: Human,Automated

### Evaluation Dataset

- RoboVQA: Hybrid: Automatic/Sensors
- BridgeDataV2: Automatic/Sensors
- AgiBot: Automatic/Sensors
- RoboFail: Automatic/Sensors
- HoloAssist: Human
- AV: Automatic/Sensors

**Labeling Method by dataset:**

- RoboVQA: Hybrid: Human,Automated
- BridgeDataV2: Hybrid: Human,Automated
- AgiBot: Hybrid: Human,Automated
- RoboFail: Hybrid: Human,Automated
- HoloAssist: Hybrid: Human,Automated
- AV: Hybrid: Human,Automated

**Evaluation Benchmark Results:**

We report the model accuracy on the embodied reasoning benchmark introduced in Cosmos-Reason1. The results differ from those presented in Table 9 due to additional training aimed at supporting a broader range of Physical AI tasks beyond the benchmark.

#### Evaluation Results

| Dataset | RoboVQA | AV | BridgeDataV2 | Agibot | HoloAssist | RoboFail | Average |
|---------|---------|----|--------------|--------|------------|----------|---------|
| Accuracy | 87.3 | 70.8 | 63.7 | 48.9 | 62.7 | 57.2 | 65.1 |
---

## Dataset Format
Modality: Video (mp4) and Text

## Dataset Quantification

**[05/17/2025](https://huggingface.co/nvidia/Cosmos-Reason1-7B#05172025-1)**

We release the embodied reasoning data and benchmarks. Each data sample is a pair of video and text. The text annotations include understanding and reasoning annotations described in the Cosmos-Reason1 paper. Each video may have multiple text annotations. The quantity of the video and text pairs is described in the table below. The AV data is currently unavailable and will be uploaded soon!

| Dataset Type | RoboVQA | AV | BridgeDataV2 | Agibot | HoloAssist | RoboFail | Total Storage Size |
|--------------|---------|----|--------------|--------|------------|----------|-------------------|
| SFT Data | 1.14m | 24.7k | 258k | 38.9k | 273k | N/A | 300.6GB |
| RL Data | 252 | 200 | 240 | 200 | 200 | N/A | 2.6GB |
| Benchmark Data | 110 | 100 | 100 | 100 | 100 | 100 | 1.5GB |

We release text annotations for all embodied reasoning datasets and videos for RoboVQA and AV datasets. For other datasets, users may download the source videos from the original data source and find corresponding video sources via the video names. The held-out RoboFail benchmark is released for measuring the generalization capability.

**[08/01/2025](https://huggingface.co/nvidia/Cosmos-Reason1-7B#08012025-1)**

| Dataset Type | PLM-Video-Human | Nexar | Describe Anything | [ITS / Warehouse] | Visual Critics | Total Storage Size |
|--------------|-----------------|-------|-------------------|-------------------|----------------|-------------------|
| SFT Data | 39k | 240k | 178k | 24k | 24k | 2.6TB |

### Inference
**Test Hardware:** H100 <br>

> **Note**: **We suggest using fps=4 for the input video and max_tokens=4096 to avoid truncated response.**

```python
from transformers import AutoProcessor
from vllm import LLM, SamplingParams
from qwen_vl_utils import process_vision_info

# You can also replace the MODEL_PATH by a safetensors folder path mentioned above
MODEL_PATH = "nvidia/Cosmos-Reason1-7B"

llm = LLM(
model=MODEL_PATH,
limit_mm_per_prompt={"image": 10, "video": 10},
)
```

### Sampling Parameters Configuration

```python
sampling_params = SamplingParams(
temperature=0.6,
top_p=0.95,
repetition_penalty=1.05,
max_tokens=4096,
)
```

### Video Message Setup

```python
video_messages = [
{"role": "system", "content": "You are a helpful assistant. Answer the question in the following format: <think>\nyour reasoning\n</think>\n\n<answer>\nyour answer\n</answer>."},
{"role": "user", "content": [
{"type": "text", "text": (
"Is it safe to turn right?"
)
},
{
"type": "video", 
"video": "file:///path/to/your/video.mp4",
"fps": 4,
}
]
},
]
```

### Message Processing and Generation

```python
# Here we use video messages as a demonstration
messages = video_messages

processor = AutoProcessor.from_pretrained(MODEL_PATH)
prompt = processor.apply_chat_template(
messages,
tokenize=False,
add_generation_prompt=True,
)
image_inputs, video_inputs, video_kwargs = process_vision_info(messages, return_video_kwargs=True)

mm_data = {}
if image_inputs is not None:
mm_data["image"] = image_inputs
if video_inputs is not None:
mm_data["video"] = video_inputs

llm_inputs = {
"prompt": prompt,
"multi_modal_data": mm_data,

# FPS will be returned in video_kwargs
"mm_processor_kwargs": video_kwargs,
}

outputs = llm.generate([llm_inputs], sampling_params=sampling_params)
generated_text = outputs[0].outputs[0].text

print(generated_text)
```

### Key Inference Notes

- **FPS Requirement**: Use `FPS=4` for input video to match the training setup
- **System Prompt**: Append `"Answer the question in the following format: <think>\nyour reasoning\n</think>\n\n<answer>\nyour answer\n</answer>."` in the system prompt to encourage long chain-of-thought reasoning response
- **Output Tokens**: Recommend using 4096 or more output max tokens to avoid truncation of long chain-of-thought response
- **Hardware**: Model is designed and optimized to run on NVIDIA GPU-accelerated systems
- **Precision**: Tested with BF16 precision for inference
- **Operating System**: Tested on Linux (other operating systems not tested)

### Ethical Considerations
NVIDIA believes Trustworthy AI is a shared responsibility and we have established policies and practices to enable development for a wide array of AI applications. When downloaded or used in accordance with our terms of service, developers should work with their internal model team to ensure this model meets requirements for the relevant industry and use case and addresses unforeseen product misuse.

Please report security vulnerabilities or NVIDIA AI Concerns [here](https://www.nvidia.com/en-us/support/submit-security-vulnerability/)

## Bias

| Field                                                                                                                                                            | Response |
| :--------------------------------------------------------------------------------------------------------------------------------------------------------------- | :------- |
| Participation considerations from adversely impacted groups [protected classes](https://www.senate.ca.gov/content/protected-classes) in model design and testing: | None     |
| Measures taken to mitigate against unwanted bias:                                                                                                                | The training video sources contain multiple physical embodiments and environments including human, car, single arm robot, bimanual robot in indoor and outdoor environments. By training on numerous and various physical interactions and curated datasets, we strive to provide a model that does not possess biases towards certain embodiments or environments.   |

## Explainability

| Field                                                     | Response                                                                                                             |
| :-------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------- |
| Intended Application & Domain:                            | Physical AI Reasoning                                                                                                |
| Model Type:                                               | Transformer                                                                                                          |
| Intended Users:                                           | Physical AI developers                                                                                               |
| Output:                                                   | Text                                                                                                                 |
| Describe how the model works:                             | Generates text answers based on input text prompt and video                                                          |
| Technical Limitations:                                    | The model may not follow the video or text input accurately in challenging cases, where the input video shows complex scene composition and temporal dynamics. Examples of challenging scenes include: fast camera movements, overlapping human-object interactions, low lighting with high motion blur, and multiple people performing different actions simultaneously.  |
| Verified to have met prescribed NVIDIA quality standards: | Yes                                                                                                                  |
| Performance Metrics:                                      | Quantitative and Qualitative Evaluation. Cosmos-Reason1 proposes the embodied reasoning benchmark and physical common sense benchmark to evaluate accuracy with visual question answering.                                                                              |
| Potential Known Risks:                                    | The model's output can generate all forms of texts, including what may be considered toxic, offensive, or indecent.  |
| Licensing:                                                | This trial service is governed by the [NVIDIA API Trial Terms of Service](https://assets.ngc.nvidia.com/products/api-catalog/legal/NVIDIA%20API%20Trial%20Terms%20of%20Service.pdf). Use of the model is governed by the [NVIDIA Open Model License Agreement](https://www.nvidia.com/en-us/agreements/enterprise-software/nvidia-open-model-license/).Additional Information: [Apache License 2.0](https://huggingface.co/datasets/choosealicense/licenses/blob/main/markdown/apache-2.0.md)  |

## Privacy

| Field                                                               | Response       |
| :------------------------------------------------------------------ | :------------- |
| Generatable or reverse engineerable personal information?           | None Known     |
| Protected class data used to create this model?                     | None Known     |
| Was consent obtained for any personal data used?                    | None Known     |
| How often is dataset reviewed?                                      | Before Release |
| Is there provenance for all datasets used in training?              | Yes            |
| Does data labeling (annotation, metadata) comply with privacy laws? | Yes            |
| Applicable Privacy Policy | [NVIDIA Privacy Policy](https://www.nvidia.com/en-us/about-nvidia/privacy-policy)            |

## Safety & Security

| Field                                           | Response                                                                                                                                                                                                                                                                                                                             |
| :---------------------------------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Model Application(s):                           | Physical AI common sense understanding and embodied reasoning                                                                                                                                                                                                                                                                                                                     |
| Describe the life critical impact (if present). | None Known                                                                                                                                                                                                                                                                                                                           |
| Use Case Restrictions:                          | This trial service is governed by the [NVIDIA API Trial Terms of Service](https://assets.ngc.nvidia.com/products/api-catalog/legal/NVIDIA%20API%20Trial%20Terms%20of%20Service.pdf). Use of the model is governed by the [NVIDIA Open Model License Agreement](https://www.nvidia.com/en-us/agreements/enterprise-software/nvidia-open-model-license/).Additional Information: [Apache License 2.0](https://huggingface.co/datasets/choosealicense/licenses/blob/main/markdown/apache-2.0.md) |
| Model and dataset restrictions:                 | The Principle of least privilege (PoLP) is applied limiting access for dataset generation and model development.  Restrictions enforce dataset access during training, and dataset license constraints adhered to. Model checkpoints are made available on Hugging Face, and may become available on cloud providers' model catalog. |

## Prototype

```python
import requests

invoke_url = "https://ai.api.nvidia.com/v1/vlm/nvidia/cosmos-reason1-7b"

headers = {
"Authorization": "Bearer ",
"Accept": "application/json",
}

payload = {
"messages": [
{
"role": "user",
"content": ""
}
]
}

# re-use connections
session = requests.Session()

response = session.post(invoke_url, headers=headers, json=payload)

response.raise_for_status()
response_body = response.json()
print(response_body)
```

```javascript
import fs from 'fs';
import axios from 'axios';
import path from 'path';

const invokeUrl = "https://ai.api.nvidia.com/v1/vlm/nvidia/cosmos-reason1-7b";
const stream = ;
const query = 'Describe the scene';

const kNvcfAssetUrl = 'https://api.nvcf.nvidia.com/v2/nvcf/assets';

// Retrieve the API Key from environment variables
const kApiKey = process.env.TEST_NVCF_API_KEY;
if (!kApiKey) {
console.error("Generate API_KEY and export TEST_NVCF_API_KEY=xxxx");
process.exit(1);
}

const kSupportedList = {
"png": ["image/png", "img"],
"jpg": ["image/jpg", "img"],
"jpeg": ["image/jpeg", "img"],
"mp4": ["video/mp4", "video"]
};

// Get file extension
function getExtension(filename) {
const ext = path.extname(filename).toLowerCase();
return ext.slice(1); // remove the leading dot
}

// Get MIME type
function mimeType(ext) {
return kSupportedList[ext][0];
}

// Get media type
function mediaType(ext) {
return kSupportedList[ext][1];
}

// Upload asset
async function uploadAsset(mediaFile, description) {
const ext = getExtension(mediaFile);
if (!(ext in kSupportedList)) {
throw new Error(`Unsupported file extension: ${ext}`);
}

const dataInput = fs.readFileSync(mediaFile); // Sync file read

const headers = {
"Authorization": `Bearer ${kApiKey}`,
"Content-Type": "application/json",
"Accept": "application/json"
};

const postData = {
contentType: mimeType(ext),
description: description
};

// First API call to authorize asset upload
const { data: authorizeRes } = await axios.post(kNvcfAssetUrl, postData, { headers });
console.log(`uploadUrl: ${authorizeRes.uploadUrl}`);

// Second API call to upload the file
const response = await axios.put(authorizeRes.uploadUrl, dataInput, {
headers: {
"x-amz-meta-nvcf-asset-description": description,
"content-type": mimeType(ext)
}
});

if (response.status === 200) {
console.log(`upload asset_id ${authorizeRes.assetId} successfully!`);
//return uuidParse(authorizeRes.assetId);
return authorizeRes.assetId.toString()
} else {
console.log(`upload asset_id ${authorizeRes.assetId} failed.`);
throw new Error(`Asset upload failed: ${authorizeRes.assetId}`);
}
}

// Delete asset
async function deleteAsset(assetId) {
const headers = {
"Authorization": `Bearer ${kApiKey}`
};
const url = `${kNvcfAssetUrl}/${assetId}`;
await axios.delete(url, { headers });
}

// Chat with media NVCF
async function chatWithMediaNvcf(inferUrl, mediaFiles, query, stream = false) {
const assetList = [];
const extList = [];
let mediaContent = "";
let hasVideo = false;

for (const mediaFile of mediaFiles) {
const ext = getExtension(mediaFile);
if (!(ext in kSupportedList)) {
throw new Error(`${mediaFile} format is not supported`);
}

if (mediaType(ext) === "video") {
hasVideo = true;
}

console.log(`uploading file: ${mediaFile}`);
const assetId = await uploadAsset(mediaFile, "Reference media file");
console.log(`assetId: ${assetId}`);
assetList.push(assetId);
extList.push(ext);
mediaContent += `<${mediaType(ext)} src="data:${mimeType(ext)};asset_id,${assetId}" />`;
}

if (hasVideo && mediaFiles.length !== 1) {
throw new Error("Only a single video is supported.");
}

const assetSeq = assetList.join(',');
console.log(`received asset_id list: ${assetSeq}`);

const headers = {
"Authorization": `Bearer ${kApiKey}`,
"Content-Type": "application/json",
"NVCF-INPUT-ASSET-REFERENCES": assetSeq,
"NVCF-FUNCTION-ASSET-IDS": assetSeq,
"Accept": "application/json"
};

if (stream) {
headers["Accept"] = "text/event-stream";
}

const messages = [{
"role": "user",
"content": `${query} ${mediaContent}`
}];

const payload = {
max_tokens: 1024,
temperature: 0.2,
top_p: 0.7,
seed: 50,
num_frames_per_inference: 8,
messages: messages,
stream: stream,
model: "nvidia/cosmos-reason1-7b"
};

// Post to the inference API
//let response = await axios.post(inferUrl, payload, { headers });
const response = await axios.post(inferUrl, payload, {
headers: headers,
responseType: stream ? 'stream' : 'json'
});

if (stream) {
response.data.on('data', (line) => {
console.log(line.toString());
});
} else {
console.log(JSON.stringify(response.data));
}

// Clean up uploaded assets
console.log(`deleting assets: ${assetList}`);
for (const assetId of assetList) {
await deleteAsset(assetId);
}
}

// Main function to run the script
async function main() {
const args = process.argv.slice(2);
if (args.length <= 0) {
console.log("Usage: export TEST_NVCF_API_KEY=xxx");
console.log(`python ${process.argv[0]} sample1.png sample2.png ... sample16.png`);
console.log(`python ${process.argv[0]} sample.mp4`);
process.exit(1);
}

const mediaSamples = args;
await chatWithMediaNvcf(invokeUrl, mediaSamples, query, stream);
}

main();
```

```bash
#!/bin/bash
stream=
# Check if TEST_NVCF_API_KEY is set
if [ -z "$TEST_NVCF_API_KEY" ]; then
echo "Generate API_KEY and export TEST_NVCF_API_KEY=xxxx"
exit 1
fi

invoke_url="https://ai.api.nvidia.com/v1/vlm/nvidia/cosmos-reason1-7b"
kNvcfAssetUrl="https://api.nvcf.nvidia.com/v2/nvcf/assets"
query="Describe the scene"

# supported table
kSupportedList=("png:image/png,img" "jpg:image/jpg,img" "jpeg:image/jpeg,img" "mp4:video/mp4,video")

# get "mime,media"
get_media_info() {
local ext="$1"
for item in "${kSupportedList[@]}"; do
if [[ "$item" == "$ext:"* ]]; then
# Return "mime,media"
echo "${item#*:}"
return
fi
done
echo ""
}

get_extension() {
filename="$1"
echo "${filename##*.}" | tr '[:upper:]' '[:lower:]'
}

upload_asset() {
media_file="$1"
description="$2"
ext=$(get_extension "$media_file")

media_info=$(get_media_info "$ext")
if [ -z "$media_info" ]; then
echo "$media_file format is not supported"
exit 1
fi

mime_type="${media_info%%,*}"
media_type="${media_info#*,}"

# Get upload URL
response=$(curl -s -X POST "$kNvcfAssetUrl" \
-H "Authorization: Bearer $TEST_NVCF_API_KEY" \
-H "Content-Type: application/json" \
-H "accept: application/json" \
-d "{\"contentType\": \"$mime_type\", \"description\": \"$description\"}")

upload_url=$(echo "$response" | jq -r '.uploadUrl')
asset_id=$(echo "$response" | jq -r '.assetId')

# Upload the asset file to the URL
curl -s -X PUT "$upload_url" \
-H "x-amz-meta-nvcf-asset-description: $description" \
-H "content-type: $mime_type" \
--data-binary "@$media_file"

echo "$asset_id"
}

delete_asset() {
asset_id="$1"
curl -s -X DELETE "$kNvcfAssetUrl/$asset_id" \
-H "Authorization: Bearer $TEST_NVCF_API_KEY"
}

chat_with_media_nvcf() {
infer_url="$1"
query="$2"
shift 2
media_files=("$@")

asset_list=()
media_content=""

has_video=false

for media_file in "${media_files[@]}"; do
ext=$(get_extension "$media_file")

media_info=$(get_media_info "$ext")
if [ -z "$media_info" ]; then
echo "$media_file format is not supported"
exit 1
fi
mime_type="${media_info%%,*}"
media_type="${media_info#*,}"

if [[ "$mime_type" == "video" ]]; then
has_video=true
fi

echo "uploading media_file: $media_file"
asset_id=$(upload_asset "$media_file" "Reference media file")
asset_list+=("$asset_id")
media_content+="<$media_type src=\"data:$mime_type;asset_id,$asset_id\" />"
done

if $has_video && [ "${#media_files[@]}" -gt 1 ]; then
echo "Only single video supported."
exit 1
fi

asset_seq=$(IFS=,; echo "${asset_list[*]}")

headers=(
-H "Authorization: Bearer $TEST_NVCF_API_KEY"
-H "Content-Type: application/json"
-H "NVCF-INPUT-ASSET-REFERENCES: $asset_seq"
-H "NVCF-FUNCTION-ASSET-IDS: $asset_seq"
)
if [ "$stream" = true ]; then
headers+=(-H "Accept: text/event-stream")
else
headers+=(-H "Accept: application/json")
fi

payload=$(jq -n --arg query "$query" --arg media_content "$media_content" --argjson stream "$stream" '{
max_tokens: 1024,
temperature: 0.2,
top_p: 0.7,
seed: 50,
num_frames_per_inference: 8,
messages: [{"role": "user", "content": "\($query) \($media_content)"}],
stream: $stream,
model: "nvidia/cosmos-reason1-7b"
}')

response=$(curl -s -X POST "$infer_url" "${headers[@]}" -d "$payload")

if [ "$stream" = true ]; then
echo "$response" | while IFS= read -r line; do
echo "$line"
done
else
echo "$response" | jq .
fi

# Cleanup uploaded assets
for asset_id in "${asset_list[@]}"; do
echo "deleting asset $asset_id"
delete_asset "$asset_id"
done
}

if [ "$#" -le 0 ]; then
echo "Usage: export TEST_NVCF_API_KEY=xxx"
echo "       $0 sample1.png sample2.png ... sample16.png"
echo "       $0 sample.mp4"
exit 1
fi

chat_with_media_nvcf "$invoke_url" "$query" "$@"
```