Skip to main content
Open In ColabOpen on GitHub

ChatQwQ

This will help you get started with QwQ chat models. For detailed documentation of all ChatQwQ features and configurations head to the API reference.

Overview

Integration details

ClassPackageLocalSerializablePackage downloadsPackage latest
ChatQwQlangchain-qwqbetaPyPI - DownloadsPyPI - Version

Model features

Tool callingStructured outputJSON modeImage inputAudio inputVideo inputToken-level streamingNative asyncToken usageLogprobs

Setup

To access QwQ models you'll need to create an Alibaba Cloud account, get an API key, and install the langchain-qwq integration package.

Credentials

Head to Alibaba's API Key page to sign up to Alibaba Cloud and generate an API key. Once you've done this set the DASHSCOPE_API_KEY environment variable:

import getpass
import os

if not os.getenv("DASHSCOPE_API_KEY"):
os.environ["DASHSCOPE_API_KEY"] = getpass.getpass("Enter your Dashscope API key: ")

Installation

The LangChain QwQ integration lives in the langchain-qwq package:

%pip install -qU langchain-qwq

Instantiation

Now we can instantiate our model object and generate chat completions:

from langchain_qwq import ChatQwQ

llm = ChatQwQ(
model="qwq-plus",
max_tokens=3_000,
timeout=None,
max_retries=2,
# other params...
)

Invocation

messages = [
(
"system",
"You are a helpful assistant that translates English to French."
"Translate the user sentence.",
),
("human", "I love programming."),
]
ai_msg = llm.invoke(messages)
ai_msg
AIMessage(content="J'aime la programmation.", additional_kwargs={'reasoning_content': 'Okay, the user wants me to translate "I love programming." into French. Let me start by recalling the basic translation. The verb "love" in French is "aimer", and "programming" is "la programmation". So the literal translation would be "J\'aime la programmation." But wait, I should check if there\'s any context or nuances I need to consider. The user mentioned they\'re a helpful assistant, so maybe they want a more natural or commonly used phrase. Sometimes in French, people might use "adorer" instead of "aimer" for stronger emphasis, but "aimer" is more standard here. Also, the structure "J\'aime" is correct for "I love". No need for any articles if it\'s a general statement, but "la programmation" is a feminine noun, so the article is necessary. Let me confirm the gender of "programmation"—yes, it\'s feminine. So "la" is correct. I think that\'s it. The translation should be "J\'aime la programmation."'}, response_metadata={'model_name': 'qwq-plus'}, id='run--396edf0f-ab92-4317-99be-cc9f5377c312-0', usage_metadata={'input_tokens': 32, 'output_tokens': 229, 'total_tokens': 261, 'input_token_details': {}, 'output_token_details': {}})

Chaining

We can chain our model with a prompt template like so:

from langchain_core.prompts import ChatPromptTemplate

prompt = ChatPromptTemplate(
[
(
"system",
"You are a helpful assistant that translates"
"{input_language} to {output_language}.",
),
("human", "{input}"),
]
)

chain = prompt | llm
chain.invoke(
{
"input_language": "English",
"output_language": "German",
"input": "I love programming.",
}
)
API Reference:ChatPromptTemplate
AIMessage(content='Ich liebe das Programmieren.', additional_kwargs={'reasoning_content': 'Okay, the user wants to translate "I love programming." into German. Let\'s start by breaking down the sentence. The subject is "I," which translates to "Ich" in German. The verb "love" is "liebe" in present tense for the first person singular. Then "programming" is a noun. Now, in German, the word for programming, especially in the context of computer programming, is "Programmierung." However, sometimes people might use "Programmieren" as well. Wait, but "Programmierung" is the noun form, so "die Programmierung." The structure in German would be "Ich liebe die Programmierung." Alternatively, could it be "Programmieren" as the verb in a nominalized form? Let me think. If you say "Ich liebe das Programmieren," that\'s also correct because "das Programmieren" is the gerundive form, which is commonly used for activities. So both are possible. Which one is more natural? Hmm. "Das Programmieren" might be more common in everyday language. Let me check some examples. For instance, "I love cooking" would be "Ich liebe das Kochen." So following that pattern, "Ich liebe das Programmieren" would be the equivalent. Therefore, maybe "Programmieren" with the article "das" is better here. But the user might just want a direct translation without the article. Wait, the original sentence is "I love programming," which is a noun, so in German, you need an article. So the correct translation would include "das" before the noun. So the correct sentence is "Ich liebe das Programmieren." Alternatively, if they want to use the noun without an article, maybe in a more abstract sense, but I think "das" is necessary here. Let me confirm. Yes, in German, when using the noun form of a verb like this, you need the article. So the best translation is "Ich liebe das Programmieren." I think that\'s the most natural way to say it. Alternatively, "Programmierung" is more formal, but "Programmieren" is more commonly used in such contexts. So I\'ll go with "Ich liebe das Programmieren."'}, response_metadata={'model_name': 'qwq-plus'}, id='run--0ceaba8a-7842-48fb-8bec-eb96d2c83ed4-0', usage_metadata={'input_tokens': 28, 'output_tokens': 466, 'total_tokens': 494, 'input_token_details': {}, 'output_token_details': {}})

Tool Calling

ChatQwQ supports tool calling API that lets you describe tools and their arguments, and have the model return a JSON object with a tool to invoke and the inputs to that tool.

Use with bind_tools

from langchain_core.tools import tool

from langchain_qwq import ChatQwQ


@tool
def multiply(first_int: int, second_int: int) -> int:
"""Multiply two integers together."""
return first_int * second_int


llm = ChatQwQ()

llm_with_tools = llm.bind_tools([multiply])

msg = llm_with_tools.invoke("What's 5 times forty two")

print(msg)
API Reference:tool
content='' additional_kwargs={'reasoning_content': 'Okay, the user is asking "What\'s 5 times forty two". Let me break this down. They want the product of 5 and 42. The function provided is called multiply, which takes two integers. First, I need to parse the numbers from the question. The first integer is 5, straightforward. The second is forty two, which is 42 in numeric form. So I should call the multiply function with first_int=5 and second_int=42. Let me double-check the parameters: both are required and of type integer. Yep, that\'s correct. No examples given, but the function should handle these numbers. Alright, time to format the tool call.'} response_metadata={'model_name': 'qwq-plus'} id='run--3c5ff46c-3fc8-4caf-a665-2405aeef2948-0' tool_calls=[{'name': 'multiply', 'args': {'first_int': 5, 'second_int': 42}, 'id': 'call_33fb94c6662d44928e56ec', 'type': 'tool_call'}] usage_metadata={'input_tokens': 176, 'output_tokens': 173, 'total_tokens': 349, 'input_token_details': {}, 'output_token_details': {}}

vision Support

Image

from langchain_core.messages import HumanMessage

model = ChatQwQ(model="qvq-max-latest")

messages = [
HumanMessage(
content=[
{
"type": "image_url",
"image_url": {"url": "https://example.com/image/image.png"},
},
{"type": "text", "text": "What do you see in this image?"},
]
)
]

response = model.invoke(messages)
print(response.content)
API Reference:HumanMessage
The image depicts a charming Christmas-themed arrangement set against a rustic wooden backdrop, creating a warm and festive atmosphere. Here's a detailed breakdown:

### **Background & Setting**
- **Wooden Wall**: A horizontally paneled wooden wall forms the backdrop, giving a cozy, cabin-like feel.
- **Foreground Surface**: The decorations rest on a smooth wooden surface (likely a table or desk), enhancing the natural, earthy tone of the scene.

### **Key Elements**
1. **Snow-Covered Trees**:
- Two miniature evergreen trees dusted with artificial snow flank the sides of the arrangement, evoking a wintry landscape.

2. **String Lights**:
- A strand of white bulb lights stretches across the back, weaving through the decor and adding a soft, glowing ambiance.

3. **Ornamental Sphere**:
- A reflective gold sphere with striped patterns sits near the center-left, catching and dispersing light.

4. **"Merry Christmas" Sign**:
- A wooden cutout spelling "MERRY CHRISTMAS" in capital letters serves as the focal point. The letters feature star-shaped cutouts, allowing light to shine through.

5. **Reindeer Figurine**:
- A brown reindeer with white facial markings and large antlers stands prominently on the right, facing forward and adding a playful touch.

6. **Candle Holders**:
- Three birch-bark candle holders are arranged in front of the reindeer. Two hold lit tealights, casting a warm glow, while the third remains unlit.

7. **Natural Accents**:
- **Pinecones**: Scattered throughout, adding texture and a woodland feel.
- **Berry Branches**: Red-berried greenery (likely holly) weaves behind the sign, introducing vibrant color.
- **Pine Branches**: Fresh-looking branches enhance the seasonal authenticity.

8. **Gift Box**:
- A small golden gift box with a bow sits near the left, symbolizing holiday gifting.

9. **Textile Detail**:
- A fabric piece with "Christmas" embroidered on it peeks from the left, partially obscured but contributing to the thematic unity.

### **Color Palette & Mood**
- **Warm Tones**: Browns (wood, reindeer), golds (ornament, gift box), and whites (snow, lights) dominate, creating a inviting glow.
- **Cool Accents**: Greens (trees, branches) and reds (berries) provide contrast, balancing the warmth.
- **Lighting**: The lit candles and string lights cast a soft, flickering illumination, enhancing the intimate, celebratory vibe.

### **Composition**
- **Balance**: The arrangement is symmetrical, with trees and candles on either side framing the central sign and reindeer.
- **Depth**: Layered elements (trees, lights, branches) create visual interest, drawing the eye inward.

This image beautifully captures the essence of a cozy, handmade Christmas display, blending traditional symbols with natural textures to evoke nostalgia and joy.

Video

from langchain_core.messages import HumanMessage

model = ChatQwQ(model="qvq-max-latest")

messages = [
HumanMessage(
content=[
{
"type": "video_url",
"video_url": {"url": "https://example.com/video/1.mp4"},
},
{"type": "text", "text": "Can you tell me about this video?"},
]
)
]

response = model.invoke(messages)
print(response.content)
API Reference:HumanMessage
The image provided is a still frame from a video featuring a young woman with short brown hair and bangs, smiling brightly at the camera. Here's a detailed breakdown:

### **Description of the Image:**
- **Subject:** A youthful female with a cheerful expression, showcasing a wide smile with visible teeth.
- **Appearance:**
- Short, neatly styled brown hair with blunt bangs.
- Natural makeup emphasizing clear skin and subtle eye makeup.
- Wearing a white round-neck shirt layered under a light pink knitted cardigan.
- Accessories include a delicate necklace with a small pendant and small earrings.
- **Background:** An outdoor setting with blurred architectural elements (e.g., buildings with columns), suggesting a campus, park, or residential area.
- **Lighting:** Soft, natural daylight, enhancing the warm and inviting atmosphere.

### **Key Details About the Video:**
1. **AI-Generated Content:** The watermark ("通义·AI合成" / "Tongyi AI Synthesis") indicates this image was created using Alibaba's Tongyi AI model, known for generating hyper-realistic visuals.
2. **Style & Purpose:** The high-quality, photorealistic style suggests the video may demonstrate AI imaging capabilities, potentially for advertising, entertainment, or educational purposes.
3. **Context Clues:** The subject's casual yet polished look and the pleasant outdoor setting imply a positive, approachable theme (e.g., lifestyle, technology promotion, or social media content).

### **What We Can Infer About the Video:**
- Likely showcases dynamic AI-generated scenes featuring the same character in various poses or interactions.
- May highlight realism in digital avatars or synthetic media.
- Could be part of a demo reel, tutorial, or creative project emphasizing AI artistry.

### **Limitations:**
- As only a single frame is provided, specifics about the video's length, narrative, or additional scenes cannot be determined.

If you have more frames or context, feel free to share! 😊

API reference

For detailed documentation of all ChatQwQ features and configurations head to the API reference