Chatgpt的一些常用指令代码模版可以推荐一些吗?
2024-11-21 阅读 7
当使用ChatGPT时,以下是一些常用的指令代码模板:
1. 连接到ChatGPT API:
```python
import openai
openai.api_key = 'your-api-key'
response = openai.Completion.create(
engine="text-davinci-002",
prompt="Your prompt here",
max_tokens=150
)
print(response.choices[0].text.strip())
```
2. 设置对话历史:
```python
chat_history = [
{"role": "system", "content": "Hello, how can I help you today?"},
{"role": "user", "content": "I need help with my computer."},
{"role": "system", "content": "Sure, I can assist you with that. What seems to be the problem?"}
]
def format_chat_history(history):
formatted_history = ""
for chat in history:
formatted_history += f"{chat['role']}: {chat['content']}\n"
return formatted_history
prompt = format_chat_history(chat_history)
```
3. 生成对话回复:
```python
response = openai.Completion.create(
engine="text-davinci-002",
prompt=prompt,
max_tokens=150
)
print(response.choices[0].text.strip())
```
这些代码模板可以帮助您连接到ChatGPT API,并设置对话历史以生成对话回复。您可以根据需要进行修改和扩展。
更新于 2024年11月24日