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

3.6 KiB

Quick Start

This guide will help you get started with the FastGPT Python SDK in just a few minutes.

1. Get Your API Key

You'll need a FastGPT API key to use the SDK. You can obtain one from your FastGPT instance:

  1. Log in to your FastGPT instance
  2. Navigate to Settings → API Keys
  3. Create a new API key
  4. Copy the key (it will start with fastgpt-)

2. Basic Chat Completion

The simplest way to use the SDK is with a basic chat completion:

from fastgpt_client import ChatClient

# Initialize the client
with ChatClient(
    api_key="fastgpt-xxxxx",
    base_url="http://localhost:3000"
) as client:
    # Send a message
    response = client.create_chat_completion(
        messages=[{"role": "user", "content": "Hello! What's AI?"}],
        stream=False
    )
    response.raise_for_status()
    result = response.json()

    # Print the response
    print(result['choices'][0]['message']['content'])

3. Streaming Responses

For real-time responses, use streaming:

import json

with ChatClient(api_key="fastgpt-xxxxx") as client:
    response = client.create_chat_completion(
        messages=[{"role": "user", "content": "Tell me a short story"}],
        stream=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)

4. Using Context (chatId)

To maintain a conversation across multiple requests, use chatId:

with ChatClient(api_key="fastgpt-xxxxx") as client:
    chat_id = "my_conversation_123"

    # First message
    response = client.create_chat_completion(
        messages=[{"role": "user", "content": "What's AI?"}],
        chatId=chat_id,
        stream=False
    )

    # Second message (continues the conversation)
    response = client.create_chat_completion(
        messages=[{"role": "user", "content": "Tell me more"}],
        chatId=chat_id,  # Same chatId maintains context
        stream=False
    )

5. Using Variables

You can use template variables in your FastGPT workflows:

with ChatClient(api_key="fastgpt-xxxxx") as client:
    response = client.create_chat_completion(
        messages=[{"role": "user", "content": "Hello [name]!"}],
        variables={"name": "Alice"},  # Replaces [name] placeholder
        stream=False
    )

6. Get Chat Histories

Retrieve your chat histories:

with ChatClient(api_key="fastgpt-xxxxx") as client:
    histories = client.get_chat_histories(
        appId="your-app-id",
        offset=0,
        pageSize=20,
        source="api"
    )
    histories.raise_for_status()
    data = histories.json()

    for chat in data['data']['list']:
        print(f"{chat['title']}: {chat['chatId']}")

Environment Variables

For better security, use environment variables for your API key:

# .env file
API_KEY=fastgpt-xxxxx
BASE_URL=http://localhost:3000
import os
from dotenv import load_dotenv
from fastgpt_client import ChatClient

load_dotenv()

with ChatClient(
    api_key=os.getenv("API_KEY"),
    base_url=os.getenv("BASE_URL")
) as client:
    # Your code here
    pass

Next Steps