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

7.2 KiB

Chat Context Example

Learn how to maintain conversation context across multiple requests using chatId.

Understanding chatId

The chatId parameter allows you to:

  • Maintain conversation history - The AI remembers previous messages
  • Resume conversations - Continue an existing chat session
  • Organize conversations - Keep separate conversations for different users/topics

Basic Context Usage

from fastgpt_client import ChatClient

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

    # First message
    response = client.create_chat_completion(
        messages=[{"role": "user", "content": "My name is Alice"}],
        chatId=chat_id,
        stream=False
    )
    result = response.json()
    print(f"AI: {result['choices'][0]['message']['content']}")

    # Second message - AI remembers the name!
    response = client.create_chat_completion(
        messages=[{"role": "user", "content": "What's my name?"}],
        chatId=chat_id,  # Same chatId maintains context
        stream=False
    )
    result = response.json()
    print(f"AI: {result['choices'][0]['message']['content']}")
    # Output: "Your name is Alice!"

Multi-Turn Conversation Example

"""Multi-turn conversation with chatId."""

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 multi_turn_conversation():
    """Maintain context across multiple turns."""
    with ChatClient(api_key=API_KEY, base_url=BASE_URL) as client:
        chat_id = "my_conversation"

        conversation = [
            "Hi, I'm learning Python.",
            "What are the main data types in Python?",
            "Can you give me an example of a list?",
            "How do I add items to a list?",
        ]

        for user_message in conversation:
            print(f"\nUser: {user_message}")

            response = client.create_chat_completion(
                messages=[{"role": "user", "content": user_message}],
                chatId=chat_id,
                stream=False
            )
            response.raise_for_status()
            result = response.json()

            ai_message = result['choices'][0]['message']['content']
            print(f"AI: {ai_message}")


if __name__ == "__main__":
    multi_turn_conversation()

Managing Multiple Conversations

def manage_multiple_conversations():
    """Handle separate conversations for different users."""
    with ChatClient(api_key=API_KEY, base_url=BASE_URL) as client:
        # Conversation with user A
        chat_id_a = "user_123_conversation"
        response = client.create_chat_completion(
            messages=[{"role": "user", "content": "I like cats"}],
            chatId=chat_id_a,
            stream=False
        )

        # Conversation with user B
        chat_id_b = "user_456_conversation"
        response = client.create_chat_completion(
            messages=[{"role": "user", "content": "I like dogs"}],
            chatId=chat_id_b,
            stream=False
        )

        # Continue with user A
        response = client.create_chat_completion(
            messages=[{"role": "user", "content": "What did I say I like?"}],
            chatId=chat_id_a,
            stream=False
        )
        # Response: "You said you like cats"

Retrieving Chat History

def get_conversation_history():
    """Retrieve and display chat history."""
    with ChatClient(api_key=API_KEY, base_url=BASE_URL) as client:
        app_id = os.getenv("APP_ID")

        # Get all chat histories
        response = client.get_chat_histories(
            appId=app_id,
            offset=0,
            pageSize=20,
            source="api"
        )
        response.raise_for_status()
        data = response.json()

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

        # Get records for a specific chat
        chat_id = data['data']['list'][0]['chatId']
        records_response = client.get_chat_records(
            appId=app_id,
            chatId=chat_id,
            offset=0,
            pageSize=10
        )
        records_response.raise_for_status()
        records_data = records_response.json()

        print(f"\nRecords for {chat_id}:")
        for record in records_data['data']['list']:
            content = record.get('content', {})
            text = content.get('text', 'N/A')
            print(f"  - {text[:50]}...")

Updating Chat Title

def update_chat_title():
    """Update the title of a chat."""
    with ChatClient(api_key=API_KEY, base_url=BASE_URL) as client:
        app_id = os.getenv("APP_ID")
        chat_id = "my_conversation"

        # Update the chat title
        response = client.update_chat_history(
            appId=app_id,
            chatId=chat_id,
            customTitle="Python Learning Session"
        )
        response.raise_for_status()
        print("Chat title updated!")

Pinning a Chat

def pin_chat():
    """Pin a chat to the top."""
    with ChatClient(api_key=API_KEY, base_url=BASE_URL) as client:
        app_id = os.getenv("APP_ID")
        chat_id = "my_conversation"

        # Pin the chat
        response = client.update_chat_history(
            appId=app_id,
            chatId=chat_id,
            top=True
        )
        response.raise_for_status()
        print("Chat pinned!")

Deleting a Chat

def delete_chat():
    """Delete a chat conversation."""
    with ChatClient(api_key=API_KEY, base_url=BASE_URL) as client:
        app_id = os.getenv("APP_ID")
        chat_id = "old_conversation"

        # Delete the chat
        response = client.delete_chat_history(
            appId=app_id,
            chatId=chat_id
        )
        response.raise_for_status()
        print("Chat deleted!")

Best Practices

  1. Use meaningful chat IDs - Include user IDs or session IDs
  2. Store chat IDs - Keep them in your database for later retrieval
  3. Handle missing chats - Chat IDs may expire or be deleted
  4. Clean up old chats - Delete or archive conversations you no longer need
def robust_conversation():
    """Handle chatId gracefully."""
    with ChatClient(api_key=API_KEY, base_url=BASE_URL) as client:
        chat_id = "user_123_session_456"

        try:
            response = client.create_chat_completion(
                messages=[{"role": "user", "content": "Hello"}],
                chatId=chat_id,
                stream=False
            )
            response.raise_for_status()
            result = response.json()

            # Store the chatId for future use
            returned_chat_id = result.get('chatId', chat_id)
            print(f"Chat ID: {returned_chat_id}")

        except Exception as e:
            # Start a new conversation if this one fails
            print(f"Error with chatId: {e}")
            print("Starting new conversation...")
            # Create new chat without chatId

See Also