2024主流AI大模型免费接入实战:Gemini、ChatGPT、Claude解决方案
1. 主流AI大模型现状与国内使用痛点分析
随着AI技术的快速发展,各大厂商纷纷推出自己的大语言模型产品。2024年7月实测发现,Gemini 3.5、ChatGPT 5.5、Claude 4.8、Grok 4.3等模型在功能性和实用性方面都有显著提升。然而,国内用户在访问这些国际AI服务时常常遇到网络限制、付费门槛高、稳定性差等问题。
从技术架构角度看,这些大模型都采用了Transformer架构的变体,但在训练数据、参数规模和应用场景上各有特色。Gemini 3.5在代码生成和多模态处理方面表现突出,ChatGPT 5.5在对话连贯性和知识广度上保持优势,Claude 4.8在安全性和逻辑推理方面更为严谨,而Grok 4.3则在实时信息处理和幽默感方面独具特色。
国内用户在实际使用中主要面临三大挑战:首先是访问稳定性问题,直接访问国外服务经常出现连接超时或速度缓慢;其次是付费模式的门槛,多数优质服务需要境外支付方式;最后是数据安全和隐私保护问题,敏感信息传输存在风险。本文将针对这些痛点,提供一套完整的解决方案。
2. 环境准备与基础工具配置
2.1 硬件与网络环境要求
在使用这些AI服务前,需要确保设备满足基本要求。对于电脑端,建议使用Windows 10及以上版本或macOS 10.14及以上版本,内存至少8GB,存储空间剩余10GB以上。手机端则需要Android 8.0或iOS 13及以上系统版本。
网络环境方面,虽然这些服务在国外访问顺畅,但国内用户需要做好相应的网络优化。建议使用带宽不低于50Mbps的网络连接,避免在高峰时段进行大文件传输或长时间会话。对于移动设备,确保4G/5G信号稳定,Wi-Fi连接质量良好。
2.2 必备软件工具安装
首先需要准备以下几个核心工具:现代浏览器(Chrome 90+、Firefox 88+或Safari 14+)、API调试工具(如Postman或Insomnia)、文本编辑器(VS Code或Sublime Text)。这些工具将帮助您更好地与AI服务进行交互。
对于开发者用户,还需要安装相应的SDK和开发环境。Python用户需要安装3.8及以上版本,并配置好pip包管理器。Node.js用户则需要安装16.x及以上版本。以下是基础环境检查命令:
# 检查Python版本 python --version pip --version # 检查Node.js版本 node --version npm --version # 检查系统信息(Windows) systeminfo | findstr /B /C:"OS Name" /C:"OS Version" # 检查系统信息(macOS/Linux) uname -a2.3 账户注册与认证准备
虽然本文重点介绍免氪金方案,但部分服务仍需要基础账户注册。建议使用国际邮箱服务(如Gmail、Outlook)进行注册,避免使用国内邮箱可能出现的收信延迟问题。注册时注意准备好手机验证工具,部分服务需要海外手机号验证。
重要提示:在注册任何AI服务账户时,务必使用强密码并开启双重认证。避免在多个平台使用相同密码,定期检查账户安全状态。以下是密码安全的最佳实践示例:
import re import secrets import string def generate_secure_password(length=16): """生成安全密码示例""" if length < 12: raise ValueError("密码长度至少12位") # 包含大小写字母、数字、特殊字符 characters = string.ascii_letters + string.digits + "!@#$%^&*" password = ''.join(secrets.choice(characters) for _ in range(length)) # 验证密码强度 if (re.search(r'[A-Z]', password) and re.search(r'[a-z]', password) and re.search(r'[0-9]', password) and re.search(r'[!@#$%^&*]', password)): return password else: return generate_secure_password(length) # 使用示例 secure_password = generate_secure_password() print(f"生成的安全密码: {secure_password}")3. Gemini 3.5 实战接入方案
3.1 官方API接入与优化
Google Gemini 3.5提供了相对友好的API接入方式。首先访问Google AI Studio平台,使用Google账户登录后即可获得有限的免费使用额度。对于轻度用户,免费额度通常足够日常使用。
API接入的核心步骤包括获取API密钥、安装SDK、配置请求参数。以下是Python接入示例:
import google.generativeai as genai import os # 配置API密钥 GEMINI_API_KEY = "your_api_key_here" genai.configure(api_key=GEMINI_API_KEY) # 创建模型实例 model = genai.GenerativeModel('gemini-1.5-pro') def chat_with_gemini(prompt, temperature=0.7): """与Gemini对话的基础函数""" try: response = model.generate_content( prompt, generation_config=genai.types.GenerationConfig( temperature=temperature, top_p=0.8, top_k=40, max_output_tokens=2048, ) ) return response.text except Exception as e: return f"请求失败: {str(e)}" # 使用示例 result = chat_with_gemini("用Python写一个快速排序算法") print(result)3.2 免费额度最大化利用技巧
Gemini的免费额度有一定限制,但通过以下技巧可以最大化利用:首先,合理设置max_output_tokens参数,避免不必要的长文本生成;其次,使用流式传输减少等待时间;最后,利用缓存机制避免重复请求。
对于代码生成任务,可以先用简短的提示词获取基础代码框架,再逐步细化需求。对于文档处理,可以先进行内容摘要再请求详细分析。以下是一个优化使用的示例:
from typing import List, Dict import time class GeminiOptimizer: def __init__(self, api_key): self.api_key = api_key self.request_count = 0 self.last_request_time = time.time() genai.configure(api_key=api_key) self.model = genai.GenerativeModel('gemini-1.5-flash') # 使用更经济的模型 def optimized_request(self, prompt: str, max_retries=3) -> str: """优化请求,避免频繁调用""" current_time = time.time() # 实现请求频率控制 if current_time - self.last_request_time < 1.0: # 每秒最多1次请求 time.sleep(1.0 - (current_time - self.last_request_time)) for attempt in range(max_retries): try: response = self.model.generate_content( prompt, generation_config=genai.types.GenerationConfig( max_output_tokens=1024, # 限制输出长度 temperature=0.3 # 降低随机性 ) ) self.request_count += 1 self.last_request_time = time.time() return response.text except Exception as e: if attempt == max_retries - 1: return f"所有重试失败: {str(e)}" time.sleep(2 ** attempt) # 指数退避 def batch_process(self, prompts: List[str]) -> List[str]: """批量处理提示词,减少API调用次数""" combined_prompt = "\n\n".join([f"任务{i+1}: {prompt}" for i, prompt in enumerate(prompts)]) combined_prompt += "\n\n请按顺序回答以上所有任务,用明确的编号分隔。" result = self.optimized_request(combined_prompt) return self._parse_batch_response(result, len(prompts)) def _parse_batch_response(self, response: str, task_count: int) -> List[str]: """解析批量处理的响应""" # 简单的响应解析逻辑 results = [] for i in range(task_count): start_marker = f"任务{i+1}:" end_marker = f"任务{i+2}:" if i < task_count - 1 else "" if start_marker in response: start_index = response.index(start_marker) + len(start_marker) end_index = response.index(end_marker) if end_marker else len(response) task_result = response[start_index:end_index].strip() results.append(task_result) else: results.append("解析失败") return results # 使用示例 optimizer = GeminiOptimizer("your_api_key") results = optimizer.batch_process([ "解释机器学习的基本概念", "写一个Python函数计算斐波那契数列", "简述深度学习的发展历史" ]) for i, result in enumerate(results): print(f"结果{i+1}: {result[:100]}...")3.3 移动端适配与使用技巧
在手机端使用Gemini时,可以通过Google AI Studio的移动端网页版获得较好体验。建议将网页添加到主屏幕,实现类似原生应用的使用感受。对于频繁使用的用户,可以考虑使用Tasker(Android)或Shortcuts(iOS)创建快捷指令。
移动端使用的关键优化点包括:使用简洁的提示词、利用语音输入功能、合理管理对话历史。以下是一个移动端优化的配置示例:
// 移动端网页优化配置示例 const mobileConfig = { viewport: 'width=device-width, initial-scale=1.0', themeColor: '#4285f4', display: 'standalone', shortcuts: [ { name: '新对话', url: '/new-chat', description: '开始新的对话' }, { name: '历史记录', url: '/history', description: '查看对话历史' } ] }; // 移动端API调用优化 class MobileGeminiClient { constructor(apiKey) { this.apiKey = apiKey; this.chatHistory = []; this.maxHistoryLength = 10; } async sendMessage(message) { // 优化移动端网络请求 const controller = new AbortController(); const timeoutId = setTimeout(() => controller.abort(), 30000); // 30秒超时 try { const response = await fetch('https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.apiKey}` }, body: JSON.stringify({ contents: [{ parts: [{ text: this.buildPrompt(message) }] }] }), signal: controller.signal }); clearTimeout(timeoutId); const data = await response.json(); this.updateChatHistory(message, data.candidates[0].content.parts[0].text); return data.candidates[0].content.parts[0].text; } catch (error) { clearTimeout(timeoutId); throw new Error(`请求失败: ${error.message}`); } } buildPrompt(currentMessage) { // 结合历史记录构建更好的提示词 if (this.chatHistory.length === 0) { return currentMessage; } const recentHistory = this.chatHistory.slice(-3); // 只保留最近3条历史 const context = recentHistory.map(chat => `用户: ${chat.user}\n助手: ${chat.assistant}` ).join('\n\n'); return `${context}\n\n用户: ${currentMessage}`; } updateChatHistory(userMessage, assistantResponse) { this.chatHistory.push({ user: userMessage, assistant: assistantResponse }); // 限制历史记录长度 if (this.chatHistory.length > this.maxHistoryLength) { this.chatHistory = this.chatHistory.slice(-this.maxHistoryLength); } } }4. ChatGPT 5.5 稳定访问方案
4.1 第三方客户端与API代理方案
由于OpenAI的服务在国内访问存在限制,我们可以通过多种方式实现稳定访问。第一种方案是使用第三方开发的客户端应用,这些应用通常内置了代理功能,能够提供更稳定的连接。第二种方案是使用API中转服务,将请求路由到海外服务器。
以下是使用Python请求第三方API网关的示例:
import requests import json from typing import Optional, Dict, Any class ChatGPTClient: def __init__(self, api_base: str, api_key: str): self.api_base = api_base.rstrip('/') self.api_key = api_key self.headers = { 'Content-Type': 'application/json', 'Authorization': f'Bearer {api_key}' } def create_chat_completion(self, messages: list, model: str = "gpt-3.5-turbo", temperature: float = 0.7, max_tokens: Optional[int] = None) -> Dict[str, Any]: """创建聊天完成请求""" payload = { "model": model, "messages": messages, "temperature": temperature } if max_tokens: payload["max_tokens"] = max_tokens try: response = requests.post( f"{self.api_base}/v1/chat/completions", headers=self.headers, json=payload, timeout=60 ) response.raise_for_status() return response.json() except requests.exceptions.RequestException as e: return {"error": str(e)} def stream_chat(self, messages: list, model: str = "gpt-3.5-turbo"): """流式聊天实现""" payload = { "model": model, "messages": messages, "temperature": 0.7, "stream": True } try: response = requests.post( f"{self.api_base}/v1/chat/completions", headers=self.headers, json=payload, stream=True, timeout=60 ) response.raise_for_status() for line in response.iter_lines(): if line: line = line.decode('utf-8') if line.startswith('data: '): data = line[6:] if data != '[DONE]': yield json.loads(data) except Exception as e: yield {"error": str(e)} # 使用示例 def demonstrate_chatgpt_usage(): client = ChatGPTClient("https://api.example-proxy.com", "your_api_key") # 普通对话 messages = [ {"role": "user", "content": "你好,请介绍Python的装饰器"} ] response = client.create_chat_completion(messages) if "error" not in response: print("回复:", response['choices'][0]['message']['content']) # 流式对话示例 print("开始流式对话:") for chunk in client.stream_chat(messages): if "error" in chunk: print("错误:", chunk["error"]) break if "choices" in chunk and chunk["choices"]: delta = chunk["choices"][0].get("delta", {}) if "content" in delta: print(delta["content"], end="", flush=True) # demonstrate_chatgpt_usage()4.2 本地部署与开源替代方案
对于需要更高隐私保护和稳定性的用户,可以考虑使用开源模型本地部署。虽然性能可能不及原版ChatGPT 5.5,但足以满足大多数日常需求。推荐使用Ollama、Text Generation WebUI等工具进行本地部署。
以下是在本地使用Ollama部署开源模型的完整流程:
# 安装Ollama(Linux/macOS) curl -fsSL https://ollama.ai/install.sh | sh # 安装Ollama(Windows) # 从官网下载安装包:https://ollama.ai/download # 拉取模型(以Llama 3为例) ollama pull llama3:8b # 运行模型 ollama run llama3:8b配套的Python客户端代码:
import requests import json class LocalLLMClient: def __init__(self, base_url="http://localhost:11434"): self.base_url = base_url def generate(self, prompt: str, model: str = "llama3:8b", options: dict = None) -> dict: """生成文本""" if options is None: options = { "temperature": 0.7, "top_p": 0.9, "top_k": 40, "num_predict": 512 } payload = { "model": model, "prompt": prompt, "stream": False, "options": options } try: response = requests.post( f"{self.base_url}/api/generate", json=payload, timeout=120 ) return response.json() except Exception as e: return {"error": str(e)} def chat(self, messages: list, model: str = "llama3:8b") -> dict: """聊天模式""" # 将消息历史转换为提示词 prompt = self.format_messages(messages) return self.generate(prompt, model) def format_messages(self, messages: list) -> str: """格式化消息历史""" formatted = [] for msg in messages: role = msg["role"] content = msg["content"] if role == "system": formatted.append(f"系统: {content}") elif role == "user": formatted.append(f"用户: {content}") elif role == "assistant": formatted.append(f"助手: {content}") return "\n".join(formatted) + "\n助手:" # 使用示例 local_client = LocalLLMClient() # 简单生成 result = local_client.generate("请用Python实现二分查找算法") if "response" in result: print(result["response"]) # 对话模式 messages = [ {"role": "user", "content": "什么是机器学习?"}, {"role": "assistant", "content": "机器学习是人工智能的一个分支,让计算机通过数据学习规律。"}, {"role": "user", "content": "有哪些主要类型?"} ] chat_result = local_client.chat(messages) if "response" in chat_result: print(chat_result["response"])4.3 浏览器扩展与用户脚本优化
通过浏览器扩展可以极大提升ChatGPT的使用体验。推荐安装以下类型的扩展:API访问助手、对话管理工具、提示词模板库、导出分享功能等。这些扩展通常可以在Chrome Web Store或GitHub上找到。
以下是一个用户脚本示例,用于增强ChatGPT网页版的功能:
// ==UserScript== // @name ChatGPT增强助手 // @namespace http://tampermonkey.net/ // @version 1.2 // @description 增强ChatGPT使用体验 // @author You // @match https://chat.openai.com/* // @grant none // ==/UserScript== (function() { 'use strict'; // 创建增强功能面板 function createEnhancementPanel() { const panel = document.createElement('div'); panel.style.cssText = ` position: fixed; top: 20px; right: 20px; background: #2d3748; color: white; padding: 15px; border-radius: 10px; z-index: 10000; font-family: Arial, sans-serif; min-width: 200px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); `; panel.innerHTML = ` <h3 style="margin:0 0 10px 0; font-size:14px;">ChatGPT增强工具</h3> <button id="quickSave" style="background:#4a5568; color:white; border:none; padding:5px 10px; border-radius:5px; margin:2px; cursor:pointer;">快速保存</button> <button id="exportChat" style="background:#4a5568; color:white; border:none; padding:5px 10px; border-radius:5px; margin:2px; cursor:pointer;">导出对话</button> <button id="clearHistory" style="background:#4a5568; color:white; border:none; padding:5px 10px; border-radius:5px; margin:2px; cursor:pointer;">清空历史</button> <div style="margin-top:10px; font-size:12px;"> <label>温度设置: <input type="range" id="tempSlider" min="0" max="1" step="0.1" value="0.7"></label> <span id="tempValue">0.7</span> </div> `; document.body.appendChild(panel); // 添加功能实现 document.getElementById('quickSave').addEventListener('click', quickSaveChat); document.getElementById('exportChat').addEventListener('click', exportChatHistory); document.getElementById('clearHistory').addEventListener('click', clearChatHistory); document.getElementById('tempSlider').addEventListener('input', updateTemperature); } function quickSaveChat() { const chatContent = document.querySelector('main')?.innerText || '无法获取聊天内容'; const blob = new Blob([chatContent], {type: 'text/plain'}); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = `chatgpt_chat_${new Date().toISOString().slice(0,19)}.txt`; a.click(); URL.revokeObjectURL(url); } function exportChatHistory() { // 实现导出聊天历史功能 console.log('导出聊天历史功能'); } function clearChatHistory() { if (confirm('确定要清空聊天历史吗?')) { // 实现清空历史功能 console.log('清空聊天历史'); } } function updateTemperature(e) { const value = e.target.value; document.getElementById('tempValue').textContent = value; // 实际应用中需要将温度设置保存到ChatGPT的请求中 } // 页面加载完成后创建面板 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', createEnhancementPanel); } else { createEnhancementPanel(); } })();5. Claude 4.8 接入与使用指南
5.1 Anthropic API直接接入方法
Claude 4.8作为Anthropic的最新模型,在逻辑推理和安全性方面表现优异。虽然官方API需要付费,但通过以下方式可以获得有限的免费访问权限。首先注册Anthropic账户,新用户通常有一定量的免费试用额度。
API接入的核心代码如下:
import anthropic import os from typing import Dict, List, Optional class ClaudeClient: def __init__(self, api_key: str): self.client = anthropic.Anthropic(api_key=api_key) self.conversation_history = [] def send_message(self, message: str, model: str = "claude-3-sonnet-20240229", max_tokens: int = 1024, temperature: float = 0.7) -> Dict: """发送消息给Claude""" try: message = self.client.messages.create( model=model, max_tokens=max_tokens, temperature=temperature, messages=[{"role": "user", "content": message}] ) response_text = message.content[0].text self.conversation_history.append({ "user": message, "assistant": response_text }) return { "success": True, "response": response_text, "usage": message.usage } except Exception as e: return { "success": False, "error": str(e) } def continue_conversation(self, new_message: str) -> Dict: """继续对话,包含历史上下文""" if not self.conversation_history: return self.send_message(new_message) # 构建包含历史的对话 messages = [] for exchange in self.conversation_history[-5:]: # 保留最近5轮对话 messages.append({"role": "user", "content": exchange["user"]}) messages.append({"role": "assistant", "content": exchange["assistant"]}) messages.append({"role": "user", "content": new_message}) try: message = self.client.messages.create( model="claude-3-sonnet-20240229", max_tokens=1024, temperature=0.7, messages=messages ) response_text = message.content[0].text self.conversation_history.append({ "user": new_message, "assistant": response_text }) return { "success": True, "response": response_text } except Exception as e: return { "success": False, "error": str(e) } # 使用示例 def demo_claude_usage(): # 注意:需要实际的API密钥 client = ClaudeClient("your_anthropic_api_key") # 单次对话 result = client.send_message("用Python实现一个简单的Web服务器") if result["success"]: print("Claude回复:", result["response"]) # 连续对话 result2 = client.continue_conversation("请为这个服务器添加文件上传功能") if result2["success"]: print("第二次回复:", result2["response"]) # demo_claude_usage()5.2 免费试用额度优化策略
Claude的免费试用额度有限,需要通过优化使用方式来延长使用时间。关键策略包括:压缩提示词、使用更经济的模型版本、合理设置参数、利用缓存机制。
以下是一个优化使用额度的工具类:
import time import hashlib import json from pathlib import Path class ClaudeUsageOptimizer: def __init__(self, api_key: str, cache_dir: str = ".claude_cache"): self.api_key = api_key self.cache_dir = Path(cache_dir) self.cache_dir.mkdir(exist_ok=True) self.request_count = 0 self.daily_limit = 100 # 假设每日限制100次请求 def get_cache_key(self, prompt: str, model: str, temperature: float) -> str: """生成缓存键""" content = f"{prompt}_{model}_{temperature}" return hashlib.md5(content.encode()).hexdigest() def get_cached_response(self, cache_key: str) -> Optional[Dict]: """获取缓存响应""" cache_file = self.cache_dir / f"{cache_key}.json" if cache_file.exists(): with open(cache_file, 'r', encoding='utf-8') as f: cached_data = json.load(f) # 检查缓存是否过期(24小时) if time.time() - cached_data['timestamp'] < 86400: return cached_data['response'] return None def cache_response(self, cache_key: str, response: Dict): """缓存响应""" cache_file = self.cache_dir / f"{cache_key}.json" cache_data = { 'timestamp': time.time(), 'response': response } with open(cache_file, 'w', encoding='utf-8') as f: json.dump(cache_data, f, ensure_ascii=False, indent=2) def optimized_request(self, prompt: str, model: str = "claude-3-haiku-20240307", # 使用更经济的模型 temperature: float = 0.3, # 降低随机性 use_cache: bool = True) -> Dict: """优化后的请求方法""" # 检查每日限制 if self.request_count >= self.daily_limit: return {"error": "每日请求次数已达上限"} # 尝试使用缓存 if use_cache: cache_key = self.get_cache_key(prompt, model, temperature) cached_response = self.get_cached_response(cache_key) if cached_response: return {"success": True, "response": cached_response, "cached": True} # 压缩提示词 compressed_prompt = self.compress_prompt(prompt) # 实际API请求 client = anthropic.Anthropic(api_key=self.api_key) try: message = client.messages.create( model=model, max_tokens=512, # 限制输出长度 temperature=temperature, messages=[{"role": "user", "content": compressed_prompt}] ) response_text = message.content[0].text self.request_count += 1 # 缓存结果 if use_cache: self.cache_response(cache_key, response_text) return { "success": True, "response": response_text, "cached": False, "usage": message.usage } except Exception as e: return { "success": False, "error": str(e) } def compress_prompt(self, prompt: str) -> str: """压缩提示词,减少token使用""" # 简单的提示词压缩逻辑 lines = prompt.split('\n') compressed_lines = [] for line in lines: line = line.strip() if line and not line.startswith('#'): # 移除空行和注释 # 移除多余空格 line = ' '.join(line.split()) compressed_lines.append(line) return '\n'.join(compressed_lines) def batch_process(self, prompts: List[str]) -> List[Dict]: """批量处理提示词""" results = [] for prompt in prompts: # 添加延迟避免频繁请求 time.sleep(1) result = self.optimized_request(prompt) results.append(result) return results # 使用示例 optimizer = ClaudeUsageOptimizer("your_api_key") prompts = [ "解释神经网络的基本原理", "写一个Python函数计算素数", "简述深度学习的发展历程" ] results = optimizer.batch_process(prompts) for i, result in enumerate(results): if result["success"]: print(f"提示词{i+1}结果: {result['response'][:100]}...") else: print(f"提示词{i+1}失败: {result['error']}")5.3 移动端适配与语音交互
Claude在移动端的使用体验同样重要。通过优化界面布局和交互方式,可以在手机端获得更好的使用效果。特别是结合语音输入输出功能,可以大幅提升移动端的使用便利性。
以下是一个移动端优化的Web应用示例:
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Claude移动端优化</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f5f5f5; height: 100vh; display: flex; flex-direction: column; } .header { background: #2d3748; color: white; padding: 15px; text-align: center; position: sticky; top: 0; z-index: 100; } .chat-container { flex: 1; overflow-y: auto; padding: 10px; display: flex; flex-direction: column; gap: 10px; } .message { max-width: 85%; padding: 12px; border-radius: 18px; word-wrap: break-word; } .user-message { align-self: flex-end; background: #007acc; color: white; margin-left: auto; } .assistant-message { align-self: flex-start; background: white; border: 1px solid #ddd; } .input-area { padding: 10px; background: white; border-top: 1px solid #ddd; display: flex; gap: 10px; align-items: center; } .text-input { flex: 1; padding: 12px; border: 1px solid #ddd; border-radius: 20px; outline: none; font-size: 16px; } .voice-btn { width: 44px; height: 44px; border-radius: 50%; background: #007acc; color: white; border: none; display: flex; align-items: center; justify-content: center; cursor: pointer; } .send-btn { padding: 12px 20px; background: #007acc; color: white; border: none; border-radius: 20px; cursor: pointer; } @media (max-width: 480px) { .message { max-width: 90%; } .input-area { padding: 8px; } } </style> </head> <body> <div class="header"> <h1>Claude聊天助手</h1> </div> <div class="chat-container" id="chatContainer"> <div class="message assistant-message"> 你好!我是Claude,有什么可以帮你的吗? </div> </div> <div class="input-area"> <button class="voice-btn" id="voiceBtn" title="语音输入"> 🎤 </button> <input type="text" class="text-input" id="textInput" placeholder="输入消息..."> <button class="send-btn" id="sendBtn">发送</button> </div> <script> class MobileClaudeClient { constructor() { this.chatHistory = []; this.isRecording = false; this.recognition = null; this.initVoiceRecognition(); } initVoiceRecognition() { if ('webkitSpeechRecognition' in window || 'SpeechRecognition' in window) { const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition; this.recognition = new SpeechRecognition(); this.recognition.continuous = false; this.recognition.interimResults = false; this.recognition.lang = 'zh-CN'; this.recognition.onresult = (event) => { const transcript = event.results[0][0].transcript; document.getElementById('textInput').value = transcript; this.sendMessage(transcript); }; this.recognition.onerror = (event) => { console.error('语音识别错误:', event.error); }; } } startVoiceRecognition() { if (this.recognition) { this.recognition.start(); this.isRecording = true; document.getElementById('voiceBtn').textContent = '🔴'; } else { alert('您的浏览器不支持