Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Este guia mostra como migrar seu código Python da API PaLM para
a API Gemini. É possível gerar mensagens de texto e conversas de várias interações (chat)
com o Gemini, mas não deixe de conferir suas respostas, porque elas podem ser
diferentes das saídas do PaLM.
Resumo das diferenças da API
Os nomes dos métodos foram alterados. Em vez de ter métodos separados para gerar
texto e chat, há um método generate_content que pode fazer os dois.
O Chat tem um método auxiliar start_chat que simplifica o chat.
Em vez de funções autônomas, as novas APIs são métodos do
GenerativeModel.
A estrutura de resposta de saída foi alterada.
As categorias das configurações de segurança mudaram. Consulte a
configurações de segurança para mais detalhes.
Geração de texto: básico
PaLM
Gemini
pipinstallgoogle-generativeaiimportgoogle.generativeaiaspalmimportospalm.configure(api_key=os.environ['API_KEY'])response=palm.generate_text(prompt="The opposite of hot is")print(response.result)# 'cold.'
pipinstallgoogle-generativeaiimportgoogle.generativeaiasgenaiimportosgenai.configure(api_key=os.environ['API_KEY'])model=genai.GenerativeModel(model_name='gemini-pro')response=model.generate_content('The opposite of hot is')print(response.text)# The opposite of hot is cold.'
Geração de texto: parâmetros opcionais
PaLM
Gemini
pipinstallgoogle-generativeaiimportgoogle.generativeaiaspalmimportospalm.configure(api_key=os.environ['API_KEY'])prompt="""You are an expert at solving wordproblems.Solve the following problem:I have three houses, each with threecats. Each cat owns 4 mittens, and a hat.Each mitten was knit from 7m of yarn,each hat from 4m. How much yarn wasneeded to make all the items?Think about it step by step, and showyour work."""completion=palm.generate_text(model=model,prompt=prompt,temperature=0,# The maximum length of responsemax_output_tokens=800,)print(completion.result)
pipinstallgoogle-generativeaiimportgoogle.generativeaiasgenaiimportosgenai.configure(api_key=os.environ['API_KEY'])model=genai.GenerativeModel(model_name='gemini-pro')prompt="""You are an expert at solving wordproblems.Solve the following problem:I have three houses, each with threecats. Each cat owns 4 mittens, and a hat.Each mitten was knit from 7m of yarn,each hat from 4m. How much yarn wasneeded to make all the items?Think about it step by step, and showyour work."""completion=model.generate_content(prompt,generation_config={'temperature':0,'max_output_tokens':800})print(completion.text)
Chat: básico
PaLM
API
pipinstallgoogle-generativeaiimportgoogle.generativeaiaspalmimportospalm.configure(api_key=os.environ['API_KEY'])chat=palm.chat(messages=["Hello."])print(chat.last)# 'Hello! What can I help you with?'chat=chat.reply("Just chillin'")print(chat.last)# 'That's great! ...'
chat.messages[{'author':'0','content':'Hello'},{'author':'1','content':'Hello! How can I help you today?'},{'author':'0','content':"Just chillin'"},{'author':'1','content':"That's great! I'm glad you're able to relax andtakesometimeforyourself.Whatareyouuptotoday?"}]
chat.history[parts{text:"Hello."}role:"user",parts{text:"Greetings! How may I assist you today?"}role:"assistant",parts{text:"Just chillin\'"}role:"user",parts{text:"That\'s great! I\'m glad to hearyou\'re having a relaxing time.MayIofferyouanyvirtualentertainmentorassistance?Icanprovideyouwithmusicrecommendations,playgameswithyou,orengageinafriendlyconversation.\n\nAdditionally,I\'m capable of generatingcreativecontent,suchaspoems,stories,orevensonglyrics.Ifyou\'d like, I can surprise you withsomethingunique.\n\nJustletmeknowwhatyou\'re in the mood for,andI\'ll be happy to oblige."}role:"assistant"]
Chat: temperatura
PaLM
Gemini
# Setting temperature=1 usually produces more zany responses!chat=palm.chat(messages="What should I eat for dinner tonight? List a few options",temperature=1)chat.last'Here are a few ideas ...
model=genai.GenerativeModel(model_name='gemini-pro')chat=model.start_chat()# Setting temperature=1 usually produces more zany responses!response=chat.send_message("What should I eat for dinner tonight? List a few options",generation_config={'temperature':1.0})print(response.text)'1. Grilled Salmon with Roasted Vegetables: ...'
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Não contém as informações de que eu preciso","missingTheInformationINeed","thumb-down"],["Muito complicado / etapas demais","tooComplicatedTooManySteps","thumb-down"],["Desatualizado","outOfDate","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Problema com as amostras / o código","samplesCodeIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 2024-08-23 UTC."],[],[]]