In the rapidly evolving landscape of artificial intelligence, language models have become a pivotal tool for various applications, from automating customer service to generating creative content.
Among the leading technologies is Alibaba Cloud Model Studio, a robust platform specifically designed for generative AI development. It provides seamless access to top-tier foundation models (FMs) like Qwen-Max, Qwen-Plus, Qwen-Turbo, and the Qwen 2 series. You can easily customise these models using your enterprise data by implementing a Retrieval-Augmented Generation (RAG) architecture with just one click. Create AI agents effortlessly and develop generative AI (GenAI) applications that understand your business needs, all without worrying about the underlying infrastructure and computing power.
How to Use Alibaba Cloud Model Studio SDK
Step 1: Setting Up Your Environment
To start with Alibaba Cloud Model Studio SDK, you need a suitable environment. For this tutorial, we’ll use an Ubuntu 22.04.4 server. Ensure that Python 3.8 or later is installed. You can install Python and other necessary packages using the following commands:
sudo apt update
sudo apt install python3 python3-pip -y
Step 2: Installing the Dashscope SDK
The Alibaba Cloud Model Studio SDK for Python is required to interact with Qwen LLM. Install it using pip:
pip3 install dashscope
Step 3: Writing the Python Script
This script sends a request to the Qwen LLM API to generate a poem based on the user’s input.
Follow this step to obtain an API key.
import random
from http import HTTPStatus
from dashscope import Generation
import dashscope
def call_with_messages(user_input):
messages = [{'role': 'system', 'content': 'You are a helpful assistant.'},
{'role': 'user', 'content': f'请根据以下词语创作一首诗:{user_input}'}]
response = Generation.call(model="qwen-turbo",
messages=messages,
seed=random.randint(1, 10000),
result_format='message')
if response.status_code == HTTPStatus.OK:
print(response)
else:
print('Request id: %s, Status code: %s, error code: %s, error message: %s' % (
response.request_id, response.status_code,
response.code, response.message
))
if __name__ == '__main__':
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
user_input = input("请输入一些词语来创作一首诗:")
call_with_messages(user_input)
Step 4: Running the Script
Run the script in your terminal:
python3 poem_generator.py
Enter some Chinese words when prompted, and the script will return a generated poem.
2. Example of a Poem Generator Web Application
To make this more interactive, let’s create a web application using PHP, hosted on an Apache server. This application will allow users to enter words and generate a Chinese poem.
Setting Up Apache and PHP
First, ensure Apache and PHP are installed on your server:
sudo apt update
sudo apt install apache2 php libapache2-mod-php -y
Creating the Web Application
Create an index.php file in your Apache server’s root directory (/var/www/html/):
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$inputWords = htmlspecialchars($_POST['input_words']);
$apiUrl = 'https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation';
$apiKey = 'your_api_key_here';
$data = array(
'model' => 'qwen-turbo',
'input' => array(
'messages' => array(
array('role' => 'system', 'content' => 'You are a helpful assistant.'),
array('role' => 'user', 'content' => '请根据以下词语创作一首诗:' . $inputWords)
)
),
'parameters' => new stdClass()
);
$jsonData = json_encode($data, JSON_UNESCAPED_UNICODE);
$ch = curl_init($apiUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer ' . $apiKey,
'Content-Type: application/json',
'Content-Length: ' . strlen($jsonData)
));
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode == 200) {
$responseData = json_decode($response, true);
if (isset($responseData['output']['text'])) {
echo '
Generated Poem:
'; echo '
' . htmlspecialchars($responseData['output']['text'], ENT_QUOTES, 'UTF-8') . '
'; } else { echo '
Error:
'; echo '
Response does not contain an "output.text" field. Check API response format.
'; } } else { $error = json_decode($response, true); $errorMessage = isset($error['message']) ? htmlspecialchars($error['message'], ENT_QUOTES, 'UTF-8') : 'No error message provided'; $requestId = isset($error['request_id']) ? htmlspecialchars($error['request_id'], ENT_QUOTES, 'UTF-8') : 'No request ID'; $errorCode = isset($error['code']) ? htmlspecialchars($error['code'], ENT_QUOTES, 'UTF-8') : 'No error code'; echo '
Error:
'; echo '
Request ID: ' . $requestId . '
'; echo 'Status Code: ' . htmlspecialchars($httpCode, ENT_QUOTES, 'UTF-8') . '
'; echo 'Error Code: ' . $errorCode . '
'; echo 'Error Message: ' . $errorMessage . '
'; } } ?>
Replace your_api_key_here with your actual API key. Refer to this step to get the Alibaba Cloud Model Studio API key.
Open your web browser and navigate to http://Server IP Address/index.php.
Let’s watch the demo:
By following these steps, you can leverage Alibaba Cloud Qwen LLM to create an interactive and engaging web application that generates Chinese poems. Whether you’re a developer looking to enhance your projects with AI or a poet seeking inspiration from technology, Alibaba Cloud Qwen LLM Qwen LLM provides a versatile platform to explore the possibilities of language generation.
2 thoughts on “How to Use Qwen LLM for Creative Applications: A Case Study with a Chinese Poem Generator”