Python Openai
## Python3.x Python OpenAI
openai is a powerful Python library for interacting with OpenAI's suite of models and services.
openai encapsulates all RESTful API calls, allowing developers to easily integrate powerful AI capabilities into their Python applications, such as natural language processing, image generation, and speech recognition.
**Key Features:**
* Text Generation: Generate articles, code, summaries, conversations, etc. using models like GPT-4 or GPT-5.
* Image Generation: Create images from text descriptions using the DALL-E model.
* Embeddings: Convert text into vector representations, commonly used for semantic search, text classification, and clustering tasks.
* Speech-to-Text: Transcribe audio files into text using the Whisper model.
* Fine-tuning: Train a more targeted model by providing your own dataset.
* Assistants API: Build complex applications that can understand context, call tools, and maintain long-term interactions.
> openai open source repository: [https://github.com/openai/openai-python](https://github.com/openai/openai-python)
!(#)
* * *
## How to Use?
Environment Requirements:
* Python version: 3.9 or higher.
* Dependencies: httpx (default), aiohttp (optional), websockets (required for Realtime API).
First, you need to install the openai library using pip:
pip install openai or pip3 install openai
Then, go to the OpenAI official website [https://platform.openai.com/](https://platform.openai.com/) to register an account, and generate an API Key on the API keys page.
Check installed version:
import openai print(openai. __version__ ) # Output current SDK version
## Example
import os
from openai import OpenAI
client = OpenAI(
# This is the default and can be omitted
api_key="Your API key",
)
response = client.responses.create(
model="gpt-4o",
instructions="You are a coding assistant that talks like a pirate.",
input="How do I check if a Python object is an instance of a class?",
)
print(response.output_text)
**Parameter Description:**
| Parameter | Required | Type | Description |
| --- | --- | --- | --- |
| `api_key` | Yes | `str` | Your OpenAI key |
| `model` | Yes | `str` | Specifies the OpenAI model to use, determining capability, reasoning level, and cost |
| `instructions` | No | `str` | System-level instructions (System Prompt), defining the model's identity, behavior norms, and expression style, with higher priority than `input` |
| `input` | Yes | `str` / `list` | User input content, describing specific questions or tasks |
* * *
## Third-Party Models
Currently, accessing OpenAI from within China is somewhat difficult. Many domestic platforms also support OpenAI compatibility, such as DeepSeek, Qwen, and GLM.
### iFlytek Xingchen MaaS
Visit iFlytek Xingchen MaaS (https://maas.xfyun.cn/modelSquare?ch=maas_lm_l2E), where there are currently free large model products available.
!(#)
Hover over the free model, then select API call, and set the name and authorized application:
!(#)
Looking at the protocol support, currently only OpenAI-compatible protocol is available:
!(#)
Let's write a Python file to test:
## Example
from openai import OpenAI
# Required: Get the corresponding APIKey and API Base from the service management page
api_key ="The APIKey you applied for in the image above"
api_base ="http://maas-api.cn-huabei-1.xf-yun.com/v2"
client = OpenAI(api_key=api_key, base_url=api_base)
response = client.chat.completions.create(
model="The modelId from the image above",# Model name, required
messages=[
{"role": "system","content": "You are a helpful assistant"},
{"role": "user","content": "Hello"},
],
stream=False# stream=False non-streaming (return all at once), stream=True streaming (return in real-time)
)
print(response.choices.message.content)
Fill in the corresponding api_key, api_base, and model parameters, then you can execute:
Hello! How can I help you today?
More complete call:
## Example
from openai import OpenAI
# Required: Get the corresponding APIKey and API Base from the service management page
api_key =""
api_base ="http://maas-api.cn-huabei-1.xf-yun.com/v2"
client = OpenAI(api_key=api_key, base_url=api_base)
def unified_chat_test(model_id, messages, use_stream=False, extra_body={}):
"""
A unified function to demonstrate various calling scenarios.
:param model_id: The model ID to call.
:param messages: List of conversation messages.
:param use_stream: Whether to use streaming output.
:param extra_body: Dictionary containing additional request parameters, such as response_format.
"""
try:
response = client.chat.completions.create(
model=model_id,
messages=messages,
stream=use_stream,
temperature=0.7,
max_tokens=4096,
extra_headers={"lora_id": "0"},# When calling fine-tuned models, replace with the resourceId from the model service card
stream_options={"include_usage": True},
extra_body=extra_body
)
if use_stream:
# Process streaming response
full_response =""
print("--- Streaming Output ---")
for chunk in response:
if hasattr(chunk.choices.delta,'content')and chunk.choices.delta.content:
content =chunk.choices.delta.content
print(content, end="", flush=True)
full_response += content
print("nn--- Complete Response ---")
print(full_response)
else:
# Process non-streaming response
print("--- Non-Streaming Output ---")
message = response.choices.message
print(message.content)
except Exception as e:
print(f"Request error: {e}")
if __name__ =="__main__":
model_id =""# Required: When calling large models, corresponds to the modelId on the inference service model card
# 1. Normal non-streaming call
print("********* 1. Normal Non-Streaming Call *********")
plain_messages =[{"role": "user","content": "Hello, please introduce yourself."}]
unified_chat_test(model_id, plain_messages, use_stream=False)
# 2. Normal streaming call
print("n********* 2. Normal Streaming Call *********")
stream_messages =[{"role": "user","content": "Write a poem about summer."}]
unified_chat_test(model_id, stream_messages, use_stream=True)
# 3. JSON Mode call
print("n********* 3. JSON Mode Call *********")
json_messages =[{"role": "user","content": "Please give me a JSON object about Shanghai, containing city name (city) and population (population)."}]
json_extra_body ={
"response_format": {"type": "json_object"},
"search_disable": True# JSON Mode recommended to disable search
}
unified_chat_test(model_id, json_messages, use_stream=False, extra_body=json_extra_body)
# 4. Test stop and prefix continuation features
print("n********* 4. Test stop and prefix continuation features *********")
print("Set stop words: ['γ', 'οΌ'] - Model will stop generating when encountering period or exclamation mark")
stream_messages =[{"role": "user","content": "Explain to me what 1 plus 1 equals."}]
unified_chat_test(model_id, stream_messages, use_stream=True, extra_body={"stop": ["γ","οΌ"],"continue_final_message":True})
# 5. Tools/Function Calling example
print("n********* 5. Tools/Function Calling Example *********")
tools =[
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get weather information for specified city",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "City name, e.g.: Beijing, Shanghai"
},
"unit": {
"type": "string",
"enum": ["celsius","fahrenheit"],
"description": "Temperature unit"
}
},
"required":
}
}
}
]
tool_messages =[{"role": "user","content": "What's the weather like in Beijing today?"}]
response = client.chat.completions.create(
model=model_id,
messages=tool_messages,
tools=tools,
tool_choice="auto"
)
message = response.choices.message
if message.tool_calls:
print(f"Model requests to call tool: {message.tool_calls.function.name}")
print(f"Parameters: {message.tool_calls.function.arguments}")
else:
print(message.content)
Note that in the code you need to set your applied api_key and model_id:
api_key = "xxx" # This configuration needs to be modified api_base = "http://maas-api.cn-huabei-1.xf-yun.com/v2" model_id = " xxxx" # This configuration needs to be modified
Output results are as follows:
********* 1. Normal Non-Streaming Call ********* --- Non-Streaming Output ---Hello! I am Tongyi Qianwen (Qwen), a large language model independently developed by Alibaba Group's Tongyi Lab. Nice to meet you! I can serve as your intelligent partner, providing support and assistance in multiple areas, such as: * **Content creation and editing**: Assisting you with writing articles, emails, reports, stories, or text polishing and translation.* **Logical reasoning and problem solving**...
### DeepSeek
DeepSeek API is fully compatible with OpenAI's API format. With just a few configuration changes, you can directly use the OpenAI SDK or compatible tools to access the DeepSeek API.
| Parameter | Value/Description |
| --- | --- |
| base_url | Required, fixed value: `https://api.deepseek.com` (can also use `https://api.deepseek.com/v1`, only for OpenAI compatibility, v1 is unrelated to model version) |
| api_key | Required, need to apply for your exclusive API Key on DeepSeek official website first (application address: [https://platform.deepseek.com/](https://platform.deepseek.com/)) |
| model | Required, model to set: * `deepseek-v4-flash`: Corresponds to DeepSeek's **non-thinking mode**, fast response speed, suitable for regular Q&A. * `deepseek-v4-pro`: Corresponds to DeepSeek's **thinking mode**, stronger reasoning capability, suitable for complex problem solving. |
## Example
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ.get('DEEPSEEK_API_KEY'),# Recommended to configure via environment variable, can also hardcode (not recommended)
base_url="https://api.deepseek.com")
response = client.chat.completions.create(
model="deepseek-v4-flash",
messages=[
{"role": "system","content": "You are a helpful assistant"},
{"role": "user","content": "Hello"},
],
stream=False# stream=False non-streaming (return all at once), stream=True streaming (return in real-time)
)
print(response.choices.message.content)
* * *
## Usage Methods
Next, we use the OpenAI SDK to access the Tongyi Qianwen model on the Bailian service.
### Non-Streaming Call Example
## Example
from openai import OpenAI
import os
def get_response():
client = OpenAI(
api_key="sk-xxx",# Please use Alibaba Cloud Bailian API Key
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",# Fill in DashScope SDK's base_url
)
completion = client.chat.completions.create(
model="qwen-plus",# Here using qwen-plus as example, can replace with other model names as needed. Model list: https://help.aliyun.com/zh/model-studio/getting-started/models
messages=[{'role': 'system','content': 'You are a helpful assistant.'},
{'role': 'user','content': 'Who are you?'}]
)
# json data
#print(completion.model_dump_json())
p
YouTip