{"cells": [{"cell_type": "markdown", "id": "302934307671667531413257853548643485645", "metadata": {}, "source": ["# Gradio Demo: llm_claude"]}, {"cell_type": "code", "execution_count": null, "id": "272996653310673477252411125948039410165", "metadata": {}, "outputs": [], "source": ["!pip install -q gradio openai>=1.0.0"]}, {"cell_type": "code", "execution_count": null, "id": "288918539441861185822528903084949547379", "metadata": {}, "outputs": [], "source": ["# This is a simple 20 questions-style game built on top of the Anthropic API.\n", "# Before running this, make sure you have exported your Anthropic API key as an environment variable:\n", "# export ANTHROPIC_API_KEY=\"your-anthropic-api-key\"\n", "\n", "import anthropic\n", "import gradio as gr\n", "\n", "client = anthropic.Anthropic()\n", "\n", "def predict(message, history):\n", " keys_to_keep = [\"role\", \"content\"]\n", " history = [{k: d[k] for k in keys_to_keep if k in d} for d in history]\n", " history.append({\"role\": \"user\", \"content\": message})\n", " if len(history) > 20:\n", " history.append({\"role\": \"user\", \"content\": \"DONE\"})\n", " output = client.messages.create(\n", " messages=history, # type: ignore\n", " model=\"claude-3-5-sonnet-20241022\",\n", " max_tokens=1000,\n", " system=\"You are guessing an object that the user is thinking of. You can ask 10 yes/no questions. Keep asking questions until the user says DONE\"\n", " )\n", " return {\n", " \"role\": \"assistant\",\n", " \"content\": output.content[0].text, # type: ignore\n", " \"options\": [{\"value\": \"Yes\"}, {\"value\": \"No\"}]\n", " }\n", "\n", "placeholder = \"\"\"\n", "

10 Questions


Think of a person, place, or thing. I'll ask you 10 yes/no questions to try and guess it.\n", "
\n", "\"\"\"\n", "\n", "demo = gr.ChatInterface(\n", " predict,\n", " examples=[\"Start!\"],\n", " chatbot=gr.Chatbot(placeholder=placeholder),\n", " type=\"messages\"\n", ")\n", "\n", "if __name__ == \"__main__\":\n", " demo.launch()\n"]}], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}