Spaces:
Sleeping
Sleeping
File size: 8,331 Bytes
5fdb69e |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 |
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "12ca6f8a",
"metadata": {},
"outputs": [],
"source": [
"# imports\n",
"\n",
"import os\n",
"from dotenv import load_dotenv\n",
"from openai import OpenAI\n",
"import anthropic\n",
"from IPython.display import Markdown, display, update_display"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "4b53a815",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"OpenAI API Key exists and begins sk-proj-\n",
"Anthropic API Key exists and begins sk-ant-\n",
"Google API Key not set\n"
]
}
],
"source": [
"# Load environment variables in a file called .env\n",
"# Print the key prefixes to help with any debugging\n",
"\n",
"load_dotenv(override=True)\n",
"openai_api_key = os.getenv('OPENAI_API_KEY')\n",
"anthropic_api_key = os.getenv('ANTHROPIC_API_KEY')\n",
"google_api_key = os.getenv('GOOGLE_API_KEY')\n",
"\n",
"if openai_api_key:\n",
" print(f\"OpenAI API Key exists and begins {openai_api_key[:8]}\")\n",
"else:\n",
" print(\"OpenAI API Key not set\")\n",
" \n",
"if anthropic_api_key:\n",
" print(f\"Anthropic API Key exists and begins {anthropic_api_key[:7]}\")\n",
"else:\n",
" print(\"Anthropic API Key not set\")\n",
"\n",
"if google_api_key:\n",
" print(f\"Google API Key exists and begins {google_api_key[:8]}\")\n",
"else:\n",
" print(\"Google API Key not set\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "3d2b7cfe",
"metadata": {},
"outputs": [],
"source": [
"# Connect to OpenAI, Anthropic\n",
"\n",
"openai = OpenAI()\n",
"\n",
"claude = anthropic.Anthropic()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b7d88d4b",
"metadata": {},
"outputs": [],
"source": [
"class ConversationManager:\n",
" def __init__(self):\n",
" self.conversation_history = []\n",
" self.participants = {}\n",
" \n",
" def add_participant(self, name, chatbot):\n",
" \"\"\"Add a model to the conversation\"\"\"\n",
" self.participants[name] = chatbot\n",
" \n",
" def add_message(self, speaker, message):\n",
" \"\"\"Add a message to the shared conversation history\"\"\"\n",
" self.conversation_history.append({\n",
" \"speaker\": speaker,\n",
" \"role\": \"assistant\" if speaker in self.participants else \"user\",\n",
" \"content\": message\n",
" })\n",
" \n",
" def get_context_for_model(self, model_name):\n",
" \"\"\"Create context appropriate for the given model\"\"\"\n",
" # Convert the shared history to model-specific format\n",
" messages = []\n",
" for msg in self.conversation_history:\n",
" if msg[\"speaker\"] == model_name:\n",
" messages.append({\"role\": \"assistant\", \"content\": msg[\"content\"]})\n",
" else:\n",
" messages.append({\"role\": \"user\", \"content\": msg[\"content\"]})\n",
" return messages\n",
" \n",
" def run_conversation(self, starting_message, turns=3, round_robin=True):\n",
" \"\"\"Run a multi-model conversation for specified number of turns\"\"\"\n",
" current_message = starting_message\n",
" models = list(self.participants.keys())\n",
" \n",
" # Add initial message\n",
" self.add_message(\"user\", current_message)\n",
" \n",
" for _ in range(turns):\n",
" for model_name in models:\n",
" # Get context appropriate for this model\n",
" model_context = self.get_context_for_model(model_name)\n",
" \n",
" # Get response from this model\n",
" chatbot = self.participants[model_name]\n",
" response = chatbot.generate_response(model_context)\n",
" \n",
" # Add to conversation history\n",
" self.add_message(model_name, response)\n",
" \n",
" print(f\"{model_name}:\\n{response}\\n\")\n",
" \n",
" if not round_robin:\n",
" # If not round-robin, use this response as input to next model\n",
" current_message = response"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "80c537c3",
"metadata": {},
"outputs": [],
"source": [
"class ChatBot:\n",
" def __init__(self, model_name, system_prompt, **kwargs):\n",
" self.model_name = model_name\n",
" self.system_prompt = system_prompt\n",
" self.api_key = kwargs.get('api_key', None)\n",
" self.base_url = kwargs.get('base_url', None)\n",
" \n",
" def generate_response(self, messages):\n",
" \"\"\"Generate a response based on provided messages without storing history\"\"\"\n",
" # Prepare messages including system prompt\n",
" full_messages = [{\"role\": \"system\", \"content\": self.system_prompt}] + messages\n",
" \n",
" try:\n",
" if \"claude\" in self.model_name.lower():\n",
" # Format messages for Claude API\n",
" claude_messages = [m for m in messages if m[\"role\"] != \"system\"]\n",
" response = anthropic.Anthropic().messages.create(\n",
" model=self.model_name,\n",
" system=self.system_prompt,\n",
" messages=claude_messages,\n",
" max_tokens=200,\n",
" )\n",
" return response.content[0].text\n",
" \n",
" else:\n",
" # Use OpenAI API (works for OpenAI, Gemini via OpenAI client, etc)\n",
" openai_client = OpenAI(api_key=self.api_key, base_url=self.base_url)\n",
" response = openai_client.chat.completions.create(\n",
" model=self.model_name,\n",
" messages=full_messages,\n",
" max_tokens=200,\n",
" )\n",
" return response.choices[0].message.content\n",
" \n",
" except Exception as e:\n",
" return f\"Error: {str(e)}\""
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "d197c3ef",
"metadata": {},
"outputs": [],
"source": [
"# Initialize models\n",
"gpt_bot = ChatBot(\"gpt-4o-mini\", \"You are witty and sarcastic.\")\n",
"claude_bot = ChatBot(\"claude-3-haiku-20240307\", \"You are thoughtful and philosophical.\")\n",
"\n",
"model_name = \"qwen2.5:1.5b\"\n",
"system_prompt = \"You are a helpful assistant that is very argumentative in a snarky way.\"\n",
"kwargs = {\n",
" \"api_key\": \"ollama\",\n",
" \"base_url\": 'http://localhost:11434/v1'\n",
"}\n",
"qwen = ChatBot(model_name, system_prompt, **kwargs)\n",
"\n",
"# Set up conversation manager\n",
"conversation = ConversationManager()\n",
"conversation.add_participant(\"GPT\", gpt_bot)\n",
"conversation.add_participant(\"Claude\", claude_bot)\n",
"conversation.add_participant(\"Qwen\", qwen)\n",
"\n",
"# Run a multi-model conversation\n",
"conversation.run_conversation(\"What's the most interesting technology trend right now?\", turns=2)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python (llms)",
"language": "python",
"name": "llms"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.9"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
|