Files
fastgpt-python-sdk/docs/examples/variables.md
2026-01-08 17:35:21 +08:00

320 lines
9.0 KiB
Markdown

# Variables Example
Learn how to use template variables in your FastGPT workflows.
## What are Variables?
Variables allow you to dynamically replace placeholders in your FastGPT workflows. This is useful for:
- **Personalizing responses** - Insert user names, company names, etc.
- **Conditional content** - Show different content based on user input
- **Multi-language support** - Switch languages dynamically
- **Configuration** - Pass settings to your workflow
## Basic Variable Usage
```python
from fastgpt_client import ChatClient
with ChatClient(api_key="fastgpt-xxxxx") as client:
response = client.create_chat_completion(
messages=[{"role": "user", "content": "Introduction"}],
variables={
"user_name": "Alice",
"company": "Tech Corp",
"language": "English"
},
stream=False
)
result = response.json()
print(result['choices'][0]['message']['content'])
# Output might be: "Hello Alice! Welcome to Tech Corp..."
```
## Complete Variables Example
```python
"""Using template variables in FastGPT workflows."""
from fastgpt_client import ChatClient
from dotenv import load_dotenv
import os
load_dotenv()
API_KEY = os.getenv("API_KEY")
BASE_URL = os.getenv("BASE_URL")
def personalized_greeting():
"""Personalized greeting with variables."""
with ChatClient(api_key=API_KEY, base_url=BASE_URL) as client:
response = client.create_chat_completion(
messages=[{"role": "user", "content": "Greet me"}],
variables={
"user_name": "Alice",
"time_of_day": "morning",
"language": "English"
},
stream=False
)
response.raise_for_status()
result = response.json()
print("Response:", result['choices'][0]['message']['content'])
def dynamic_content():
"""Dynamic content based on variables."""
with ChatClient(api_key=API_KEY, base_url=BASE_URL) as client:
# Generate content for different audiences
audiences = [
{
"audience": "technical",
"detail_level": "high",
"include_examples": True
},
{
"audience": "business",
"detail_level": "low",
"include_examples": False
},
{
"audience": "general",
"detail_level": "medium",
"include_examples": True
}
]
for config in audiences:
print(f"\n--- Content for {config['audience']} audience ---")
response = client.create_chat_completion(
messages=[{"role": "user", "content": "Explain AI"}],
variables=config,
stream=False
)
response.raise_for_status()
result = response.json()
print(result['choices'][0]['message']['content'][:200] + "...")
def multi_language():
"""Multi-language support with variables."""
with ChatClient(api_key=API_KEY, base_url=BASE_URL) as client:
languages = [
{"language": "English", "user_name": "Alice"},
{"language": "Spanish", "user_name": "Carlos"},
{"language": "French", "user_name": "Marie"},
]
for lang_config in languages:
print(f"\n--- Response in {lang_config['language']} ---")
response = client.create_chat_completion(
messages=[{"role": "user", "content": "Say hello"}],
variables=lang_config,
stream=False
)
response.raise_for_status()
result = response.json()
print(result['choices'][0]['message']['content'])
def context_aware_response():
"""Response with contextual variables."""
with ChatClient(api_key=API_KEY, base_url=BASE_URL) as client:
# User context
user_context = {
"user_name": "Alice",
"user_level": "beginner",
"topic": "Python programming",
"goal": "learn data analysis"
}
# Generate personalized learning plan
response = client.create_chat_completion(
messages=[
{
"role": "user",
"content": "Create a learning plan for me"
}
],
variables=user_context,
stream=False
)
response.raise_for_status()
result = response.json()
print("Personalized Learning Plan:")
print(result['choices'][0]['message']['content'])
def workflow_with_variables():
"""Complete workflow using multiple variables."""
with ChatClient(api_key=API_KEY, base_url=BASE_URL) as client:
# Scenario: Customer support chat
customer_context = {
"customer_name": "John Doe",
"company": "Acme Corp",
"plan": "enterprise",
"issue_type": "technical",
"urgency": "high",
"language": "English",
"account_id": "12345"
}
# Generate personalized support response
response = client.create_chat_completion(
messages=[
{
"role": "user",
"content": "I need help with my account"
}
],
variables=customer_context,
stream=False
)
response.raise_for_status()
result = response.json()
print("Support Response:")
print(result['choices'][0]['message']['content'])
def streaming_with_variables():
"""Streaming response with variables."""
import json
with ChatClient(api_key=API_KEY, base_url=BASE_URL) as client:
response = client.create_chat_completion(
messages=[{"role": "user", "content": "Tell me a story"}],
variables={
"genre": "science fiction",
"length": "short",
"protagonist": "AI robot"
},
stream=True
)
print("Streaming story: ", end="", flush=True)
for line in response.iter_lines():
if line.startswith("data:"):
data = line[5:].strip()
if data and data != "[DONE]":
chunk = json.loads(data)
if "choices" in chunk and chunk["choices"]:
delta = chunk["choices"][0].get("delta", {})
content = delta.get("content", "")
if content:
print(content, end="", flush=True)
print()
if __name__ == "__main__":
print("=== Personalized Greeting ===")
try:
personalized_greeting()
except Exception as e:
print(f"Error: {e}")
print("\n=== Dynamic Content ===")
try:
dynamic_content()
except Exception as e:
print(f"Error: {e}")
print("\n=== Multi-Language ===")
try:
multi_language()
except Exception as e:
print(f"Error: {e}")
print("\n=== Context-Aware Response ===")
try:
context_aware_response()
except Exception as e:
print(f"Error: {e}")
print("\n=== Workflow with Variables ===")
try:
workflow_with_variables()
except Exception as e:
print(f"Error: {e}")
print("\n=== Streaming with Variables ===")
try:
streaming_with_variables()
except Exception as e:
print(f"Error: {e}")
```
## Common Use Cases
### 1. Personalization
```python
variables = {
"user_name": "Alice",
"company": "Tech Corp",
"role": "Developer"
}
```
### 2. Localization
```python
variables = {
"language": "Spanish",
"region": "Latin America",
"currency": "USD"
}
```
### 3. Conditional Logic
```python
variables = {
"user_tier": "premium",
"feature_set": "advanced",
"support_level": "24/7"
}
```
### 4. Content Generation
```python
variables = {
"topic": "AI",
"tone": "professional",
"length": "500",
"format": "blog post"
}
```
## Best Practices
1. **Use descriptive variable names** - `user_name` instead of `n`
2. **Validate variables** - Ensure required variables are provided
3. **Document your variables** - Keep a list of expected variables
4. **Use defaults** - Provide fallback values when possible
```python
def get_variables(user_input):
"""Validate and prepare variables."""
required_vars = ["user_name", "language"]
variables = {
"user_name": user_input.get("name", "Guest"),
"language": user_input.get("language", "English"),
"company": user_input.get("company", ""),
}
# Validate required variables
missing = [var for var in required_vars if not variables.get(var)]
if missing:
raise ValueError(f"Missing required variables: {missing}")
return variables
```
## See Also
- [ChatClient API](../api/chat_client.md) - Complete API reference
- [Chat Context](chat_context.md) - Managing conversation context
- [Streaming](streaming.md) - Streaming responses